-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_classifier.py
More file actions
executable file
·375 lines (343 loc) · 10.6 KB
/
train_classifier.py
File metadata and controls
executable file
·375 lines (343 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env python3
"""
Train sklearn classifier using data from generate_dummy_data.py
Creates a trained model file that can be used for classification.
"""
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import pickle
import os
# Training data extracted from generate_dummy_data.py
# Includes EU/Ireland-specific examples
TRAINING_DATA = [
# Food
("McDonald", "food"),
("Starbucks", "food"),
("Pizza Hut", "food"),
("Subway", "food"),
("KFC", "food"),
("Burger King", "food"),
("Taco Bell", "food"),
("Domino's Pizza", "food"),
("Chipotle", "food"),
("Panera Bread", "food"),
("Dunkin'", "food"),
("Olive Garden", "food"),
("Red Lobster", "food"),
("Outback Steakhouse", "food"),
("Buffalo Wild Wings", "food"),
("Restaurant dinner", "food"),
("Lunch meeting", "food"),
("Breakfast", "food"),
("Coffee shop", "food"),
("Food truck", "food"),
("Supermac's", "food"),
("Deliveroo", "food"),
("Just Eat", "food"),
("UberEats", "food"),
("Cafe", "food"),
("Café", "food"),
("Dinner", "food"),
("Lunch", "food"),
("Brunch", "food"),
("Restaurant", "food"),
# Travel
("Uber ride", "travel"),
("Lyft ride", "travel"),
("Taxi", "travel"),
("Train ticket", "travel"),
("Bus fare", "travel"),
("Flight ticket", "travel"),
("Hotel booking", "travel"),
("Airbnb", "travel"),
("Car rental", "travel"),
("Gas station", "travel"),
("Parking fee", "travel"),
("Toll fee", "travel"),
("Metro card", "travel"),
("Bike rental", "travel"),
("Scooter rental", "travel"),
("Luas ticket", "travel"),
("DART fare", "travel"),
("Dublin Bus", "travel"),
("Bus Eireann", "travel"),
("Aer Lingus", "travel"),
("Ryanair flight", "travel"),
("Flight", "travel"),
("Train", "travel"),
("Bus", "travel"),
("Parking", "travel"),
("Petrol", "travel"),
("Gas", "travel"),
# Shopping
("Grocery shopping", "shopping"),
("Target", "shopping"),
("Walmart", "shopping"),
("Amazon order", "shopping"),
("Clothing store", "shopping"),
("Electronics store", "shopping"),
("Bookstore", "shopping"),
("Pharmacy", "shopping"),
("Home Depot", "shopping"),
("Costco", "shopping"),
("Online purchase", "shopping"),
("Gift shop", "shopping"),
("Convenience store", "shopping"),
("Tesco", "shopping"),
("Dunnes Stores", "shopping"),
("SuperValu", "shopping"),
("Aldi", "shopping"),
("Lidl", "shopping"),
("Penneys", "shopping"),
("Primark", "shopping"),
("Boots", "shopping"),
("Superdrug", "shopping"),
("Argos", "shopping"),
("IKEA", "shopping"),
("Shopping", "shopping"),
("Grocery", "shopping"),
("Store", "shopping"),
# Entertainment
("Movie tickets", "entertainment"),
("Concert", "entertainment"),
("Theater show", "entertainment"),
("Museum entry", "entertainment"),
("Amusement park", "entertainment"),
("Bowling", "entertainment"),
("Karaoke", "entertainment"),
("Escape room", "entertainment"),
("Arcade", "entertainment"),
("Sports game", "entertainment"),
("Comedy show", "entertainment"),
("Music festival", "entertainment"),
("Festival tickets", "entertainment"),
("Club entry", "entertainment"),
("Bar drinks", "entertainment"),
("Cinema", "entertainment"),
("Movie", "entertainment"),
("Concert tickets", "entertainment"),
("3Arena", "entertainment"),
("Croke Park", "entertainment"),
("Aviva Stadium", "entertainment"),
("Pub", "entertainment"),
("Bar", "entertainment"),
("Event", "entertainment"),
("Show", "entertainment"),
# Utilities
("Electricity bill", "utilities"),
("Water bill", "utilities"),
("Internet bill", "utilities"),
("Phone bill", "utilities"),
("Gas bill", "utilities"),
("Cable bill", "utilities"),
("Streaming service", "utilities"),
("Insurance", "utilities"),
("Rent", "utilities"),
("Mortgage", "utilities"),
("ESB", "utilities"),
("Eir", "utilities"),
("Vodafone", "utilities"),
("Netflix", "utilities"),
("Spotify", "utilities"),
("Sky TV", "utilities"),
("Virgin Media", "utilities"),
("Bill", "utilities"),
("Subscription", "utilities"),
("Service", "utilities"),
# Other
("Gym membership", "other"),
("Gym class", "other"),
("Yoga class", "other"),
("Personal trainer", "other"),
("Doctor visit", "other"),
("Pharmacy", "other"),
("Dry cleaning", "other"),
("Laundry", "other"),
("Haircut", "other"),
("Spa", "other"),
("Massage", "other"),
("Car repair", "other"),
("Car wash", "other"),
("Pet supplies", "other"),
("Veterinary", "other"),
("Donation", "other"),
("Gym", "other"),
("Doctor", "other"),
# Additional variations for better training
# Food variations
("McDonald's", "food"),
("McDonalds", "food"),
("Coffee", "food"),
("Tea", "food"),
("Snacks", "food"),
("Fast food", "food"),
("Takeaway", "food"),
("Food delivery", "food"),
("Restaurant meal", "food"),
("Dining out", "food"),
("Lunch break", "food"),
("Dinner date", "food"),
("Breakfast meeting", "food"),
("Food court", "food"),
("Bakery", "food"),
("Pizzeria", "food"),
("Bistro", "food"),
# Travel variations
("Ride", "travel"),
("Transport", "travel"),
("Commute", "travel"),
("Journey", "travel"),
("Trip", "travel"),
("Travel", "travel"),
("Transportation", "travel"),
("Airport", "travel"),
("Station", "travel"),
("Taxi fare", "travel"),
("Uber trip", "travel"),
("Train journey", "travel"),
("Bus ride", "travel"),
("Plane ticket", "travel"),
("Hotel stay", "travel"),
("Accommodation", "travel"),
("Car hire", "travel"),
("Vehicle rental", "travel"),
("Fuel", "travel"),
("Petrol station", "travel"),
("Gas pump", "travel"),
("Toll road", "travel"),
("Parking lot", "travel"),
# Shopping variations
("Shop", "shopping"),
("Retail", "shopping"),
("Purchase", "shopping"),
("Buy", "shopping"),
("Shopping trip", "shopping"),
("Grocery store", "shopping"),
("Supermarket", "shopping"),
("Market", "shopping"),
("Online shopping", "shopping"),
("E-commerce", "shopping"),
("Retail store", "shopping"),
("Department store", "shopping"),
("Clothing", "shopping"),
("Electronics", "shopping"),
("Books", "shopping"),
("Medicine", "shopping"),
("Drugstore", "shopping"),
("Convenience", "shopping"),
# Entertainment variations
("Entertainment", "entertainment"),
("Fun", "entertainment"),
("Leisure", "entertainment"),
("Recreation", "entertainment"),
("Movies", "entertainment"),
("Cinema tickets", "entertainment"),
("Film", "entertainment"),
("Performance", "entertainment"),
("Music", "entertainment"),
("Gig", "entertainment"),
("Event tickets", "entertainment"),
("Sports event", "entertainment"),
("Match", "entertainment"),
("Game tickets", "entertainment"),
("Attraction", "entertainment"),
("Theme park", "entertainment"),
("Activity", "entertainment"),
("Night out", "entertainment"),
("Drinks", "entertainment"),
# Utilities variations
("Utility", "utilities"),
("Utilities", "utilities"),
("Bills", "utilities"),
("Monthly bill", "utilities"),
("Electric", "utilities"),
("Power", "utilities"),
("Water supply", "utilities"),
("Internet service", "utilities"),
("WiFi", "utilities"),
("Broadband", "utilities"),
("Phone service", "utilities"),
("Mobile plan", "utilities"),
("Cable TV", "utilities"),
("TV subscription", "utilities"),
("Streaming", "utilities"),
("Video streaming", "utilities"),
("Music streaming", "utilities"),
("Insurance premium", "utilities"),
("Rent payment", "utilities"),
("Housing", "utilities"),
("Mortgage payment", "utilities"),
]
def train_model():
"""Train the sklearn classifier model."""
print("="*70)
print("Training Expense Classifier with sklearn")
print("="*70)
# Prepare data
X = [item[0] for item in TRAINING_DATA]
y = [item[1] for item in TRAINING_DATA]
print(f"\nTraining data: {len(X)} examples")
print(f"Categories: {set(y)}")
# Split into train/test (80/20)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"\nTraining set: {len(X_train)} examples")
print(f"Test set: {len(X_test)} examples")
# Create pipeline: TF-IDF vectorization + Naive Bayes classifier
print("\nTraining model...")
model = Pipeline([
('tfidf', TfidfVectorizer(
lowercase=True,
ngram_range=(1, 2), # Use unigrams and bigrams
max_features=5000,
min_df=1,
max_df=0.95
)),
('clf', MultinomialNB(alpha=1.0)) # Laplace smoothing
])
# Train
model.fit(X_train, y_train)
# Test
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"\n✓ Model trained!")
print(f"✓ Test accuracy: {accuracy:.2%}")
# Show detailed results
print("\n" + "="*70)
print("Classification Report:")
print("="*70)
print(classification_report(y_test, y_pred))
# Save model
model_path = 'expense_classifier_model.pkl'
with open(model_path, 'wb') as f:
pickle.dump(model, f)
file_size = os.path.getsize(model_path) / (1024 * 1024) # Size in MB
print(f"\n✓ Model saved to: {model_path}")
print(f"✓ Model size: {file_size:.2f} MB")
# Test some examples
print("\n" + "="*70)
print("Testing Examples:")
print("="*70)
test_examples = [
"McDonald",
"Luas ticket",
"Tesco shopping",
"Netflix subscription",
"Movie tickets",
"ESB bill"
]
for example in test_examples:
prediction = model.predict([example])[0]
proba = model.predict_proba([example])[0]
max_proba = max(proba)
print(f"{example:30} → {prediction:15} (confidence: {max_proba:.2%})")
print("\n" + "="*70)
print("Training complete!")
print("="*70)
return model
if __name__ == "__main__":
train_model()