|
a |
|
b/Preprocess_Deap.ipynb |
|
|
1 |
{ |
|
|
2 |
"cells": [ |
|
|
3 |
{ |
|
|
4 |
"cell_type": "markdown", |
|
|
5 |
"metadata": {}, |
|
|
6 |
"source": [ |
|
|
7 |
"# Valence value regression based on Deap Dataset\n", |
|
|
8 |
"\n", |
|
|
9 |
"## 0. This notebook is based on DEAP database\n", |
|
|
10 |
"\n", |
|
|
11 |
"Anyone should refer to DEAP team first\n", |
|
|
12 |
"\n", |
|
|
13 |
"@article{koelstra2012deap,\n", |
|
|
14 |
" title={Deap: A database for emotion analysis; using physiological signals},\n", |
|
|
15 |
" author={Koelstra, Sander and Muhl, Christian and Soleymani, Mohammad and Lee, Jong-Seok and Yazdani, Ashkan and Ebrahimi, Touradj and Pun, Thierry and Nijholt, Anton and Patras, Ioannis},\n", |
|
|
16 |
" journal={IEEE Transactions on Affective Computing},\n", |
|
|
17 |
" volume={3},\n", |
|
|
18 |
" number={1},\n", |
|
|
19 |
" pages={18--31},\n", |
|
|
20 |
" year={2012},\n", |
|
|
21 |
" publisher={IEEE}\n", |
|
|
22 |
"}\n", |
|
|
23 |
"\n", |
|
|
24 |
"## 1. Dependency\n", |
|
|
25 |
"* numpy\n", |
|
|
26 |
"* pyEEG\n", |
|
|
27 |
"* sciki-learn" |
|
|
28 |
] |
|
|
29 |
}, |
|
|
30 |
{ |
|
|
31 |
"cell_type": "code", |
|
|
32 |
"execution_count": 7, |
|
|
33 |
"metadata": {}, |
|
|
34 |
"outputs": [], |
|
|
35 |
"source": [ |
|
|
36 |
"import numpy as np\n", |
|
|
37 |
"#import pyeeg as pe\n", |
|
|
38 |
"import pickle as pickle\n", |
|
|
39 |
"import pandas as pd\n", |
|
|
40 |
"import math\n", |
|
|
41 |
"\n", |
|
|
42 |
"from sklearn import svm\n", |
|
|
43 |
"from sklearn.preprocessing import normalize\n", |
|
|
44 |
"from sklearn.ensemble import RandomForestRegressor\n", |
|
|
45 |
"from sklearn.ensemble import AdaBoostRegressor\n", |
|
|
46 |
"\n", |
|
|
47 |
"import os\n", |
|
|
48 |
"#import tensorflow as tf\n", |
|
|
49 |
"import time" |
|
|
50 |
] |
|
|
51 |
}, |
|
|
52 |
{ |
|
|
53 |
"cell_type": "markdown", |
|
|
54 |
"metadata": {}, |
|
|
55 |
"source": [ |
|
|
56 |
"## 2. Global Variables setup\n", |
|
|
57 |
"File Name data\\SXX.dat, XX \\in [0,31]\n", |
|
|
58 |
"* data: 40 x 40 x 8064: trial x channel x data\n", |
|
|
59 |
"* label: 40 x 4: video/trial x label (valence, arousal, dominance, liking)\n", |
|
|
60 |
"\n", |
|
|
61 |
"Channel Indice: {\n", |
|
|
62 |
"* 1 : AF3; 2: F3; 3: F7; 4: FC5; 7: T7; 11: P7; 13: O1\n", |
|
|
63 |
"* 17: AF4; 19: F4; 20: F8; 21: FC6; 25: T8; 29: P8; 31: O2 }" |
|
|
64 |
] |
|
|
65 |
}, |
|
|
66 |
{ |
|
|
67 |
"cell_type": "code", |
|
|
68 |
"execution_count": 48, |
|
|
69 |
"metadata": {}, |
|
|
70 |
"outputs": [], |
|
|
71 |
"source": [ |
|
|
72 |
"channel = [1,2,3,4,6,11,13,17,19,20,21,25,29,31] #14 Channels chosen to fit Emotiv Epoch+\n", |
|
|
73 |
"band = [4,8,12,16,25,45] #5 bands\n", |
|
|
74 |
"window_size = 256 #Averaging band power of 2 sec\n", |
|
|
75 |
"step_size = 16 #Each 0.125 sec update once\n", |
|
|
76 |
"sample_rate = 128 #Sampling rate of 128 Hz\n", |
|
|
77 |
"subjectList = ['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32']\n", |
|
|
78 |
"#List of subjects" |
|
|
79 |
] |
|
|
80 |
}, |
|
|
81 |
{ |
|
|
82 |
"cell_type": "markdown", |
|
|
83 |
"metadata": {}, |
|
|
84 |
"source": [ |
|
|
85 |
"## 3. FFT with pyeeg\n", |
|
|
86 |
"* [4-8]: theta band\n", |
|
|
87 |
"* [8-12]: alpha band\n", |
|
|
88 |
"* [12-16]: low beta band \n", |
|
|
89 |
"* [16-25]: high beta band\n", |
|
|
90 |
"* [25-45]: gamma band" |
|
|
91 |
] |
|
|
92 |
}, |
|
|
93 |
{ |
|
|
94 |
"cell_type": "code", |
|
|
95 |
"execution_count": 60, |
|
|
96 |
"metadata": {}, |
|
|
97 |
"outputs": [], |
|
|
98 |
"source": [ |
|
|
99 |
"def FFT_Processing (sub, channel, band, window_size, step_size, sample_rate):\n", |
|
|
100 |
" '''\n", |
|
|
101 |
" arguments: string subject\n", |
|
|
102 |
" list channel indice\n", |
|
|
103 |
" list band\n", |
|
|
104 |
" int window size for FFT\n", |
|
|
105 |
" int step size for FFT\n", |
|
|
106 |
" int sample rate for FFT\n", |
|
|
107 |
" return: void\n", |
|
|
108 |
" '''\n", |
|
|
109 |
" meta = []\n", |
|
|
110 |
" with open('data\\s' + sub + '.dat', 'rb') as file:\n", |
|
|
111 |
"\n", |
|
|
112 |
" subject = pickle.load(file, encoding='latin1') #resolve the python 2 data problem by encoding : latin1\n", |
|
|
113 |
"\n", |
|
|
114 |
" for i in range (0,40):\n", |
|
|
115 |
" # loop over 0-39 trails\n", |
|
|
116 |
" data = subject[\"data\"][i]\n", |
|
|
117 |
" labels = subject[\"labels\"][i]\n", |
|
|
118 |
" start = 0;\n", |
|
|
119 |
"\n", |
|
|
120 |
" while start + window_size < data.shape[1]:\n", |
|
|
121 |
" meta_array = []\n", |
|
|
122 |
" meta_data = [] #meta vector for analysis\n", |
|
|
123 |
" for j in channel:\n", |
|
|
124 |
" X = data[j][start : start + window_size] #Slice raw data over 2 sec, at interval of 0.125 sec\n", |
|
|
125 |
" Y = pe.bin_power(X, band, sample_rate) #FFT over 2 sec of channel j, in seq of theta, alpha, low beta, high beta, gamma\n", |
|
|
126 |
" meta_data = meta_data + list(Y[0])\n", |
|
|
127 |
"\n", |
|
|
128 |
" meta_array.append(np.array(meta_data))\n", |
|
|
129 |
" meta_array.append(labels)\n", |
|
|
130 |
"\n", |
|
|
131 |
" meta.append(np.array(meta_array)) \n", |
|
|
132 |
" start = start + step_size\n", |
|
|
133 |
" \n", |
|
|
134 |
" meta = np.array(meta)\n", |
|
|
135 |
" np.save('out\\s' + sub, meta, allow_pickle=True, fix_imports=True)\n", |
|
|
136 |
"\n", |
|
|
137 |
"def testing (M, L, model):\n", |
|
|
138 |
" '''\n", |
|
|
139 |
" arguments: M: testing dataset\n", |
|
|
140 |
" L: testing dataset label\n", |
|
|
141 |
" model: scikit-learn model\n", |
|
|
142 |
"\n", |
|
|
143 |
" return: void\n", |
|
|
144 |
" '''\n", |
|
|
145 |
" output = model.predict(M[0:78080:32])\n", |
|
|
146 |
" label = L[0:78080:32]\n", |
|
|
147 |
"\n", |
|
|
148 |
" k = 0\n", |
|
|
149 |
" l = 0\n", |
|
|
150 |
"\n", |
|
|
151 |
" for i in range(len(label)):\n", |
|
|
152 |
" k = k + (output[i] - label[i])*(output[i] - label[i]) #square difference \n", |
|
|
153 |
"\n", |
|
|
154 |
" #a good guess\n", |
|
|
155 |
" if (output[i] > 5 and label[i] > 5):\n", |
|
|
156 |
" l = l + 1\n", |
|
|
157 |
" elif (output[i] < 5 and label[i] <5):\n", |
|
|
158 |
" l = l + 1\n", |
|
|
159 |
"\n", |
|
|
160 |
" print (\"l2 error:\", k/len(label), \"classification accuracy:\", l / len(label),l, len(label))" |
|
|
161 |
] |
|
|
162 |
}, |
|
|
163 |
{ |
|
|
164 |
"cell_type": "code", |
|
|
165 |
"execution_count": null, |
|
|
166 |
"metadata": {}, |
|
|
167 |
"outputs": [], |
|
|
168 |
"source": [ |
|
|
169 |
"for subjects in subjectList:\n", |
|
|
170 |
" FFT_Processing (subjects, channel, band, window_size, step_size, sample_rate)" |
|
|
171 |
] |
|
|
172 |
}, |
|
|
173 |
{ |
|
|
174 |
"cell_type": "markdown", |
|
|
175 |
"metadata": {}, |
|
|
176 |
"source": [ |
|
|
177 |
"## 3.Segment of preprocessed data\n", |
|
|
178 |
"* training dataset: 75 %\n", |
|
|
179 |
"* validation dataset: 12.5%\n", |
|
|
180 |
"* testing dataset: 12.5%\n", |
|
|
181 |
"\n", |
|
|
182 |
"Agrithom pool:\n", |
|
|
183 |
"* Support Vector Machine (which kernal?)\n", |
|
|
184 |
"* Ada-Boost\n", |
|
|
185 |
"\n", |
|
|
186 |
"Best practice could be refered to this paper: \n", |
|
|
187 |
"\n", |
|
|
188 |
"@article{alarcao2017emotions,\n", |
|
|
189 |
" title={Emotions recognition using EEG signals: A survey},\n", |
|
|
190 |
" author={Alarcao, Soraia M and Fonseca, Manuel J},\n", |
|
|
191 |
" journal={IEEE Transactions on Affective Computing},\n", |
|
|
192 |
" year={2017},\n", |
|
|
193 |
" publisher={IEEE}\n", |
|
|
194 |
"}" |
|
|
195 |
] |
|
|
196 |
}, |
|
|
197 |
{ |
|
|
198 |
"cell_type": "code", |
|
|
199 |
"execution_count": 54, |
|
|
200 |
"metadata": {}, |
|
|
201 |
"outputs": [ |
|
|
202 |
{ |
|
|
203 |
"name": "stdout", |
|
|
204 |
"output_type": "stream", |
|
|
205 |
"text": [ |
|
|
206 |
"training dataset: (468480, 70) (468480, 4)\n", |
|
|
207 |
"testing dataset: (78080, 70) (78080, 4)\n", |
|
|
208 |
"validation dataset: (78080, 70) (78080, 4)\n" |
|
|
209 |
] |
|
|
210 |
} |
|
|
211 |
], |
|
|
212 |
"source": [ |
|
|
213 |
"#for subjects in subjectList:\n", |
|
|
214 |
"data_training = []\n", |
|
|
215 |
"label_training = []\n", |
|
|
216 |
"data_testing = []\n", |
|
|
217 |
"label_testing = []\n", |
|
|
218 |
"data_validation = []\n", |
|
|
219 |
"label_validation = []\n", |
|
|
220 |
"\n", |
|
|
221 |
"for subjects in subjectList:\n", |
|
|
222 |
"\n", |
|
|
223 |
" with open('out\\s' + subjects + '.npy', 'rb') as file:\n", |
|
|
224 |
" sub = np.load(file)\n", |
|
|
225 |
" for i in range (0,sub.shape[0]):\n", |
|
|
226 |
" if i % 8 == 0:\n", |
|
|
227 |
" data_testing.append(sub[i][0])\n", |
|
|
228 |
" label_testing.append(sub[i][1])\n", |
|
|
229 |
" elif i % 8 == 1:\n", |
|
|
230 |
" data_validation.append(sub[i][0])\n", |
|
|
231 |
" label_validation.append(sub[i][1])\n", |
|
|
232 |
" else:\n", |
|
|
233 |
" data_training.append(sub[i][0])\n", |
|
|
234 |
" label_training.append(sub[i][1])\n", |
|
|
235 |
"\n", |
|
|
236 |
"np.save('out\\data_training', np.array(data_training), allow_pickle=True, fix_imports=True)\n", |
|
|
237 |
"np.save('out\\label_training', np.array(label_training), allow_pickle=True, fix_imports=True)\n", |
|
|
238 |
"print(\"training dataset:\", np.array(data_training).shape, np.array(label_training).shape)\n", |
|
|
239 |
"\n", |
|
|
240 |
"np.save('out\\data_testing', np.array(data_testing), allow_pickle=True, fix_imports=True)\n", |
|
|
241 |
"np.save('out\\label_testing', np.array(label_testing), allow_pickle=True, fix_imports=True)\n", |
|
|
242 |
"print(\"testing dataset:\", np.array(data_testing).shape, np.array(label_testing).shape)\n", |
|
|
243 |
"\n", |
|
|
244 |
"np.save('out\\data_validation', np.array(data_validation), allow_pickle=True, fix_imports=True)\n", |
|
|
245 |
"np.save('out\\label_validation', np.array(label_validation), allow_pickle=True, fix_imports=True)\n", |
|
|
246 |
"print(\"validation dataset:\", np.array(data_validation).shape, np.array(label_validation).shape)" |
|
|
247 |
] |
|
|
248 |
}, |
|
|
249 |
{ |
|
|
250 |
"cell_type": "markdown", |
|
|
251 |
"metadata": {}, |
|
|
252 |
"source": [ |
|
|
253 |
"## 4.Regression\n", |
|
|
254 |
"### 0. Loading Training and Testing dataset" |
|
|
255 |
] |
|
|
256 |
}, |
|
|
257 |
{ |
|
|
258 |
"cell_type": "code", |
|
|
259 |
"execution_count": 59, |
|
|
260 |
"metadata": {}, |
|
|
261 |
"outputs": [], |
|
|
262 |
"source": [ |
|
|
263 |
"with open('out\\data_training.npy', 'rb') as fileTrain:\n", |
|
|
264 |
" X = np.load(fileTrain)\n", |
|
|
265 |
" \n", |
|
|
266 |
"with open('out\\label_training.npy', 'rb') as fileTrainL:\n", |
|
|
267 |
" Y = np.load(fileTrainL)\n", |
|
|
268 |
" \n", |
|
|
269 |
"X = normalize(X)\n", |
|
|
270 |
"Z = np.ravel(Y[:, [1]])\n", |
|
|
271 |
"\n", |
|
|
272 |
"Arousal_Train = np.ravel(Y[:, [0]])\n", |
|
|
273 |
"Valence_Train = np.ravel(Y[:, [1]])\n", |
|
|
274 |
"Domain_Train = np.ravel(Y[:, [2]])\n", |
|
|
275 |
"Like_Train = np.ravel(Y[:, [3]])\n", |
|
|
276 |
"\n", |
|
|
277 |
"\n", |
|
|
278 |
"\n", |
|
|
279 |
"with open('out\\data_validation.npy', 'rb') as fileTrain:\n", |
|
|
280 |
" M = np.load(fileTrain)\n", |
|
|
281 |
" \n", |
|
|
282 |
"with open('out\\label_validation.npy', 'rb') as fileTrainL:\n", |
|
|
283 |
" N = np.load(fileTrainL)\n", |
|
|
284 |
"\n", |
|
|
285 |
"M = normalize(M)\n", |
|
|
286 |
"L = np.ravel(N[:, [1]])\n", |
|
|
287 |
"\n", |
|
|
288 |
"Arousal_Test = np.ravel(N[:, [0]])\n", |
|
|
289 |
"Valence_Test = np.ravel(N[:, [1]])\n", |
|
|
290 |
"Domain_Test = np.ravel(N[:, [2]])\n", |
|
|
291 |
"Like_Test = np.ravel(N[:, [3]])" |
|
|
292 |
] |
|
|
293 |
}, |
|
|
294 |
{ |
|
|
295 |
"cell_type": "markdown", |
|
|
296 |
"metadata": {}, |
|
|
297 |
"source": [ |
|
|
298 |
"\n", |
|
|
299 |
"### 1. Support Vector Regression\n", |
|
|
300 |
"* default setting, l1 error: 1.621761042477756 classification error: 0.6057377049180328 1478 2440" |
|
|
301 |
] |
|
|
302 |
}, |
|
|
303 |
{ |
|
|
304 |
"cell_type": "code", |
|
|
305 |
"execution_count": 15, |
|
|
306 |
"metadata": {}, |
|
|
307 |
"outputs": [ |
|
|
308 |
{ |
|
|
309 |
"data": { |
|
|
310 |
"text/plain": [ |
|
|
311 |
"SVR(C=1.0, cache_size=200, coef0=0.0, degree=3, epsilon=0.1, gamma='auto',\n", |
|
|
312 |
" kernel='rbf', max_iter=-1, shrinking=True, tol=0.001, verbose=False)" |
|
|
313 |
] |
|
|
314 |
}, |
|
|
315 |
"execution_count": 15, |
|
|
316 |
"metadata": {}, |
|
|
317 |
"output_type": "execute_result" |
|
|
318 |
} |
|
|
319 |
], |
|
|
320 |
"source": [ |
|
|
321 |
"clf = svm.SVR()\n", |
|
|
322 |
"clf.fit(X[0:468480:32], Z[0:468480:32]) " |
|
|
323 |
] |
|
|
324 |
}, |
|
|
325 |
{ |
|
|
326 |
"cell_type": "markdown", |
|
|
327 |
"metadata": {}, |
|
|
328 |
"source": [ |
|
|
329 |
"### 2. Random Forest Regression\n", |
|
|
330 |
"* n_estimators = 10, sample rate = 1/32, l1 error: 1.137919672131145 classification accuracy: 0.7774590163934426 1897 2440\n", |
|
|
331 |
"* n_estimators = 100, sample rate = 1/32, l1 error: 1.1029040163934432 classification accuracy: 0.8147540983606557 1988 2440\n", |
|
|
332 |
"* n_estimators = 100, min_samples_leaf=10, sample rate = 1/32, l1 error: 1.274458098574928 classification accuracy: 0.7622950819672131 1860 2440\n", |
|
|
333 |
"* n_estimators = 100, min_samples_leaf=50, sample rate = 1/32, l1 error: 1.4575897309409926 classification accuracy: 0.6823770491803278 1665 2440\n", |
|
|
334 |
"\n", |
|
|
335 |
"* n_estimators = 250, sample rate = 1/32, l1 error: 1.0905590819672137 classification accuracy: 0.830327868852459 2026 2440\n", |
|
|
336 |
"* n_estimators = 750, sample rate = 1/32, l1 error: 1.0953162021857932 classification accuracy: 0.8340163934426229 2035 2440\n", |
|
|
337 |
"* n_estimators = 750, sample rate = 1/8, l1 error: l1 error: 1.066982950819674 classification accuracy: 0.8217213114754098 2005 2440\n", |
|
|
338 |
"* __n_estimators = 512, sample rate = 1/32, l1 error: 1.092375304175206 classification accuracy: 0.8364754098360656 2041 2440\n", |
|
|
339 |
"__\n", |
|
|
340 |
"\n" |
|
|
341 |
] |
|
|
342 |
}, |
|
|
343 |
{ |
|
|
344 |
"cell_type": "code", |
|
|
345 |
"execution_count": 62, |
|
|
346 |
"metadata": { |
|
|
347 |
"scrolled": true |
|
|
348 |
}, |
|
|
349 |
"outputs": [ |
|
|
350 |
{ |
|
|
351 |
"name": "stdout", |
|
|
352 |
"output_type": "stream", |
|
|
353 |
"text": [ |
|
|
354 |
"l2 error: 1.876775658972537 classification accuracy: 0.8290983606557377 2023 2440\n" |
|
|
355 |
] |
|
|
356 |
} |
|
|
357 |
], |
|
|
358 |
"source": [ |
|
|
359 |
"Val_R = RandomForestRegressor(n_estimators=512, n_jobs=6)\n", |
|
|
360 |
"Val_R.fit(X[0:468480:32], Valence_Train[0:468480:32])\n", |
|
|
361 |
"testing (M, Valence_Test, Val_R)" |
|
|
362 |
] |
|
|
363 |
}, |
|
|
364 |
{ |
|
|
365 |
"cell_type": "code", |
|
|
366 |
"execution_count": 63, |
|
|
367 |
"metadata": { |
|
|
368 |
"scrolled": true |
|
|
369 |
}, |
|
|
370 |
"outputs": [ |
|
|
371 |
{ |
|
|
372 |
"name": "stdout", |
|
|
373 |
"output_type": "stream", |
|
|
374 |
"text": [ |
|
|
375 |
"l2 error: 2.0764509040715233 classification accuracy: 0.8266393442622951 2017 2440\n" |
|
|
376 |
] |
|
|
377 |
} |
|
|
378 |
], |
|
|
379 |
"source": [ |
|
|
380 |
"Aro_R = RandomForestRegressor(n_estimators=512, n_jobs=6)\n", |
|
|
381 |
"Aro_R.fit(X[0:468480:32], Arousal_Train[0:468480:32])\n", |
|
|
382 |
"testing (M, Arousal_Test, Aro_R)" |
|
|
383 |
] |
|
|
384 |
}, |
|
|
385 |
{ |
|
|
386 |
"cell_type": "code", |
|
|
387 |
"execution_count": 64, |
|
|
388 |
"metadata": { |
|
|
389 |
"scrolled": true |
|
|
390 |
}, |
|
|
391 |
"outputs": [ |
|
|
392 |
{ |
|
|
393 |
"name": "stdout", |
|
|
394 |
"output_type": "stream", |
|
|
395 |
"text": [ |
|
|
396 |
"l2 error: 1.813647083229937 classification accuracy: 0.8184426229508197 1997 2440\n" |
|
|
397 |
] |
|
|
398 |
} |
|
|
399 |
], |
|
|
400 |
"source": [ |
|
|
401 |
"Dom_R = RandomForestRegressor(n_estimators=512, n_jobs=6)\n", |
|
|
402 |
"Dom_R.fit(X[0:468480:32], Domain_Train[0:468480:32])\n", |
|
|
403 |
"testing (M, Domain_Test, Dom_R)" |
|
|
404 |
] |
|
|
405 |
}, |
|
|
406 |
{ |
|
|
407 |
"cell_type": "code", |
|
|
408 |
"execution_count": 65, |
|
|
409 |
"metadata": { |
|
|
410 |
"scrolled": true |
|
|
411 |
}, |
|
|
412 |
"outputs": [ |
|
|
413 |
{ |
|
|
414 |
"name": "stdout", |
|
|
415 |
"output_type": "stream", |
|
|
416 |
"text": [ |
|
|
417 |
"l2 error: 2.489005384276336 classification accuracy: 0.8512295081967213 2077 2440\n" |
|
|
418 |
] |
|
|
419 |
} |
|
|
420 |
], |
|
|
421 |
"source": [ |
|
|
422 |
"Lik_R = RandomForestRegressor(n_estimators=512, n_jobs=6)\n", |
|
|
423 |
"Lik_R.fit(X[0:468480:32], Like_Train[0:468480:32])\n", |
|
|
424 |
"testing (M, Like_Test, Lik_R)" |
|
|
425 |
] |
|
|
426 |
}, |
|
|
427 |
{ |
|
|
428 |
"cell_type": "markdown", |
|
|
429 |
"metadata": {}, |
|
|
430 |
"source": [ |
|
|
431 |
"### 3. AdaBoost Regression\n", |
|
|
432 |
"* n = 50, lr = 1.0: l2 error: 3.8454054839726695 classification accuracy: 0.6147540983606558 1500 2440\n", |
|
|
433 |
"* n = 50, lr = 1.0, square: l2 error: 4.015289218608164 classification accuracy: 0.5913934426229508 1443 2440\n", |
|
|
434 |
"* n = 500, lr = 1.0: l2 error: 3.8861651269012594 classification accuracy: 0.6155737704918033 1502 2440\n", |
|
|
435 |
"*\n", |
|
|
436 |
"*" |
|
|
437 |
] |
|
|
438 |
}, |
|
|
439 |
{ |
|
|
440 |
"cell_type": "code", |
|
|
441 |
"execution_count": 32, |
|
|
442 |
"metadata": {}, |
|
|
443 |
"outputs": [ |
|
|
444 |
{ |
|
|
445 |
"data": { |
|
|
446 |
"text/plain": [ |
|
|
447 |
"AdaBoostRegressor(base_estimator=None, learning_rate=0.01, loss='linear',\n", |
|
|
448 |
" n_estimators=5000, random_state=None)" |
|
|
449 |
] |
|
|
450 |
}, |
|
|
451 |
"execution_count": 32, |
|
|
452 |
"metadata": {}, |
|
|
453 |
"output_type": "execute_result" |
|
|
454 |
} |
|
|
455 |
], |
|
|
456 |
"source": [ |
|
|
457 |
"clf = AdaBoostRegressor(n_estimators=5000, learning_rate=0.01)\n", |
|
|
458 |
"clf.fit(X[0:468480:32], Z[0:468480:32])" |
|
|
459 |
] |
|
|
460 |
}, |
|
|
461 |
{ |
|
|
462 |
"cell_type": "markdown", |
|
|
463 |
"metadata": {}, |
|
|
464 |
"source": [ |
|
|
465 |
"### Calculating accuracy and loss" |
|
|
466 |
] |
|
|
467 |
}, |
|
|
468 |
{ |
|
|
469 |
"cell_type": "code", |
|
|
470 |
"execution_count": 58, |
|
|
471 |
"metadata": { |
|
|
472 |
"scrolled": true |
|
|
473 |
}, |
|
|
474 |
"outputs": [ |
|
|
475 |
{ |
|
|
476 |
"name": "stdout", |
|
|
477 |
"output_type": "stream", |
|
|
478 |
"text": [ |
|
|
479 |
"l2 error: 1.8832017200301692 classification accuracy: 0.8348360655737705 2037 2440\n" |
|
|
480 |
] |
|
|
481 |
} |
|
|
482 |
], |
|
|
483 |
"source": [ |
|
|
484 |
"output = Val_R.predict(M[0:78080:32])\n", |
|
|
485 |
"label = L[0:78080:32]\n", |
|
|
486 |
"\n", |
|
|
487 |
"k = 0\n", |
|
|
488 |
"l = 0\n", |
|
|
489 |
"\n", |
|
|
490 |
"for i in range(len(label)):\n", |
|
|
491 |
" k = k + (output[i] - label[i])*(output[i] - label[i]) #square difference \n", |
|
|
492 |
" \n", |
|
|
493 |
" #a good guess\n", |
|
|
494 |
" if (output[i] > 5 and label[i] > 5):\n", |
|
|
495 |
" l = l + 1\n", |
|
|
496 |
" elif (output[i] < 5 and label[i] <5):\n", |
|
|
497 |
" l = l + 1\n", |
|
|
498 |
"\n", |
|
|
499 |
"print (\"l2 error:\", k/len(label), \"classification accuracy:\", l / len(label),l, len(label))" |
|
|
500 |
] |
|
|
501 |
}, |
|
|
502 |
{ |
|
|
503 |
"cell_type": "markdown", |
|
|
504 |
"metadata": {}, |
|
|
505 |
"source": [ |
|
|
506 |
"### 4. ANN\n", |
|
|
507 |
"* 500 epoch 0.005 128 - 256 - 256 - 128 loss = 3.1\n", |
|
|
508 |
"* 3000 epoch 0.0001 256-512-512-256 Epoch: 3196 - Training Cost: 1.8372873067855835 Testing Cost: 2.231332540512085\n" |
|
|
509 |
] |
|
|
510 |
}, |
|
|
511 |
{ |
|
|
512 |
"cell_type": "code", |
|
|
513 |
"execution_count": null, |
|
|
514 |
"metadata": {}, |
|
|
515 |
"outputs": [], |
|
|
516 |
"source": [ |
|
|
517 |
"# Pull out columns for X (data to train with) and Y (value to predict)\n", |
|
|
518 |
"X_training = X[0:468480:32]\n", |
|
|
519 |
"Y_training = Z[0:468480:32]\n", |
|
|
520 |
"\n", |
|
|
521 |
"# Pull out columns for X (data to train with) and Y (value to predict)\n", |
|
|
522 |
"X_testing = M[0:78080:32]\n", |
|
|
523 |
"Y_testing = L[0:78080:32]\n", |
|
|
524 |
"\n", |
|
|
525 |
"# DO Scale both the training inputs and outputs\n", |
|
|
526 |
"X_scaled_training = pd.DataFrame (data = X_training).values\n", |
|
|
527 |
"Y_scaled_training = pd.DataFrame (data = Y_training).values\n", |
|
|
528 |
"\n", |
|
|
529 |
"# It's very important that the training and test data are scaled with the same scaler.\n", |
|
|
530 |
"X_scaled_testing = pd.DataFrame (data = X_testing).values\n", |
|
|
531 |
"Y_scaled_testing = pd.DataFrame (data = Y_testing).values" |
|
|
532 |
] |
|
|
533 |
}, |
|
|
534 |
{ |
|
|
535 |
"cell_type": "code", |
|
|
536 |
"execution_count": null, |
|
|
537 |
"metadata": {}, |
|
|
538 |
"outputs": [], |
|
|
539 |
"source": [ |
|
|
540 |
"# Turn off TensorFlow warning messages in program output\n", |
|
|
541 |
"os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n", |
|
|
542 |
"\n", |
|
|
543 |
"# Define model parameters\n", |
|
|
544 |
"t = time.time()\n", |
|
|
545 |
"learning_rate = 0.0001\n", |
|
|
546 |
"training_epochs = 5000\n", |
|
|
547 |
"display_step = 1\n", |
|
|
548 |
"\n", |
|
|
549 |
"# Define how many inputs and outputs are in our neural network\n", |
|
|
550 |
"number_of_inputs = 70\n", |
|
|
551 |
"number_of_outputs = 1\n", |
|
|
552 |
"\n", |
|
|
553 |
"# Define how many neurons we want in each layer of our neural network\n", |
|
|
554 |
"layer_1_nodes = 512\n", |
|
|
555 |
"layer_2_nodes = 1024\n", |
|
|
556 |
"layer_3_nodes = 1024\n", |
|
|
557 |
"layer_4_nodes = 512\n", |
|
|
558 |
"\n", |
|
|
559 |
"# Section One: Define the layers of the neural network itself\n", |
|
|
560 |
"RUN_NAME = str(int(round(t * 1000))) + '_' + str(layer_1_nodes) + '_' + str(layer_2_nodes) + '_' + str(layer_3_nodes) + '_' + str(layer_4_nodes) + '_' + str(learning_rate) + '_' + str(training_epochs) + '_' + 'Val'\n", |
|
|
561 |
"\n", |
|
|
562 |
"\n", |
|
|
563 |
"# Input Layer\n", |
|
|
564 |
"with tf.variable_scope('input'):\n", |
|
|
565 |
" X = tf.placeholder(tf.float32, shape=(None, number_of_inputs))\n", |
|
|
566 |
"\n", |
|
|
567 |
"# Layer 1\n", |
|
|
568 |
"with tf.variable_scope('layer_1'):\n", |
|
|
569 |
" weights = tf.get_variable(\"weights1\", shape=[number_of_inputs, layer_1_nodes], initializer=tf.contrib.layers.xavier_initializer())\n", |
|
|
570 |
" biases = tf.get_variable(name=\"biases1\", shape=[layer_1_nodes], initializer=tf.zeros_initializer())\n", |
|
|
571 |
" layer_1_output = tf.nn.relu(tf.matmul(X, weights) + biases)\n", |
|
|
572 |
"\n", |
|
|
573 |
"# Layer 2\n", |
|
|
574 |
"with tf.variable_scope('layer_2'):\n", |
|
|
575 |
" weights = tf.get_variable(\"weights2\", shape=[layer_1_nodes, layer_2_nodes], initializer=tf.contrib.layers.xavier_initializer())\n", |
|
|
576 |
" biases = tf.get_variable(name=\"biases2\", shape=[layer_2_nodes], initializer=tf.zeros_initializer())\n", |
|
|
577 |
" layer_2_output = tf.nn.relu(tf.matmul(layer_1_output, weights) + biases)\n", |
|
|
578 |
"\n", |
|
|
579 |
"# Layer 3\n", |
|
|
580 |
"with tf.variable_scope('layer_3'):\n", |
|
|
581 |
" weights = tf.get_variable(\"weights3\", shape=[layer_2_nodes, layer_3_nodes], initializer=tf.contrib.layers.xavier_initializer())\n", |
|
|
582 |
" biases = tf.get_variable(name=\"biases3\", shape=[layer_3_nodes], initializer=tf.zeros_initializer())\n", |
|
|
583 |
" layer_3_output = tf.nn.relu(tf.matmul(layer_2_output, weights) + biases)\n", |
|
|
584 |
"\n", |
|
|
585 |
"# Layer 4\n", |
|
|
586 |
"with tf.variable_scope('layer_4'):\n", |
|
|
587 |
" weights = tf.get_variable(\"weights4\", shape=[layer_3_nodes, layer_4_nodes], initializer=tf.contrib.layers.xavier_initializer())\n", |
|
|
588 |
" biases = tf.get_variable(name=\"biases4\", shape=[layer_4_nodes], initializer=tf.zeros_initializer())\n", |
|
|
589 |
" layer_4_output = tf.nn.relu(tf.matmul(layer_3_output, weights) + biases)\n", |
|
|
590 |
"\n", |
|
|
591 |
"# Output Layer\n", |
|
|
592 |
"with tf.variable_scope('output'):\n", |
|
|
593 |
" weights = tf.get_variable(\"weights5\", shape=[layer_4_nodes, number_of_outputs], initializer=tf.contrib.layers.xavier_initializer())\n", |
|
|
594 |
" biases = tf.get_variable(name=\"biases5\", shape=[number_of_outputs], initializer=tf.zeros_initializer())\n", |
|
|
595 |
" prediction = tf.matmul(layer_4_output, weights) + biases\n", |
|
|
596 |
"\n", |
|
|
597 |
"# Section Two: Define the cost function of the neural network that will be optimized during training\n", |
|
|
598 |
"\n", |
|
|
599 |
"with tf.variable_scope('cost'):\n", |
|
|
600 |
" Y = tf.placeholder(tf.float32, shape=(None, 1))\n", |
|
|
601 |
" cost = tf.reduce_mean(tf.squared_difference(prediction, Y))\n", |
|
|
602 |
"\n", |
|
|
603 |
"# Section Three: Define the optimizer function that will be run to optimize the neural network\n", |
|
|
604 |
"\n", |
|
|
605 |
"with tf.variable_scope('train'):\n", |
|
|
606 |
" optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)\n", |
|
|
607 |
"\n", |
|
|
608 |
"# Create a summary operation to log the progress of the network\n", |
|
|
609 |
"with tf.variable_scope('logging'):\n", |
|
|
610 |
" tf.summary.scalar('current_cost', cost)\n", |
|
|
611 |
" summary = tf.summary.merge_all()\n", |
|
|
612 |
"\n", |
|
|
613 |
"saver = tf.train.Saver()\n", |
|
|
614 |
"\n", |
|
|
615 |
"# Initialize a session so that we can run TensorFlow operations\n", |
|
|
616 |
"with tf.Session() as session:\n", |
|
|
617 |
"\n", |
|
|
618 |
" # Run the global variable initializer to initialize all variables and layers of the neural network\n", |
|
|
619 |
" session.run(tf.global_variables_initializer())\n", |
|
|
620 |
"\n", |
|
|
621 |
" # Create log file writers to record training progress.\n", |
|
|
622 |
" # We'll store training and testing log data separately.\n", |
|
|
623 |
" training_writer = tf.summary.FileWriter(\"./{}/logs/training\".format(RUN_NAME), session.graph)\n", |
|
|
624 |
" testing_writer = tf.summary.FileWriter(\"./{}/logs/testing\".format(RUN_NAME), session.graph)\n", |
|
|
625 |
"\n", |
|
|
626 |
" # Run the optimizer over and over to train the network.\n", |
|
|
627 |
" # One epoch is one full run through the training data set.\n", |
|
|
628 |
" for epoch in range(training_epochs):\n", |
|
|
629 |
"\n", |
|
|
630 |
" # Feed in the training data and do one step of neural network training\n", |
|
|
631 |
" session.run(optimizer, feed_dict={X: X_scaled_training, Y: Y_scaled_training})\n", |
|
|
632 |
"\n", |
|
|
633 |
" # Every few training steps, log our progress\n", |
|
|
634 |
" if epoch % display_step == 0:\n", |
|
|
635 |
" # Get the current accuracy scores by running the \"cost\" operation on the training and test data sets\n", |
|
|
636 |
" training_cost, training_summary = session.run([cost, summary], feed_dict={X: X_scaled_training, Y:Y_scaled_training})\n", |
|
|
637 |
" testing_cost, testing_summary = session.run([cost, summary], feed_dict={X: X_scaled_testing, Y:Y_scaled_testing})\n", |
|
|
638 |
"\n", |
|
|
639 |
" # Write the current training status to the log files (Which we can view with TensorBoard)\n", |
|
|
640 |
" training_writer.add_summary(training_summary, epoch)\n", |
|
|
641 |
" testing_writer.add_summary(testing_summary, epoch)\n", |
|
|
642 |
"\n", |
|
|
643 |
" # Print the current training status to the screen\n", |
|
|
644 |
" print(\"Epoch: {} - Training Cost: {} Testing Cost: {}\".format(epoch, training_cost, testing_cost))\n", |
|
|
645 |
"\n", |
|
|
646 |
" # Training is now complete!\n", |
|
|
647 |
"\n", |
|
|
648 |
" # Get the final accuracy scores by running the \"cost\" operation on the training and test data sets\n", |
|
|
649 |
" final_training_cost = session.run(cost, feed_dict={X: X_scaled_training, Y: Y_scaled_training})\n", |
|
|
650 |
" final_testing_cost = session.run(cost, feed_dict={X: X_scaled_testing, Y: Y_scaled_testing})\n", |
|
|
651 |
"\n", |
|
|
652 |
" print(\"Final Training cost: {}\".format(final_training_cost))\n", |
|
|
653 |
" print(\"Final Testing cost: {}\".format(final_testing_cost))\n", |
|
|
654 |
"\n", |
|
|
655 |
" save_path = saver.save(session, \"./{}/logs/trained_model.ckpt\".format(RUN_NAME))\n", |
|
|
656 |
" print(\"Model saved: {}\".format(save_path))\n", |
|
|
657 |
"\n", |
|
|
658 |
" '''\n", |
|
|
659 |
" # Now that the neural network is trained, let's use it to make predictions for our test data.\n", |
|
|
660 |
" # Pass in the X testing data and run the \"prediciton\" operation\n", |
|
|
661 |
" Y_predicted_scaled = session.run(prediction, feed_dict={X: X_scaled_testing})\n", |
|
|
662 |
" # Unscale the data back to it's original units (dollars)\n", |
|
|
663 |
" Y_predicted = Y_scaler.inverse_transform(Y_predicted_scaled)\n", |
|
|
664 |
" real_earnings = test_data_df['total_earnings'].values[0]\n", |
|
|
665 |
" predicted_earnings = Y_predicted[0][0]\n", |
|
|
666 |
" print(\"The actual earnings of Game #1 were ${}\".format(real_earnings))\n", |
|
|
667 |
" print(\"Our neural network predicted earnings of ${}\".format(predicted_earnings))\n", |
|
|
668 |
" \n", |
|
|
669 |
"'''\n", |
|
|
670 |
" model_builder = tf.saved_model.builder.SavedModelBuilder(\"./{}/exported_model\".format(RUN_NAME))\n", |
|
|
671 |
"\n", |
|
|
672 |
" inputs = {\n", |
|
|
673 |
" 'input': tf.saved_model.utils.build_tensor_info(X)\n", |
|
|
674 |
" }\n", |
|
|
675 |
" outputs = {\n", |
|
|
676 |
" 'earnings': tf.saved_model.utils.build_tensor_info(prediction)\n", |
|
|
677 |
" }\n", |
|
|
678 |
"\n", |
|
|
679 |
" signature_def = tf.saved_model.signature_def_utils.build_signature_def(\n", |
|
|
680 |
" inputs=inputs,\n", |
|
|
681 |
" outputs=outputs,\n", |
|
|
682 |
" method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME\n", |
|
|
683 |
" )\n", |
|
|
684 |
"\n", |
|
|
685 |
" model_builder.add_meta_graph_and_variables(\n", |
|
|
686 |
" session,\n", |
|
|
687 |
" tags=[tf.saved_model.tag_constants.SERVING],\n", |
|
|
688 |
" signature_def_map={\n", |
|
|
689 |
" tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_def\n", |
|
|
690 |
" }\n", |
|
|
691 |
" )\n", |
|
|
692 |
"\n", |
|
|
693 |
" model_builder.save()\n", |
|
|
694 |
" print('model saved')\n" |
|
|
695 |
] |
|
|
696 |
}, |
|
|
697 |
{ |
|
|
698 |
"cell_type": "code", |
|
|
699 |
"execution_count": null, |
|
|
700 |
"metadata": {}, |
|
|
701 |
"outputs": [], |
|
|
702 |
"source": [] |
|
|
703 |
} |
|
|
704 |
], |
|
|
705 |
"metadata": { |
|
|
706 |
"kernelspec": { |
|
|
707 |
"display_name": "Python 3", |
|
|
708 |
"language": "python", |
|
|
709 |
"name": "python3" |
|
|
710 |
}, |
|
|
711 |
"language_info": { |
|
|
712 |
"codemirror_mode": { |
|
|
713 |
"name": "ipython", |
|
|
714 |
"version": 3 |
|
|
715 |
}, |
|
|
716 |
"file_extension": ".py", |
|
|
717 |
"mimetype": "text/x-python", |
|
|
718 |
"name": "python", |
|
|
719 |
"nbconvert_exporter": "python", |
|
|
720 |
"pygments_lexer": "ipython3", |
|
|
721 |
"version": "3.6.5" |
|
|
722 |
} |
|
|
723 |
}, |
|
|
724 |
"nbformat": 4, |
|
|
725 |
"nbformat_minor": 2 |
|
|
726 |
} |