Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

classifier_nn.py 7.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
  1. import theano
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.preprocessing import StandardScaler
  5. from keras.models import Sequential
  6. from keras.layers import Dense
  7. from keras.layers import Dropout
  8. from keras.callbacks import History
  9. from keras.optimizers import SGD
  10. from sklearn.model_selection import train_test_split
  11. from matplotlib import pyplot as plt
  12. import performance as perform
  13. import sys
  14. from sklearn.model_selection import GridSearchCV
  15. from keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor
  16. from sklearn.model_selection import StratifiedKFold
  17. from sklearn.model_selection import cross_val_score
  18. from sklearn.metrics import classification_report
  19. from sklearn.learning_curve import learning_curve
  20. def set_trace():
  21. """A Poor mans break point"""
  22. # without this in iPython debugger can generate strange characters.
  23. from IPython.core.debugger import Pdb
  24. Pdb().set_trace(sys._getframe().f_back)
  25. def get_traintest_validation_split(df):
  26. """ Split the data into a train_test dataset and a validation dataset
  27. train_test will later be split into the training and testing
  28. dataset
  29. Fitting using gradient descent etc is only performed on the
  30. training set, fitting via the act of hyperparameter optimisation
  31. uses the training and test dataset as tuners (this inherently fits
  32. the data to the training and test sets).
  33. This is the reason that the test dataset is not sufficient as a
  34. validation set
  35. (it can result in overestimated performance as the current optimised
  36. model has been fine-tuned to performed well on the test set)
  37. This is why the final model is tested on a hold-out validation set
  38. """
  39. train_test, validation = np.split(df.sample(frac=1),
  40. [int(.9 * len(df))])
  41. y = np.ravel(train_test['Class'])
  42. train_test = train_test.drop('Class', 1)
  43. x = train_test.as_matrix()
  44. return x, y, validation
  45. def prepare_design_target(df):
  46. """ Prepare design matrix (X) and target vector (y)
  47. """
  48. y = np.ravel(df['Class'])
  49. x = df.drop('Class', 1)
  50. x = x.as_matrix()
  51. return x, y
  52. def manual_ann2(X, y, validation, pca_dim):
  53. """ Keras Sequential model with Manual validation
  54. """
  55. # fix random seed for reproducibility
  56. seed = 13
  57. np.random.seed(seed)
  58. cvscores = []
  59. learning_rate = 0.2
  60. sgd = SGD(lr=learning_rate, momentum=0.05, nesterov=False)
  61. def create_baseline():
  62. # NN architecture
  63. input_nodes = pca_dim
  64. hidden1_nodes = 50
  65. hidden2_nodes = 50
  66. hidden3_nodes = 50
  67. output_nodes = 1
  68. dropout_rate = 0.1
  69. model = Sequential()
  70. model.add(Dense(output_dim=hidden1_nodes,
  71. input_dim=input_nodes,
  72. activation='relu'))
  73. model.add(Dropout(dropout_rate))
  74. model.add(Dense(output_dim=hidden2_nodes,
  75. input_dim=hidden1_nodes,
  76. activation='relu'))
  77. model.add(Dropout(dropout_rate))
  78. model.add(Dense(output_dim=hidden3_nodes,
  79. input_dim=hidden2_nodes,
  80. activation='relu'))
  81. model.add(Dropout(dropout_rate))
  82. model.add(Dense(output_dim=output_nodes,
  83. input_dim=hidden3_nodes,
  84. activation='sigmoid'))
  85. # Compile model
  86. model.compile(loss='binary_crossentropy',
  87. optimizer='adam',
  88. metrics=['accuracy'])
  89. return model
  90. # evaluate model with standardized dataset
  91. estimator = KerasClassifier(build_fn=create_baseline,
  92. nb_epoch=100,
  93. batch_size=200,
  94. verbose=2)
  95. kfold = StratifiedKFold(n_splits=10,
  96. shuffle=True,
  97. random_state=seed)
  98. results = cross_val_score(estimator,
  99. X,
  100. y,
  101. cv=kfold)
  102. print("Results of 10-fold Cross-Validation: %.2f%% (%.2f%%)" % (results.mean() * 100, results.std() * 100))
  103. set_trace()
  104. title = "Learning Curves (Sequential Neural Net - Criminal men/Non-criminal women)"
  105. plot_learning_curve(estimator, title, X, y, cv=None, n_jobs=1)
  106. set_trace()
  107. accuracy = pd.DataFrame({'10 Fold Accuracy': [results.mean()*100]})
  108. accuracy.to_csv('C:\Thesis111217\CriminalClassifier\Outputs\All_images_acc.csv')
  109. # Plot Precision/Recall curve
  110. validation_y = np.ravel(validation['Class'])
  111. validation_x = validation.drop('Class', 1)
  112. validation_x = validation_x.as_matrix()
  113. X_train, X_test, y_train, y_test = \
  114. train_test_split(X, y, test_size=0.33, random_state=42)
  115. model2 = create_baseline()
  116. model2.fit(X,y)
  117. pred = model2.predict(validation_x)
  118. pred = [item for sublist in pred for item in sublist]
  119. pred = [int(round(n, 0)) for n in pred]
  120. class_names = ['Non-Criminal', 'Criminal']
  121. cm = perform.get_confusion_matrix(validation_y, pred)
  122. perform.plot_confusion_matrix(cm, class_names)
  123. set_trace()
  124. print 'Classification report:\n {}'.format(classification_report(validation_y, pred))
  125. '''
  126. # Make predictions on hold-out validation set
  127. model = create_baseline()
  128. model.fit(X, y, epochs=100, batch_size=200, verbose=2)
  129. set_trace()
  130. pred = model.predict(validation_x)
  131. pred = [item for sublist in pred for item in sublist]
  132. pred = [int(round(n, 0)) for n in pred]
  133. class_names = ['Non-Criminal', 'Criminal']
  134. cm = perform.get_confusion_matrix(validation_y, pred)
  135. perform.plot_confusion_matrix(cm, class_names)
  136. print 'Classification report:\n {}'.format(classification_report(validation_y, pred))
  137. '''
  138. return
  139. def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
  140. plt.figure()
  141. plt.title(title)
  142. if ylim is not None:
  143. plt.ylim(*ylim)
  144. plt.xlabel("Training examples")
  145. plt.ylabel("Score")
  146. train_sizes, train_scores, test_scores = learning_curve(
  147. estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
  148. train_scores_mean = np.mean(train_scores, axis=1)
  149. train_scores_std = np.std(train_scores, axis=1)
  150. test_scores_mean = np.mean(test_scores, axis=1)
  151. test_scores_std = np.std(test_scores, axis=1)
  152. plt.grid()
  153. plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
  154. train_scores_mean + train_scores_std, alpha=0.1,
  155. color="r")
  156. plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
  157. test_scores_mean + test_scores_std, alpha=0.1, color="g")
  158. plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
  159. label="Training score")
  160. plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
  161. label="Cross-validation score")
  162. plt.legend(loc="best")
  163. plt.show()
  164. #plt.savefig('C:\Thesis111217\CriminalClassifier\Outputs\LearningCurve_all.png')
  165. #plt.clf()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...