Add a script for ml classification pipeline.

ml_pipeline
Primoz 2022-11-21 14:47:19 +01:00
parent ae0f54ecc2
commit 40029a8205
2 changed files with 358 additions and 2 deletions

View File

@ -0,0 +1,356 @@
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.0
# kernelspec:
# display_name: straw2analysis
# language: python
# name: straw2analysis
# ---
# %% jupyter={"source_hidden": true}
# %matplotlib inline
import datetime
import importlib
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn import linear_model, svm, naive_bayes, neighbors, tree, ensemble
from sklearn.model_selection import LeaveOneGroupOut, cross_validate
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from lightgbm import LGBMClassifier
import xgboost as xg
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path:
sys.path.append(nb_dir)
import machine_learning.labels
import machine_learning.model
# %% [markdown]
# # RAPIDS models
# %% [markdown]
# ## PANAS negative affect
# %% jupyter={"source_hidden": true}
model_input = pd.read_csv("../data/intradaily_30_min_all_targets/input_JCQ_job_demand_mean.csv")
# %% jupyter={"source_hidden": true}
bins = [-4, -1, 1, 4] # bins for z-scored targets
model_input['target'], edges = pd.cut(model_input.target, bins=bins, labels=['low', 'medium', 'high'], retbins=True, right=False)
model_input['target'].value_counts(), edges
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'].value_counts()
# %% jupyter={"source_hidden": true}
index_columns = ["local_segment", "local_segment_label", "local_segment_start_datetime", "local_segment_end_datetime"]
#if "pid" in model_input.columns:
# index_columns.append("pid")
model_input.set_index(index_columns, inplace=True)
# %% jupyter={"source_hidden": true}
cv_method = '5kfold'
if cv_method == 'logo':
data_x, data_y, data_groups = model_input.drop(["target", "pid"], axis=1), model_input["target"], model_input["pid"]
else:
model_input['pid_index'] = model_input.groupby('pid').cumcount()
model_input['pid_count'] = model_input.groupby('pid')['pid'].transform('count')
model_input["pid_index"] = (model_input['pid_index'] / model_input['pid_count'] + 1).round()
model_input["pid_half"] = model_input["pid"] + "_" + model_input["pid_index"].astype(int).astype(str)
data_x, data_y, data_groups = model_input.drop(["target", "pid", "pid_index", "pid_half"], axis=1), model_input["target"], model_input["pid_half"]
# %% jupyter={"source_hidden": true}
categorical_feature_colnames = ["gender", "startlanguage"]
additional_categorical_features = [] #[col for col in data_x.columns if "mostcommonactivity" in col or "homelabel" in col]
categorical_feature_colnames += additional_categorical_features
categorical_features = data_x[categorical_feature_colnames].copy()
mode_categorical_features = categorical_features.mode().iloc[0]
# fillna with mode
categorical_features = categorical_features.fillna(mode_categorical_features)
# one-hot encoding
categorical_features = categorical_features.apply(lambda col: col.astype("category"))
if not categorical_features.empty:
categorical_features = pd.get_dummies(categorical_features)
numerical_features = data_x.drop(categorical_feature_colnames, axis=1)
train_x = pd.concat([numerical_features, categorical_features], axis=1)
train_x.dtypes
# %% jupyter={"source_hidden": true}
logo = LeaveOneGroupOut()
logo.get_n_splits(
train_x,
data_y,
groups=data_groups,
)
# Defaults to 5 k-folds in cross_validate method
if cv_method != 'logo' and cv_method != 'half_logo':
logo = None
# %% jupyter={"source_hidden": true}
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
# %% [markdown]
# ### Baseline: Dummy Classifier (most frequent)
dummy_class = DummyClassifier(strategy="most_frequent")
# %% jupyter={"source_hidden": true}
dummy_classifier = cross_validate(
dummy_class,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'average_precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(dummy_classifier['test_accuracy']))
print("Precision", np.median(dummy_classifier['test_average_precision']))
print("Recall", np.median(dummy_classifier['test_recall']))
print("F1", np.median(dummy_classifier['test_f1']))
# %% [markdown]
# ### Logistic Regression
# %% jupyter={"source_hidden": true}
logistic_regression = linear_model.LogisticRegression()
# %% jupyter={"source_hidden": true}
log_reg_scores = cross_validate(
logistic_regression,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(log_reg_scores['test_accuracy']))
print("Precision", np.median(log_reg_scores['test_precision']))
print("Recall", np.median(log_reg_scores['test_recall']))
print("F1", np.median(log_reg_scores['test_f1']))
# %% [markdown]
# ### Support Vector Machine
# %% jupyter={"source_hidden": true}
svc = svm.SVC()
# %% jupyter={"source_hidden": true}
svc_scores = cross_validate(
svc,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(svc_scores['test_accuracy']))
print("Precision", np.median(svc_scores['test_precision']))
print("Recall", np.median(svc_scores['test_recall']))
print("F1", np.median(svc_scores['test_f1']))
# %% [markdown]
# ### Gaussian Naive Bayes
# %% jupyter={"source_hidden": true}
gaussian_nb = naive_bayes.GaussianNB()
# %% jupyter={"source_hidden": true}
gaussian_nb_scores = cross_validate(
gaussian_nb,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(gaussian_nb_scores['test_accuracy']))
print("Precision", np.median(gaussian_nb_scores['test_precision']))
print("Recall", np.median(gaussian_nb_scores['test_recall']))
print("F1", np.median(gaussian_nb_scores['test_f1']))
# %% [markdown]
# ### Stochastic Gradient Descent Classifier
# %% jupyter={"source_hidden": true}
sgdc = linear_model.SGDClassifier()
# %% jupyter={"source_hidden": true}
sgdc_scores = cross_validate(
sgdc,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(sgdc_scores['test_accuracy']))
print("Precision", np.median(sgdc_scores['test_precision']))
print("Recall", np.median(sgdc_scores['test_recall']))
print("F1", np.median(sgdc_scores['test_f1']))
# %% [markdown]
# ### K-nearest neighbors
# %% jupyter={"source_hidden": true}
knn = neighbors.KNeighborsClassifier()
# %% jupyter={"source_hidden": true}
knn_scores = cross_validate( # Nekaj ne funkcionira pravilno
knn,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
# error_score='raise'
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(knn_scores['test_accuracy']))
print("Precision", np.median(knn_scores['test_precision']))
print("Recall", np.median(knn_scores['test_recall']))
print("F1", np.median(knn_scores['test_f1']))
# %% [markdown]
# ### Decision Tree
# %% jupyter={"source_hidden": true}
dtree = tree.DecisionTreeClassifier()
# %% jupyter={"source_hidden": true}
dtree_scores = cross_validate(
dtree,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(dtree_scores['test_accuracy']))
print("Precision", np.median(dtree_scores['test_precision']))
print("Recall", np.median(dtree_scores['test_recall']))
print("F1", np.median(dtree_scores['test_f1']))
# %% [markdown]
# ### Random Forest Classifier
# %% jupyter={"source_hidden": true}
rfc = ensemble.RandomForestClassifier()
# %% jupyter={"source_hidden": true}
rfc_scores = cross_validate(
rfc,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(rfc_scores['test_accuracy']))
print("Precision", np.median(rfc_scores['test_precision']))
print("Recall", np.median(rfc_scores['test_recall']))
print("F1", np.median(rfc_scores['test_f1']))
# %% [markdown]
# ### Gradient Boosting Classifier
# %% jupyter={"source_hidden": true}
gbc = ensemble.GradientBoostingClassifier()
# %% jupyter={"source_hidden": true}
gbc_scores = cross_validate(
gbc,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(gbc_scores['test_accuracy']))
print("Precision", np.median(gbc_scores['test_precision']))
print("Recall", np.median(gbc_scores['test_recall']))
print("F1", np.median(gbc_scores['test_f1']))
# %% [markdown]
# ### LGBM Classifier
# %% jupyter={"source_hidden": true}
lgbm = LGBMClassifier()
# %% jupyter={"source_hidden": true}
lgbm_scores = cross_validate(
lgbm,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(lgbm_scores['test_accuracy']))
print("Precision", np.median(lgbm_scores['test_precision']))
print("Recall", np.median(lgbm_scores['test_recall']))
print("F1", np.median(lgbm_scores['test_f1']))
# %% [markdown]
# ### XGBoost Classifier
# %% jupyter={"source_hidden": true}
xgb_classifier = xg.sklearn.XGBClassifier()
# %% jupyter={"source_hidden": true}
xgb_classifier_scores = cross_validate(
xgb_classifier,
X=imputer.fit_transform(train_x),
y=data_y,
groups=data_groups,
cv=logo,
n_jobs=-1,
scoring=('accuracy', 'precision', 'recall', 'f1')
)
# %% jupyter={"source_hidden": true}
print("Acc", np.median(xgb_classifier_scores['test_accuracy']))
print("Precision", np.median(xgb_classifier_scores['test_precision']))
print("Recall", np.median(xgb_classifier_scores['test_recall']))
print("F1", np.median(xgb_classifier_scores['test_f1']))

View File

@ -58,8 +58,8 @@ index_columns = ["local_segment", "local_segment_label", "local_segment_start_da
# index_columns.append("pid")
model_input.set_index(index_columns, inplace=True)
cv_method = '5kfold'
if cv_method == 'half_logo':
cv_method = 'half_logo' # logo, half_logo, 5kfold
if cv_method == 'logo':
data_x, data_y, data_groups = model_input.drop(["target", "pid"], axis=1), model_input["target"], model_input["pid"]
else:
model_input['pid_index'] = model_input.groupby('pid').cumcount()