Automize clustering classification logic and add parameters at the begining of the scripts. General changes and improvements.

ml_pipeline
Primoz 2022-11-24 16:12:20 +01:00
parent ddde80b421
commit 218b684514
2 changed files with 164 additions and 113 deletions

View File

@ -46,7 +46,9 @@ import machine_learning.model
# # RAPIDS models # # RAPIDS models
# %% [markdown] # %% [markdown]
# ## PANAS negative affect # ## Set script's parameters
cv_method_str = 'logo' # logo, halflogo, 5kfold # Cross-validation method (could be regarded as a hyperparameter)
n_sl = 1 # Number of largest/smallest accuracies (of particular CV) outputs
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
model_input = pd.read_csv("../data/intradaily_30_min_all_targets/input_JCQ_job_demand_mean.csv") model_input = pd.read_csv("../data/intradaily_30_min_all_targets/input_JCQ_job_demand_mean.csv")
@ -57,14 +59,13 @@ model_input.set_index(index_columns, inplace=True)
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
bins = [-10, -1, 1, 10] # bins for z-scored targets bins = [-10, -1, 1, 10] # bins for z-scored targets
model_input['target'], edges = pd.cut(model_input.target, bins=bins, labels=['low', 'medium', 'high'], retbins=True, right=False) #['low', 'medium', 'high'] model_input['target'], edges = pd.cut(model_input.target, bins=bins, labels=['low', 'medium', 'high'], retbins=True, right=True) #['low', 'medium', 'high']
model_input['target'].value_counts(), edges model_input['target'].value_counts(), edges
model_input = model_input[model_input['target'] != "medium"] model_input = model_input[model_input['target'] != "medium"]
model_input['target'] = model_input['target'].astype(str).apply(lambda x: 0 if x == "low" else 1) model_input['target'] = model_input['target'].astype(str).apply(lambda x: 0 if x == "low" else 1)
model_input['target'].value_counts() model_input['target'].value_counts()
cv_method_str = 'logo' # logo, halflogo, 5kfold
if cv_method_str == 'halflogo': if cv_method_str == 'halflogo':
model_input['pid_index'] = model_input.groupby('pid').cumcount() model_input['pid_index'] = model_input.groupby('pid').cumcount()
model_input['pid_count'] = model_input.groupby('pid')['pid'].transform('count') model_input['pid_count'] = model_input.groupby('pid')['pid'].transform('count')
@ -106,10 +107,6 @@ if cv_method_str == 'logo' or cv_method_str == 'half_logo':
data_y, data_y,
groups=data_groups, groups=data_groups,
) )
# %% jupyter={"source_hidden": true}
# %% [markdown]
# ### Set n for nlargest and nsmallest
n = 5
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
imputer = SimpleImputer(missing_values=np.nan, strategy='median') imputer = SimpleImputer(missing_values=np.nan, strategy='median')
@ -130,12 +127,12 @@ dummy_classifier = cross_validate(
scoring=('accuracy', 'average_precision', 'recall', 'f1') scoring=('accuracy', 'average_precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(dummy_classifier['test_accuracy'])) print("Acc", np.mean(dummy_classifier['test_accuracy']))
print("Precision", np.median(dummy_classifier['test_average_precision'])) print("Precision", np.mean(dummy_classifier['test_average_precision']))
print("Recall", np.median(dummy_classifier['test_recall'])) print("Recall", np.mean(dummy_classifier['test_recall']))
print("F1", np.median(dummy_classifier['test_f1'])) print("F1", np.mean(dummy_classifier['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-dummy_classifier['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-dummy_classifier['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(dummy_classifier['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(dummy_classifier['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Logistic Regression # ### Logistic Regression
@ -154,12 +151,12 @@ log_reg_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(log_reg_scores['test_accuracy'])) print("Acc", np.mean(log_reg_scores['test_accuracy']))
print("Precision", np.median(log_reg_scores['test_precision'])) print("Precision", np.mean(log_reg_scores['test_precision']))
print("Recall", np.median(log_reg_scores['test_recall'])) print("Recall", np.mean(log_reg_scores['test_recall']))
print("F1", np.median(log_reg_scores['test_f1'])) print("F1", np.mean(log_reg_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-log_reg_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-log_reg_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(log_reg_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(log_reg_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Support Vector Machine # ### Support Vector Machine
@ -178,12 +175,12 @@ svc_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(svc_scores['test_accuracy'])) print("Acc", np.mean(svc_scores['test_accuracy']))
print("Precision", np.median(svc_scores['test_precision'])) print("Precision", np.mean(svc_scores['test_precision']))
print("Recall", np.median(svc_scores['test_recall'])) print("Recall", np.mean(svc_scores['test_recall']))
print("F1", np.median(svc_scores['test_f1'])) print("F1", np.mean(svc_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-svc_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-svc_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(svc_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(svc_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Gaussian Naive Bayes # ### Gaussian Naive Bayes
@ -203,12 +200,12 @@ gaussian_nb_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(gaussian_nb_scores['test_accuracy'])) print("Acc", np.mean(gaussian_nb_scores['test_accuracy']))
print("Precision", np.median(gaussian_nb_scores['test_precision'])) print("Precision", np.mean(gaussian_nb_scores['test_precision']))
print("Recall", np.median(gaussian_nb_scores['test_recall'])) print("Recall", np.mean(gaussian_nb_scores['test_recall']))
print("F1", np.median(gaussian_nb_scores['test_f1'])) print("F1", np.mean(gaussian_nb_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-gaussian_nb_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-gaussian_nb_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(gaussian_nb_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(gaussian_nb_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Stochastic Gradient Descent Classifier # ### Stochastic Gradient Descent Classifier
@ -228,12 +225,12 @@ sgdc_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(sgdc_scores['test_accuracy'])) print("Acc", np.mean(sgdc_scores['test_accuracy']))
print("Precision", np.median(sgdc_scores['test_precision'])) print("Precision", np.mean(sgdc_scores['test_precision']))
print("Recall", np.median(sgdc_scores['test_recall'])) print("Recall", np.mean(sgdc_scores['test_recall']))
print("F1", np.median(sgdc_scores['test_f1'])) print("F1", np.mean(sgdc_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-sgdc_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-sgdc_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(sgdc_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(sgdc_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### K-nearest neighbors # ### K-nearest neighbors
@ -253,12 +250,12 @@ knn_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(knn_scores['test_accuracy'])) print("Acc", np.mean(knn_scores['test_accuracy']))
print("Precision", np.median(knn_scores['test_precision'])) print("Precision", np.mean(knn_scores['test_precision']))
print("Recall", np.median(knn_scores['test_recall'])) print("Recall", np.mean(knn_scores['test_recall']))
print("F1", np.median(knn_scores['test_f1'])) print("F1", np.mean(knn_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-knn_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-knn_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(knn_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(knn_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Decision Tree # ### Decision Tree
@ -278,12 +275,12 @@ dtree_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(dtree_scores['test_accuracy'])) print("Acc", np.mean(dtree_scores['test_accuracy']))
print("Precision", np.median(dtree_scores['test_precision'])) print("Precision", np.mean(dtree_scores['test_precision']))
print("Recall", np.median(dtree_scores['test_recall'])) print("Recall", np.mean(dtree_scores['test_recall']))
print("F1", np.median(dtree_scores['test_f1'])) print("F1", np.mean(dtree_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-dtree_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-dtree_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(dtree_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(dtree_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Random Forest Classifier # ### Random Forest Classifier
@ -303,12 +300,12 @@ rfc_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(rfc_scores['test_accuracy'])) print("Acc", np.mean(rfc_scores['test_accuracy']))
print("Precision", np.median(rfc_scores['test_precision'])) print("Precision", np.mean(rfc_scores['test_precision']))
print("Recall", np.median(rfc_scores['test_recall'])) print("Recall", np.mean(rfc_scores['test_recall']))
print("F1", np.median(rfc_scores['test_f1'])) print("F1", np.mean(rfc_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-rfc_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-rfc_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(rfc_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(rfc_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### Gradient Boosting Classifier # ### Gradient Boosting Classifier
@ -328,12 +325,12 @@ gbc_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(gbc_scores['test_accuracy'])) print("Acc", np.mean(gbc_scores['test_accuracy']))
print("Precision", np.median(gbc_scores['test_precision'])) print("Precision", np.mean(gbc_scores['test_precision']))
print("Recall", np.median(gbc_scores['test_recall'])) print("Recall", np.mean(gbc_scores['test_recall']))
print("F1", np.median(gbc_scores['test_f1'])) print("F1", np.mean(gbc_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-gbc_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-gbc_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(gbc_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(gbc_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### LGBM Classifier # ### LGBM Classifier
@ -353,12 +350,12 @@ lgbm_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(lgbm_scores['test_accuracy'])) print("Acc", np.mean(lgbm_scores['test_accuracy']))
print("Precision", np.median(lgbm_scores['test_precision'])) print("Precision", np.mean(lgbm_scores['test_precision']))
print("Recall", np.median(lgbm_scores['test_recall'])) print("Recall", np.mean(lgbm_scores['test_recall']))
print("F1", np.median(lgbm_scores['test_f1'])) print("F1", np.mean(lgbm_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-lgbm_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-lgbm_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(lgbm_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(lgbm_scores['test_accuracy'], n_sl)[:n_sl]))
# %% [markdown] # %% [markdown]
# ### XGBoost Classifier # ### XGBoost Classifier
@ -378,9 +375,9 @@ xgb_classifier_scores = cross_validate(
scoring=('accuracy', 'precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
print("Acc", np.median(xgb_classifier_scores['test_accuracy'])) print("Acc", np.mean(xgb_classifier_scores['test_accuracy']))
print("Precision", np.median(xgb_classifier_scores['test_precision'])) print("Precision", np.mean(xgb_classifier_scores['test_precision']))
print("Recall", np.median(xgb_classifier_scores['test_recall'])) print("Recall", np.mean(xgb_classifier_scores['test_recall']))
print("F1", np.median(xgb_classifier_scores['test_f1'])) print("F1", np.mean(xgb_classifier_scores['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-xgb_classifier_scores['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-xgb_classifier_scores['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(xgb_classifier_scores['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(xgb_classifier_scores['test_accuracy'], n_sl)[:n_sl]))

View File

@ -49,26 +49,38 @@ import machine_learning.model
# # RAPIDS models # # RAPIDS models
# %% [markdown] # %% [markdown]
# ## PANAS negative affect # ## Set script's parameters
n_clusters = 5 # Number of clusters (could be regarded as a hyperparameter)
cv_method_str = 'logo' # logo, halflogo, 5kfold # Cross-validation method (could be regarded as a hyperparameter)
n_sl = 1 # Number of largest/smallest accuracies (of particular CV) outputs
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
model_input = pd.read_csv("../data/intradaily_30_min_all_targets/input_JCQ_job_demand_mean.csv") model_input = pd.read_csv("../data/intradaily_30_min_all_targets/input_JCQ_job_demand_mean.csv")
index_columns = ["local_segment", "local_segment_label", "local_segment_start_datetime", "local_segment_end_datetime"]
lime_cols = [col for col in model_input if col.startswith('limesurvey_demand')] clust_col = model_input.set_index(index_columns).var().idxmax() # age is a col with the highest variance
model_input.columns[list(model_input.columns).index('age'):-1]
lime_cols = [col for col in model_input if col.startswith('limesurvey')]
lime_cols
lime_col = 'limesurvey_demand_control_ratio' lime_col = 'limesurvey_demand_control_ratio'
model_input[lime_col].describe() clust_col = lime_col
model_input[clust_col].describe()
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
# Filter-out outlier rows by lime_col # Filter-out outlier rows by clust_col
model_input = model_input[(np.abs(stats.zscore(model_input[lime_col])) < 3)] model_input = model_input[(np.abs(stats.zscore(model_input[clust_col])) < 3)]
uniq = model_input[[lime_col, 'pid']].drop_duplicates().reset_index(drop=True) uniq = model_input[[clust_col, 'pid']].drop_duplicates().reset_index(drop=True)
plt.bar(uniq['pid'], uniq[lime_col]) plt.bar(uniq['pid'], uniq[clust_col])
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
# Get clusters by lime col & and merge the clusters to main df # Get clusters by cluster col & and merge the clusters to main df
km = KMeans(n_clusters=5).fit_predict(uniq.set_index('pid')) km = KMeans(n_clusters=n_clusters).fit_predict(uniq.set_index('pid'))
np.unique(km, return_counts=True) np.unique(km, return_counts=True)
uniq['cluster'] = km uniq['cluster'] = km
uniq uniq
@ -76,12 +88,59 @@ uniq
model_input = model_input.merge(uniq[['pid', 'cluster']]) model_input = model_input.merge(uniq[['pid', 'cluster']])
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
index_columns = ["local_segment", "local_segment_label", "local_segment_start_datetime", "local_segment_end_datetime"]
model_input.set_index(index_columns, inplace=True) model_input.set_index(index_columns, inplace=True)
# %% jupyter={"source_hidden": true} # %% jupyter={"source_hidden": true}
# Create dict with classification ml models
cmodels = {
'dummy_classifier': {
'model': DummyClassifier(strategy="most_frequent"),
'metrics': [0, 0, 0, 0]
},
'logistic_regression': {
'model': linear_model.LogisticRegression(),
'metrics': [0, 0, 0, 0]
},
'support_vector_machine': {
'model': svm.SVC(),
'metrics': [0, 0, 0, 0]
},
'gaussian_naive_bayes': {
'model': naive_bayes.GaussianNB(),
'metrics': [0, 0, 0, 0]
},
'stochastic_gradient_descent_classifier': {
'model': linear_model.SGDClassifier(),
'metrics': [0, 0, 0, 0]
},
'knn': {
'model': neighbors.KNeighborsClassifier(),
'metrics': [0, 0, 0, 0]
},
'decision_tree': {
'model': tree.DecisionTreeClassifier(),
'metrics': [0, 0, 0, 0]
},
'random_forest_classifier': {
'model': ensemble.RandomForestClassifier(),
'metrics': [0, 0, 0, 0]
},
'gradient_boosting_classifier': {
'model': ensemble.GradientBoostingClassifier(),
'metrics': [0, 0, 0, 0]
},
'lgbm_classifier': {
'model': LGBMClassifier(),
'metrics': [0, 0, 0, 0]
},
'XGBoost_classifier': {
'model': xg.sklearn.XGBClassifier(),
'metrics': [0, 0, 0, 0]
}
}
for k in range(5): # %% jupyter={"source_hidden": true}
for k in range(n_clusters):
model_input_subset = model_input[model_input["cluster"] == k].copy() model_input_subset = model_input[model_input["cluster"] == k].copy()
bins = [-10, -1, 1, 10] # bins for z-scored targets bins = [-10, -1, 1, 10] # bins for z-scored targets
model_input_subset.loc[:, 'target'] = \ model_input_subset.loc[:, 'target'] = \
@ -92,8 +151,6 @@ for k in range(5):
model_input_subset['target'].value_counts() model_input_subset['target'].value_counts()
cv_method_str = 'logo' # logo, halflogo, 5kfold
if cv_method_str == 'halflogo': if cv_method_str == 'halflogo':
model_input_subset['pid_index'] = model_input_subset.groupby('pid').cumcount() model_input_subset['pid_index'] = model_input_subset.groupby('pid').cumcount()
model_input_subset['pid_count'] = model_input_subset.groupby('pid')['pid'].transform('count') model_input_subset['pid_count'] = model_input_subset.groupby('pid')['pid'].transform('count')
@ -134,45 +191,42 @@ for k in range(5):
groups=data_groups, groups=data_groups,
) )
n = 3
imputer = SimpleImputer(missing_values=np.nan, strategy='median') imputer = SimpleImputer(missing_values=np.nan, strategy='median')
# Create dict with classification ml models
cmodels = {
'dummy_classifier': DummyClassifier(strategy="most_frequent"),
'logistic_regression': linear_model.LogisticRegression(),
'support_vector_machine': svm.SVC(),
'gaussian_naive_bayes': naive_bayes.GaussianNB(),
'stochastic_gradient_descent_classifier': linear_model.SGDClassifier(),
'knn': neighbors.KNeighborsClassifier(),
'decision_tree': tree.DecisionTreeClassifier(),
'random_forest_classifier': ensemble.RandomForestClassifier(),
'gradient_boosting_classifier': ensemble.GradientBoostingClassifier(),
'lgbm_classifier': LGBMClassifier(),
'XGBoost_classifier': xg.sklearn.XGBClassifier()
}
for model_title, model in cmodels.items(): for model_title, model in cmodels.items():
classifier = cross_validate( classifier = cross_validate(
model, model['model'],
X=imputer.fit_transform(train_x), X=imputer.fit_transform(train_x),
y=data_y, y=data_y,
groups=data_groups, groups=data_groups,
cv=cv_method, cv=cv_method,
n_jobs=-1, n_jobs=-1,
error_score='raise', error_score='raise',
scoring=('accuracy', 'average_precision', 'recall', 'f1') scoring=('accuracy', 'precision', 'recall', 'f1')
) )
print("\n-------------------------------------\n") print("\n-------------------------------------\n")
print("Current cluster:", k, end="\n") print("Current cluster:", k, end="\n")
print("Current model:", model_title, end="\n") print("Current model:", model_title, end="\n")
print("Acc", np.median(classifier['test_accuracy'])) print("Acc", np.mean(classifier['test_accuracy']))
print("Precision", np.median(classifier['test_average_precision'])) print("Precision", np.mean(classifier['test_precision']))
print("Recall", np.median(classifier['test_recall'])) print("Recall", np.mean(classifier['test_recall']))
print("F1", np.median(classifier['test_f1'])) print("F1", np.mean(classifier['test_f1']))
print("Largest 5 ACC:", np.sort(-np.partition(-classifier['test_accuracy'], n)[:n])[::-1]) print(f"Largest {n_sl} ACC:", np.sort(-np.partition(-classifier['test_accuracy'], n_sl)[:n_sl])[::-1])
print("Smallest 5 ACC:", np.sort(np.partition(classifier['test_accuracy'], n)[:n])) print(f"Smallest {n_sl} ACC:", np.sort(np.partition(classifier['test_accuracy'], n_sl)[:n_sl]))
# %%
cmodels[model_title]['metrics'][0] += np.mean(classifier['test_accuracy'])
cmodels[model_title]['metrics'][1] += np.mean(classifier['test_precision'])
cmodels[model_title]['metrics'][2] += np.mean(classifier['test_accuracy'])
cmodels[model_title]['metrics'][3] += np.mean(classifier['test_f1'])
# %% jupyter={"source_hidden": true}
# Get overall results
for model_title, model in cmodels.items():
print("\n************************************\n")
print("Current model:", model_title, end="\n")
print("Acc", model['metrics'][0]/n_clusters)
print("Precision", model['metrics'][1]/n_clusters)
print("Recall", model['metrics'][2]/n_clusters)
print("F1", model['metrics'][3]/n_clusters)