tuttelikz

Traditional Machine Learning

Jun 12th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.06 KB | None | 0 0
  1. #####################################################################################################################
  2. # 20165443 Sanzhar Askaruly
  3. # Advanced Machine Learning
  4. #####################################################################################################################
  5.  
  6. #####################################################################################################################
  7. # Including libraries
  8. #####################################################################################################################
  9.  
  10. # Basic libraries
  11. import numpy as np
  12. import pandas as pd
  13. import sklearn
  14. import random
  15. import matplotlib
  16. import matplotlib.pyplot as plt
  17. import utils
  18.  
  19. # Models
  20. from sklearn import linear_model, datasets
  21. from sklearn import tree
  22. from sklearn.naive_bayes import GaussianNB
  23. from sklearn.neural_network import MLPClassifier
  24.  
  25. # Model Evaluation
  26. from sklearn.model_selection import train_test_split
  27. from sklearn.model_selection import cross_val_score
  28. from sklearn import metrics
  29.  
  30. #####################################################################################################################
  31. # File input
  32. #####################################################################################################################
  33.  
  34. filename1 = 'dataset/eyerim_dataset.csv'
  35. filename2 = 'dataset/cheek_dataset.csv'
  36. filename3 = 'dataset/forearm_dataset.csv'
  37.  
  38. data = pd.read_csv(filename1)
  39.  
  40. #####################################################################################################################
  41. # Preprocessing
  42. #####################################################################################################################
  43.  
  44.  
  45.  
  46. #matrix_data = data.as_matrix()
  47. #X = matrix_data[:,2]
  48. #X_reshape = X.reshape(-1, 1)
  49. #Y = matrix_data[:,-1]
  50.  
  51.  
  52. matrix_data = data.as_matrix()
  53. X = matrix_data[:,0:8]
  54. #X_reshape = X.reshape(-1, 1)
  55. X_reshape = X
  56. Y = matrix_data[:,8]
  57.  
  58. #print(matrix_data)
  59. #print(Y)
  60.  
  61. #####################################################################################################################
  62. # Modeling
  63. #####################################################################################################################
  64.  
  65. logreg = linear_model.LogisticRegression(C=1e5)
  66. dec_tree = tree.DecisionTreeClassifier()
  67. gauss_nb = GaussianNB()
  68. neur_net = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)
  69.  
  70. #####################################################################################################################
  71. # Training set
  72. #####################################################################################################################
  73.  
  74. logreg_model = logreg.fit(X_reshape, Y)
  75. dec_tree_model = dec_tree.fit(X_reshape, Y)
  76. gauss_nb_model = gauss_nb.fit(X_reshape, Y)
  77. neur_net_model = neur_net.fit(X_reshape, Y)
  78.  
  79. #####################################################################################################################
  80. # Printing training set scores
  81. #####################################################################################################################
  82.  
  83. logreg_model_score = logreg_model.score(X_reshape, Y)
  84. dec_tree_model_score = dec_tree_model.score(X_reshape, Y)
  85. gauss_nb_model_score = gauss_nb_model.score(X_reshape, Y)
  86. neur_net_model_score = neur_net_model.score(X_reshape, Y)
  87.  
  88. model_dict = {'Logistic Regression': logreg_model_score, 'Decision Tree': dec_tree_model_score, \
  89. 'Naive Bayes': gauss_nb_model_score, 'Neural Network': neur_net_model_score}
  90. max_mddel_dict = max(model_dict, key=model_dict.get)
  91. '''
  92. print("Training Set Model Information:\n")
  93. for key, value in model_dict.items() :
  94. print (key, value)
  95. '''
  96. print("\nTraining model with maximum score: {} - {}".format(max_mddel_dict, model_dict[max_mddel_dict]))
  97.  
  98. #####################################################################################################################
  99. # Printing validation (with ratio 0.3) set model scores
  100. #####################################################################################################################
  101.  
  102. X_train, X_test, y_train, y_test = train_test_split(X_reshape, Y, test_size=0.3, random_state=0)
  103. logreg_model_valid = logreg_model.fit(X_train, y_train)
  104. dec_tree_model_valid = dec_tree_model.fit(X_train, y_train)
  105. gauss_nb_model_valid = gauss_nb_model.fit(X_train, y_train)
  106. neur_net_model_valid = neur_net_model.fit(X_train, y_train)
  107.  
  108. #####################################################################################################################
  109. # Printing validation model scores
  110. #####################################################################################################################
  111.  
  112. logreg_model_valid_score = logreg_model_valid.score(X_train, y_train)
  113. dec_tree_model_valid_score = dec_tree_model_valid.score(X_train, y_train)
  114. gauss_nb_model_valid_score = gauss_nb_model_valid.score(X_train, y_train)
  115. neur_net_model_valid_score = neur_net_model_valid.score(X_train, y_train)
  116.  
  117. model_valid_dict = {'Logistic Regression': logreg_model_valid_score, 'Decision Tree': dec_tree_model_valid_score, \
  118. 'Naive Bayes': gauss_nb_model_valid_score, 'Neural Network': neur_net_model_valid_score}
  119. model_valid_dict_max = max(model_valid_dict, key=model_valid_dict.get)
  120. '''
  121. print("Validation Set Model Information:\n")
  122. for key, value in model_valid_dict.items() :
  123. print (key, value)
  124. '''
  125. print("\nValidation model with maximum score: {} - {}".format(model_valid_dict_max, model_valid_dict[model_valid_dict_max]))
  126.  
  127. #####################################################################################################################
  128. # Predicts and their probabilities
  129. #####################################################################################################################
  130.  
  131. logreg_model_valid_predict = logreg_model_valid.predict(X_test)
  132. dec_tree_model_valid_predict = dec_tree_model_valid.predict(X_test)
  133. gauss_nb_model_valid_predict = gauss_nb_model_valid.predict(X_test)
  134. neur_net_model_valid_predict = neur_net_model_valid.predict(X_test)
  135.  
  136. logreg_model_valid_probs = logreg_model_valid.predict_proba(X_test)
  137. dec_tree_model_valid_probs = dec_tree_model_valid.predict_proba(X_test)
  138. gauss_nb_model_valid_probs = gauss_nb_model_valid.predict_proba(X_test)
  139. neur_net_model_valid_probs = neur_net_model_valid.predict_proba(X_test)
  140.  
  141. #####################################################################################################################
  142. # Prediction accuracy scores
  143. #####################################################################################################################
  144.  
  145. logreg_model_valid_predict_accuracy = metrics.accuracy_score(y_test, logreg_model_valid_predict)
  146. dec_tree_model_valid_predict_accuracy = metrics.accuracy_score(y_test, dec_tree_model_valid_predict)
  147. gauss_nb_model_valid_predict_accuracy = metrics.accuracy_score(y_test, gauss_nb_model_valid_predict)
  148. neur_net_model_valid_predict_accuracy = metrics.accuracy_score(y_test, neur_net_model_valid_predict)
  149.  
  150. predict_accuracy_dict = {'Logistic Regression': logreg_model_valid_predict_accuracy, 'Decision Tree': dec_tree_model_valid_predict_accuracy, \
  151. 'Naive Bayes': gauss_nb_model_valid_predict_accuracy, 'Neural Network': neur_net_model_valid_predict_accuracy}
  152. predict_accuracy_max = max(predict_accuracy_dict, key=predict_accuracy_dict.get)
  153.  
  154. '''
  155. print("Validation Set Accuracy Information:\n")
  156. for key, value in model_valid_dict_accuracy.items() :
  157. print (key, value)
  158. '''
  159. print("\nHighest predictio acuuracy: {} - {}".format(predict_accuracy_max, predict_accuracy_dict[predict_accuracy_max]))
  160.  
  161. #####################################################################################################################
  162. # ROC scores
  163. #####################################################################################################################
  164.  
  165. logreg_model_valid_probs_roc = metrics.roc_auc_score(y_test, logreg_model_valid_probs[:, 1])
  166. dec_tree_model_valid_probs_roc = metrics.roc_auc_score(y_test, dec_tree_model_valid_probs[:, 1])
  167. gauss_nb_model_valid_probs_roc = metrics.roc_auc_score(y_test, gauss_nb_model_valid_probs[:, 1])
  168. neur_net_model_valid_probs_roc = metrics.roc_auc_score(y_test, neur_net_model_valid_probs[:, 1])
  169.  
  170. probs_roc_dict = {'Logistic Regression': logreg_model_valid_probs_roc, 'Decision Tree': dec_tree_model_valid_probs_roc, \
  171. 'Naive Bayes': gauss_nb_model_valid_probs_roc, 'Neural Network': neur_net_model_valid_probs_roc}
  172. probs_roc_dict_max = max(probs_roc_dict, key=probs_roc_dict.get)
  173.  
  174. print("\nHighest probability ROC: {} - {}".format(probs_roc_dict_max, probs_roc_dict[probs_roc_dict_max]))
  175.  
  176. #####################################################################################################################
  177. # Confusion Matrices
  178. #####################################################################################################################
  179.  
  180. logreg_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, logreg_model_valid_predict)
  181. dec_tree_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, dec_tree_model_valid_predict)
  182. gauss_nb_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, gauss_nb_model_valid_predict)
  183. neur_net_model_valid_predict_conf_m = metrics.confusion_matrix(y_test, neur_net_model_valid_predict)
  184.  
  185. #####################################################################################################################
  186. # Classification Report
  187. #####################################################################################################################
  188.  
  189. logreg_model_valid_predict_report = metrics.classification_report(y_test, logreg_model_valid_predict)
  190. dec_tree_model_valid_predict_report = metrics.classification_report(y_test, dec_tree_model_valid_predict)
  191. gauss_nb_model_valid_predict_report = metrics.classification_report(y_test, gauss_nb_model_valid_predict)
  192. neur_net_model_valid_predict_report = metrics.classification_report(y_test, neur_net_model_valid_predict)
  193.  
  194. #####################################################################################################################
  195. # Model Evaluation Using Cross-Validation, 4 fold
  196. #####################################################################################################################
  197.  
  198. logreg_scores = cross_val_score(logreg, X_reshape, Y, scoring='accuracy', cv=4)
  199. dec_tree_scores = cross_val_score(dec_tree, X_reshape, Y, scoring='accuracy', cv=4)
  200. gauss_nb_scores = cross_val_score(gauss_nb, X_reshape, Y, scoring='accuracy', cv=4)
  201. neur_net_scores = cross_val_score(neur_net, X_reshape, Y, scoring='accuracy', cv=4)
  202.  
  203. logreg_scores_mean = logreg_scores.mean()
  204. dec_tree_scores_mean = dec_tree_scores.mean()
  205. gauss_nb_scores_mean = gauss_nb_scores.mean()
  206. neur_net_scores_mean = neur_net_scores.mean()
  207.  
  208. cv_scores_mean_dict = {'Logistic Regression': logreg_scores_mean, 'Decision Tree': dec_tree_scores_mean, \
  209. 'Naive Bayes': gauss_nb_scores_mean, 'Neural Network': neur_net_scores_mean}
  210. cv_scores_mean_dict_max = max(cv_scores_mean_dict, key=cv_scores_mean_dict.get)
  211.  
  212. print("\nHighest cross-validation score: {} - {}".format(cv_scores_mean_dict_max, cv_scores_mean_dict[cv_scores_mean_dict_max]))
  213.  
  214.  
  215.  
  216.  
  217.  
  218. #####################################################################################################################
  219. # Plot training score
  220. #####################################################################################################################
  221.  
  222. objects_model_score = list(model_dict.keys())
  223. y_pos_model_score = np.arange(len(objects_model_score))
  224. performance_model_score = list(model_dict.values())
  225.  
  226. plt.bar(y_pos_model_score, performance_model_score, align='center', alpha=0.5)
  227. plt.xticks(y_pos_model_score, objects_model_score)
  228. plt.ylabel('Training score')
  229. plt.title('Classifier by training score')
  230. plt.show()
  231.  
  232. #####################################################################################################################
  233. # Plot validation score
  234. #####################################################################################################################
  235.  
  236. objects_valid_score = list(model_valid_dict.keys())
  237. y_pos_valid_score = np.arange(len(objects_valid_score))
  238. performance_valid_score = list(model_valid_dict.values())
  239.  
  240. plt.bar(y_pos_valid_score, performance_valid_score, align='center', alpha=0.5)
  241. plt.xticks(y_pos_valid_score, objects_valid_score)
  242. plt.ylabel('Validation score')
  243. plt.title('Classifier by validation score')
  244. plt.show()
  245.  
  246.  
  247. #####################################################################################################################
  248. # Plot prediction accuracy
  249. #####################################################################################################################
  250.  
  251. objects_accuracy = list(predict_accuracy_dict.keys())
  252. y_pos_accuracy = np.arange(len(objects_accuracy))
  253. performance_accuracy = list(predict_accuracy_dict.values())
  254.  
  255. plt.bar(y_pos_accuracy, performance_accuracy, align='center', alpha=0.5)
  256. plt.xticks(y_pos_accuracy, objects_accuracy)
  257. plt.ylabel('Accuracy')
  258. plt.title('Classifier by prediction accuracy')
  259. plt.show()
  260.  
  261.  
  262. #####################################################################################################################
  263. # Plot probability ROC
  264. #####################################################################################################################
  265.  
  266. objects_probs_roc = list(probs_roc_dict.keys())
  267. y_pos_probs_roc = np.arange(len(objects_probs_roc))
  268. performance_probs_roc = list(probs_roc_dict.values())
  269.  
  270. plt.bar(y_pos_probs_roc, performance_probs_roc, align='center', alpha=0.5)
  271. plt.xticks(y_pos_probs_roc, objects_probs_roc)
  272. plt.ylabel('ROC score')
  273. plt.title('Classifier by probability ROC')
  274. plt.show()
  275.  
  276. #####################################################################################################################
  277. # Plot validation score
  278. #####################################################################################################################
  279.  
  280. objects_cv_score = list(cv_scores_mean_dict.keys())
  281. y_pos_cv_score = np.arange(len(objects_cv_score))
  282. performance_cv_score = list(cv_scores_mean_dict.values())
  283.  
  284. plt.bar(y_pos_cv_score, performance_cv_score, align='center', alpha=0.5)
  285. plt.xticks(y_pos_cv_score, objects_cv_score)
  286. plt.ylabel('Training score')
  287. plt.title('Classifier by cross validation score')
  288. plt.show()
  289.  
  290.  
  291.  
  292. '''
  293. N = 3
  294. ind = np.arange(N) # the x locations for the groups
  295. width = 0.27 # the width of the bars
  296.  
  297. fig = plt.figure()
  298. ax = fig.add_subplot(111)
  299.  
  300. yvals = [4, 9, 2]
  301. rects1 = ax.bar(ind, yvals, width, color='r')
  302. zvals = [1,2,3]
  303. rects2 = ax.bar(ind+width, zvals, width, color='g')
  304. kvals = [11,12,13]
  305. rects3 = ax.bar(ind+width*2, kvals, width, color='b')
  306.  
  307. ax.set_ylabel('Scores')
  308. ax.set_xticks(ind+width)
  309. ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
  310. ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )
  311.  
  312. def autolabel(rects):
  313. for rect in rects:
  314. h = rect.get_height()
  315. ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
  316. ha='center', va='bottom')
  317.  
  318. autolabel(rects1)
  319. autolabel(rects2)
  320. autolabel(rects3)
  321.  
  322. plt.show()
  323. '''
Add Comment
Please, Sign In to add comment