- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
Latest commit
63 lines (50 loc) · 1.88 KB
/
Copy pathmodel.py
File metadata and controls
63 lines (50 loc) · 1.88 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
importpandasaspd
importnumpyasnp
fromsklearn.linear_modelimportLogisticRegression
fromxgboostimportXGBClassifier
fromcatboostimportCatBoostClassifier
fromlightgbmimportLGBMClassifier
fromsklearn.metricsimportaccuracy_score
importjoblib
importos
fromcollectionsimportdefaultdict
fromsklearn.model_selectionimporttrain_test_split
defextract_features_and_labels(csv_path):
df=pd.read_csv(csv_path)
requests=df['number'].tolist()
labels=df['is_cached'].tolist()
freq_counter=defaultdict(int)
features= []
fori, keyinenumerate(requests):
freq_counter[key] +=1
features.append([key, freq_counter[key]])
returnnp.array(features), np.array(labels)
deftrain_and_save_best_model(data_csv, models_dir="models"):
os.makedirs(models_dir, exist_ok=True)
X, y=extract_features_and_labels(data_csv)
X_train, X_test, y_train, y_test=train_test_split(X, y, test_size=0.2, random_state=42)
models= {
"logreg": LogisticRegression(max_iter=1000),
"xgb": XGBClassifier(use_label_encoder=False, eval_metric='logloss'),
"cat": CatBoostClassifier(verbose=0),
"lgbm": LGBMClassifier()
}
best_model_name=None
best_model=None
best_accuracy=0
forname, modelinmodels.items():
print(f"Training {name}")
model.fit(X_train, y_train)
y_pred=model.predict(X_test)
acc=accuracy_score(y_test, y_pred)
print(f"Accuracy of {name}: {acc:.4f}")
ifacc>best_accuracy:
best_accuracy=acc
best_model_name=name
best_model=model
best_path=f"{models_dir}/best_model.pkl"
joblib.dump(best_model, best_path)
print(f"Saved best model ({best_model_name}) to {best_path}")
if__name__=="__main__":
DATA_CSV="data/labeled_requests.csv"
train_and_save_best_model(DATA_CSV)