Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #####################################################################################################################
- # 20165443 Sanzhar Askaruly
- # Advanced Machine Learning
- #####################################################################################################################
- #####################################################################################################################
- # Including libraries
- #####################################################################################################################
- # Basic libraries
- import numpy as np
- import pandas as pd
- import sklearn
- import random
- import matplotlib
- import matplotlib.pyplot as plt
- import utils
- # Models
- from sklearn import linear_model, datasets
- from sklearn import tree
- from sklearn.naive_bayes import GaussianNB
- from sklearn.neural_network import MLPClassifier
- # Model Evaluation
- from sklearn.model_selection import train_test_split
- from sklearn.model_selection import cross_val_score
- from sklearn import metrics
- #####################################################################################################################
- # File input
- #####################################################################################################################
- filename1 = 'dataset/eyerim_dataset.csv'
- filename2 = 'dataset/cheek_dataset.csv'
- filename3 = 'dataset/forearm_dataset.csv'
- data = pd.read_csv(filename1)
- #####################################################################################################################
- # Preprocessing
- #####################################################################################################################
- #matrix_data = data.as_matrix()
- #X = matrix_data[:,2]
- #X_reshape = X.reshape(-1, 1)
- #Y = matrix_data[:,-1]
- matrix_data = data.as_matrix()
- X = matrix_data[:,0:8]
- #X_reshape = X.reshape(-1, 1)
- X_reshape = X
- Y = matrix_data[:,8]
- #print(matrix_data)
- #print(Y)
- #####################################################################################################################
- # Modeling
- #####################################################################################################################
- logreg = linear_model.LogisticRegression(C=1e5)
- dec_tree = tree.DecisionTreeClassifier()
- gauss_nb = GaussianNB()
- neur_net = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
- #####################################################################################################################
- # Training set
- #####################################################################################################################
- logreg_model = logreg.fit(X_reshape, Y)
- dec_tree_model = dec_tree.fit(X_reshape, Y)
- gauss_nb_model = gauss_nb.fit(X_reshape, Y)
- neur_net_model = neur_net.fit(X_reshape, Y)
- #####################################################################################################################
- # Printing training set scores
- #####################################################################################################################
- logreg_model_score = logreg_model.score(X_reshape, Y)
- dec_tree_model_score = dec_tree_model.score(X_reshape, Y)
- gauss_nb_model_score = gauss_nb_model.score(X_reshape, Y)
- neur_net_model_score = neur_net_model.score(X_reshape, Y)
- model_dict = {'Logistic Regression': logreg_model_score, 'Decision Tree': dec_tree_model_score, \
- 'Naive Bayes': gauss_nb_model_score, 'Neural Network': neur_net_model_score}
- max_mddel_dict = max(model_dict, key=model_dict.get)
- '''
- print("Training Set Model Information:\n")
- for key, value in model_dict.items() :
- print (key, value)
- '''
- print("\nTraining model with maximum score: {} - {}".format(max_mddel_dict, model_dict[max_mddel_dict]))
- #####################################################################################################################
- # Printing validation (with ratio 0.3) set model scores
- #####################################################################################################################
- X_train, X_test, y_train, y_test = train_test_split(X_reshape, Y, test_size=0.3, random_state=0)
- logreg_model_valid = logreg_model.fit(X_train, y_train)
- dec_tree_model_valid = dec_tree_model.fit(X_train, y_train)
- gauss_nb_model_valid = gauss_nb_model.fit(X_train, y_train)
- neur_net_model_valid = neur_net_model.fit(X_train, y_train)
- #####################################################################################################################
- # Printing validation model scores
- #####################################################################################################################
- logreg_model_valid_score = logreg_model_valid.score(X_train, y_train)
- dec_tree_model_valid_score = dec_tree_model_valid.score(X_train, y_train)
- gauss_nb_model_valid_score = gauss_nb_model_valid.score(X_train, y_train)
- neur_net_model_valid_score = neur_net_model_valid.score(X_train, y_train)
- model_valid_dict = {'Logistic Regression': logreg_model_valid_score, 'Decision Tree': dec_tree_model_valid_score, \
- 'Naive Bayes': gauss_nb_model_valid_score, 'Neural Network': neur_net_model_valid_score}
- model_valid_dict_max = max(model_valid_dict, key=model_valid_dict.get)
- '''
- print("Validation Set Model Information:\n")
- for key, value in model_valid_dict.items() :
- print (key, value)
- '''
- print("\nValidation model with maximum score: {} - {}".format(model_valid_dict_max, model_valid_dict[model_valid_dict_max]))
- #####################################################################################################################
- # Predicts and their probabilities
- #####################################################################################################################
- logreg_model_valid_predict = logreg_model_valid.predict(X_test)
- dec_tree_model_valid_predict = dec_tree_model_valid.predict(X_test)
- gauss_nb_model_valid_predict = gauss_nb_model_valid.predict(X_test)
- neur_net_model_valid_predict = neur_net_model_valid.predict(X_test)
- logreg_model_valid_probs = logreg_model_valid.predict_proba(X_test)
- dec_tree_model_valid_probs = dec_tree_model_valid.predict_proba(X_test)
- gauss_nb_model_valid_probs = gauss_nb_model_valid.predict_proba(X_test)
- neur_net_model_valid_probs = neur_net_model_valid.predict_proba(X_test)
- #####################################################################################################################
- # Prediction accuracy scores
- #####################################################################################################################
- logreg_model_valid_predict_accuracy = metrics.accuracy_score(y_test, logreg_model_valid_predict)
- dec_tree_model_valid_predict_accuracy = metrics.accuracy_score(y_test, dec_tree_model_valid_predict)
- gauss_nb_model_valid_predict_accuracy = metrics.accuracy_score(y_test, gauss_nb_model_valid_predict)
- neur_net_model_valid_predict_accuracy = metrics.accuracy_score(y_test, neur_net_model_valid_predict)
- predict_accuracy_dict = {'Logistic Regression': logreg_model_valid_predict_accuracy, 'Decision Tree': dec_tree_model_valid_predict_accuracy, \
- 'Naive Bayes': gauss_nb_model_valid_predict_accuracy, 'Neural Network': neur_net_model_valid_predict_accuracy}
- predict_accuracy_max = max(predict_accuracy_dict, key=predict_accuracy_dict.get)
- '''
- print("Validation Set Accuracy Information:\n")
- for key, value in model_valid_dict_accuracy.items() :
- print (key, value)
- '''
- print("\nHighest predictio acuuracy: {} - {}".format(predict_accuracy_max, predict_accuracy_dict[predict_accuracy_max]))
- #####################################################################################################################
- # ROC scores
- #####################################################################################################################
- logreg_model_valid_probs_roc = metrics.roc_auc_score(y_test, logreg_model_valid_probs[:, 1])
- dec_tree_model_valid_probs_roc = metrics.roc_auc_score(y_test, dec_tree_model_valid_probs[:, 1])
- gauss_nb_model_valid_probs_roc = metrics.roc_auc_score(y_test, gauss_nb_model_valid_probs[:, 1])
- neur_net_model_valid_probs_roc = metrics.roc_auc_score(y_test, neur_net_model_valid_probs[:, 1])
- probs_roc_dict = {'Logistic Regression': logreg_model_valid_probs_roc, 'Decision Tree': dec_tree_model_valid_probs_roc, \
- 'Naive Bayes': gauss_nb_model_valid_probs_roc, 'Neural Network': neur_net_model_valid_probs_roc}
- probs_roc_dict_max = max(probs_roc_dict, key=probs_roc_dict.get)
- print("\nHighest probability ROC: {} - {}".format(probs_roc_dict_max, probs_roc_dict[probs_roc_dict_max]))
- #####################################################################################################################
- # Confusion Matrices
- #####################################################################################################################
- logreg_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, logreg_model_valid_predict)
- dec_tree_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, dec_tree_model_valid_predict)
- gauss_nb_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, gauss_nb_model_valid_predict)
- neur_net_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, neur_net_model_valid_predict)
- #####################################################################################################################
- # Classification Report
- #####################################################################################################################
- logreg_model_valid_predict_report = metrics.classification_report(y_test, logreg_model_valid_predict)
- dec_tree_model_valid_predict_report = metrics.classification_report(y_test, dec_tree_model_valid_predict)
- gauss_nb_model_valid_predict_report = metrics.classification_report(y_test, gauss_nb_model_valid_predict)
- neur_net_model_valid_predict_report = metrics.classification_report(y_test, neur_net_model_valid_predict)
- #####################################################################################################################
- # Model Evaluation Using Cross-Validation, 4 fold
- #####################################################################################################################
- logreg_scores = cross_val_score(logreg, X_reshape, Y, scoring='accuracy', cv=4)
- dec_tree_scores = cross_val_score(dec_tree, X_reshape, Y, scoring='accuracy', cv=4)
- gauss_nb_scores = cross_val_score(gauss_nb, X_reshape, Y, scoring='accuracy', cv=4)
- neur_net_scores = cross_val_score(neur_net, X_reshape, Y, scoring='accuracy', cv=4)
- logreg_scores_mean = logreg_scores.mean()
- dec_tree_scores_mean = dec_tree_scores.mean()
- gauss_nb_scores_mean = gauss_nb_scores.mean()
- neur_net_scores_mean = neur_net_scores.mean()
- cv_scores_mean_dict = {'Logistic Regression': logreg_scores_mean, 'Decision Tree': dec_tree_scores_mean, \
- 'Naive Bayes': gauss_nb_scores_mean, 'Neural Network': neur_net_scores_mean}
- cv_scores_mean_dict_max = max(cv_scores_mean_dict, key=cv_scores_mean_dict.get)
- print("\nHighest cross-validation score: {} - {}".format(cv_scores_mean_dict_max, cv_scores_mean_dict[cv_scores_mean_dict_max]))
- #####################################################################################################################
- # Plot training score
- #####################################################################################################################
- objects_model_score = list(model_dict.keys())
- y_pos_model_score = np.arange(len(objects_model_score))
- performance_model_score = list(model_dict.values())
- plt.bar(y_pos_model_score, performance_model_score, align='center', alpha=0.5)
- plt.xticks(y_pos_model_score, objects_model_score)
- plt.ylabel('Training score')
- plt.title('Classifier by training score')
- plt.show()
- #####################################################################################################################
- # Plot validation score
- #####################################################################################################################
- objects_valid_score = list(model_valid_dict.keys())
- y_pos_valid_score = np.arange(len(objects_valid_score))
- performance_valid_score = list(model_valid_dict.values())
- plt.bar(y_pos_valid_score, performance_valid_score, align='center', alpha=0.5)
- plt.xticks(y_pos_valid_score, objects_valid_score)
- plt.ylabel('Validation score')
- plt.title('Classifier by validation score')
- plt.show()
- #####################################################################################################################
- # Plot prediction accuracy
- #####################################################################################################################
- objects_accuracy = list(predict_accuracy_dict.keys())
- y_pos_accuracy = np.arange(len(objects_accuracy))
- performance_accuracy = list(predict_accuracy_dict.values())
- plt.bar(y_pos_accuracy, performance_accuracy, align='center', alpha=0.5)
- plt.xticks(y_pos_accuracy, objects_accuracy)
- plt.ylabel('Accuracy')
- plt.title('Classifier by prediction accuracy')
- plt.show()
- #####################################################################################################################
- # Plot probability ROC
- #####################################################################################################################
- objects_probs_roc = list(probs_roc_dict.keys())
- y_pos_probs_roc = np.arange(len(objects_probs_roc))
- performance_probs_roc = list(probs_roc_dict.values())
- plt.bar(y_pos_probs_roc, performance_probs_roc, align='center', alpha=0.5)
- plt.xticks(y_pos_probs_roc, objects_probs_roc)
- plt.ylabel('ROC score')
- plt.title('Classifier by probability ROC')
- plt.show()
- #####################################################################################################################
- # Plot validation score
- #####################################################################################################################
- objects_cv_score = list(cv_scores_mean_dict.keys())
- y_pos_cv_score = np.arange(len(objects_cv_score))
- performance_cv_score = list(cv_scores_mean_dict.values())
- plt.bar(y_pos_cv_score, performance_cv_score, align='center', alpha=0.5)
- plt.xticks(y_pos_cv_score, objects_cv_score)
- plt.ylabel('Training score')
- plt.title('Classifier by cross validation score')
- plt.show()
- '''
- N = 3
- ind = np.arange(N) # the x locations for the groups
- width = 0.27 # the width of the bars
- fig = plt.figure()
- ax = fig.add_subplot(111)
- yvals = [4, 9, 2]
- rects1 = ax.bar(ind, yvals, width, color='r')
- zvals = [1,2,3]
- rects2 = ax.bar(ind+width, zvals, width, color='g')
- kvals = [11,12,13]
- rects3 = ax.bar(ind+width*2, kvals, width, color='b')
- ax.set_ylabel('Scores')
- ax.set_xticks(ind+width)
- ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
- ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )
- def autolabel(rects):
- for rect in rects:
- h = rect.get_height()
- ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
- ha='center', va='bottom')
- autolabel(rects1)
- autolabel(rects2)
- autolabel(rects3)
- plt.show()
- '''
Add Comment
Please, Sign In to add comment