10. Naive Bayes
- Gaussian Naive Bayes
- Preparing data
- Running baseline model
- Finding optimal hyperparameters
- Comparing results
- Visualising feature importance
- Exporting
We run our fifth ML model, a naive bayes, first with default parameters, then we attempt to tune hyperparameters to improve it. We also visualise various accuracy scores, the confusion matrix and the ROC curve. We end by dumping our best model for further comparison.
%run /Users/thomasadler/Desktop/futuristic-platipus/capstone/notebooks/ta_01_packages_functions.py
modelling_df=pd.read_csv(data_filepath + 'master_modelling_df.csv', index_col=0)
#check
modelling_df.info()
Image(dictionary_filepath+"5-Modelling-Data-Dictionary.png")
X =modelling_df.loc[:, modelling_df.columns != 'is_functioning']
y = modelling_df['is_functioning']
#check
print(X.shape)
print(y.shape)
Our independent variable (X) should have the same number of rows (107,184) than our dependent variable (y). y should only have one column as it is the outcome variable.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=rand_seed)
sm = SMOTE(random_state=rand_seed)
X_train_res, y_train_res = sm.fit_resample(X_train, y_train)
#compre resampled dataset
print(f"Test set has {round(y_test.value_counts(normalize=True)[0]*100,1)}% non-functioning water points and {round(y_test.value_counts(normalize=True)[1]*100,1)}% functioning")
print(f"Original train set has {round(y_train.value_counts(normalize=True)[0]*100,1)}% non-functioning water points and {round(y_train.value_counts(normalize=True)[1]*100,1)}% functioning")
print(f"Resampled train set has {round(y_train_res.value_counts(normalize=True)[0]*100,1)}% non-functioning water points and {round(y_train_res.value_counts(normalize=True)[1]*100,1)}% functioning")
We over-sample the minority class, non-functioning water points, to get an equal distribution of our outcome variable. Note this should be done on the train set and not the test set as we should not tinker with the latter.
Note that we do not scale our data because the estimator in a Gaussian Naive Bayes computes the mean and standard deviation of a feature, then assumes that this feature follows a Normal distribution. It then uses the distance of each observation from the mean of that distribution to calculate the conditional probability of that observation with that feature value to be in a certain class.
start=time.time()
#instantiate and fit
GNB_base = GaussianNB().fit(X_train_res, y_train_res)
end=time.time()
time_fit_base=end-start
print(f"Time to fit the model on the training set is {round(time_fit_base,3)} seconds")
We use a Gaussian Naive Bayes as it can deal with our features being continuous variables.
fpr_train_base, tpr_train_base, roc_auc_train_base, precision_train_base_plot, recall_train_base_plot, pr_auc_train_base, time_predict_train_base = print_report(GNB_base, X_train_res, y_train_res)
#storing accuracy scores
accuracy_train_base, precision_train_base, recall_train_base, f1_train_base = get_scores(GNB_base, X_train_res, y_train_res)
Our training set has a relatively low accuracy metrics. It has an especially high number of False Positives.
fpr_test_base, tpr_test_base, roc_auc_test_base, precision_test_base_plot, recall_test_base_plot, pr_auc_test_base, time_predict_test_base = print_report(GNB_base, X_test, y_test)
print(f"Time to predict the outcome variable for the test set is {round(time_predict_test_base,3)} seconds")
#storing accuracy scores
accuracy_test_base, precision_test_base, recall_test_base, f1_test_base = get_scores(GNB_base, X_test, y_test)
Suprisingly our test set has a better accuracy score of 64%. However, it achieves this by having a very low precision score for non-functioning points. It mislabelled a lot of functioning points as non-functioning.
We run a grid search cross validation through a pipeline to find the optimal hyperparameters. The grid search looks at every combination of hyperparameters to find the one with the best cross-validation score.
# setting up which models/scalers we want to grid search
estimator = [('reduce_dim', PCA()),
('GNB', GaussianNB())]
# defining distribution of parameters we want to compare
param = {'reduce_dim__n_components': [0.5, 0.6, 0.7, 0.8, 0.9, None]}
# run cross validation
pipeline_cross_val_grid(estimator, param, X_train_res, y_train_res, X_test, y_test)
We only test dimensionality reduction using PCA, and the best model is where we do not apply it. As a result, we do not have an optimised model to compare with, as the baseline was already the best we could find.
plt.plot(figsize=(10,15))
plt.plot([0,1], [0,1], color='black', linestyle='--')
plt.title('Receiver Operating Characteristic (ROC) Curve - GNB')
plt.plot(fpr_train_base, tpr_train_base, color='blueviolet', lw=2,
label='Train AUC = %0.2f' % roc_auc_train_base)
plt.plot(fpr_test_base, tpr_test_base, color='crimson', lw=2,
label='Test AUC = %0.2f' % roc_auc_test_base)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc="best")
plt.tight_layout()
plt.grid()
Overall, although the test has a better accuracy score than the train set, it has a lower AUC. This is because when we look at various thresholds, the training set still performs better on the whole. It seems that the test set performed especially well for the specific threshold level we looked at.
imps = permutation_importance(GNB_base, X_test, y_test)
#visualising coefficient importance
coeff_bar_chart(imps.importances_mean, X.columns, t=False)
We see that water points which are installed after 2006 and those that are in regions with a high rate of access to toilets increases the probability of that water point functioning.
It is peculiar, however, that high rates of electricity access, bank account ownership and house ownership are associated with a water point not functioning. This may show the limitation of naive bayes in taking into many other features at the same time to identify patterns in the data.
Similarly to previous models the number of conflicts/violent events are not very important in our model.
Image(dictionary_filepath+"6-Hypotheses.png")
joblib.dump(GNB_base, model_filepath+'gaussian_naive_bayes_model.sav')
d = {'Model':['Gaussian Naive Bayes'], 'Parameters':[''], 'Accuracy Train': [accuracy_train_base],\
'Precision Train': [precision_train_base], 'Recall Train': [recall_train_base], 'F1 Train': [f1_train_base], 'ROC AUC Train':[roc_auc_train_base],\
'Accuracy Test': accuracy_test_base, 'Precision Test': [precision_test_base], 'Recall Test': [recall_test_base], 'F1 Test': [f1_test_base],\
'ROC AUC Test':[roc_auc_test_base],'Time Fit': time_fit_base,\
'Time Predict': time_predict_test_base, "Precision Non-functioning Test":0.27, "Recall Non-functioning Test":0.47,\
"F1 Non-functioning Test":0.34, "Precision Functioning Test":0.84, "Recall Functioning Test":0.69,"F1 Functioning Test":0.75}
#to dataframe
best_model_result_df=pd.DataFrame(data=d)
#check
best_model_result_df
best_model_result_df.to_csv(model_filepath + 'gaussian_naive_bayes_model.csv')
metrics=[fpr_train_base, tpr_train_base, fpr_test_base, tpr_test_base]
metrics_name=['fpr_train_base', 'tpr_train_base', 'fpr_test_base', 'tpr_test_base']
#save numpy arrays for model comparison
for metric, metric_name in zip(metrics, metrics_name):
np.save(model_filepath+f'gaussian_naive_bayes_{metric_name}', metric)