forked from IanMadlenya/MRAE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathneuralNetwork.py
More file actions
269 lines (229 loc) · 10.4 KB
/
neuralNetwork.py
File metadata and controls
269 lines (229 loc) · 10.4 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# coding: utf-8
# # Neural network
#
# - Implement denoising autoencoder
# - Track metrics
# In[ ]:
from keras import regularizers
from keras.layers import Input
from keras.layers.core import Dense
from keras.models import Model
from neuralNetwork_smoothness import measureSmoothness
import itertools
import logging
import numpy as np
import scipy as sp
import pandas as pd
import neuralNetwork_utils as ut
# ## Neural Network core
# In[ ]:
class BasicAutoencoder:
def __init__(self,
scalingFactor,
encoding_dim,
denoising,
dropoutProba,
optimizer,
loss,
nb_epoch,
batch_size,
activFirstLayer,
activSecondLayer,
trainUB,
validationLB,
validationUB,
testLB):
# Neural network parameters
## Input
self.scalingFactor = scalingFactor
self.trainUB = trainUB
self.validationLB = validationLB
self.validationUB = validationUB
self.testLB = testLB
self.stockNames = None
self.x_train = None
self.y_train = None
self.test = None
## Network behaviour: data reduction vs data augmentation
self.encoding_dim = encoding_dim
self.denoising = denoising
self.dropoutProba = dropoutProba
## Network technical specs
self.optimizer = optimizer
self.loss = loss
self.nb_epoch = nb_epoch
self.batch_size = batch_size
self.activFirstLayer = activFirstLayer
self.activSecondLayer = activSecondLayer
## Network features
self.autoencoder = None
self.history = None
## Network results
self.score = None
self.predictionTrain = None
self.predictionTest = None
self.residualTrain = None
self.residualTest = None
self.normalTests = None
self.smoothnessGlobal = -1
self.smoothnessTail = -1
##
self.parametersSet = self.getParametersSet()
# Inner neural network methods
def buildAutoencoder(self,
inputDim):
'''
Network definition layer by layer
'''
# Input placeholder
input_data = Input(shape=(inputDim,))
# "encoded" is the encoded representation of the input
encoded = Dense(self.encoding_dim,
activation=self.activFirstLayer,
activity_regularizer=regularizers.activity_l1(10e-5))(input_data)
# "decoded" is the lossy reconstruction of the input
decoded = Dense(inputDim, activation=self.activSecondLayer)(encoded)
# This model maps an input to its reconstruction
self.autoencoder = Model(input=input_data, output=decoded)
self.autoencoder.compile(optimizer=self.optimizer,
loss=self.loss)
return True
## Fitting process
def fitAutoencoder(self,
validation, # Dissociate train in x y to account for denoising eventuality
verbose=0):
self.history = self.autoencoder.fit(self.x_train.as_matrix(), # Noisy input or not
self.y_train.as_matrix(), # Clear output in any case
nb_epoch=self.nb_epoch,
batch_size=self.batch_size,
shuffle=False,
verbose=verbose,
validation_data=(validation.as_matrix(),
validation.as_matrix()))
return True
## Test process
def predict(self,
inputToPredict):
return pd.DataFrame(self.autoencoder.predict(inputToPredict.as_matrix()),
index=inputToPredict.index.values,
columns=inputToPredict.columns.values)
# Global process
## Full process: ML and metrics tracking
def learningProcess(self, bplotPreds=True, bplotError=True, bplotResiduals=True):
self.runML()
self.setPredsAndResiduals()
self.getMetrics()
self.saveOutput()
self.displayMetrics(bplotPreds=bplotPreds,
bplotError=bplotError,
bplotResiduals=bplotResiduals)
self.releaseResources()
return True
## ML process
def runML(self, stocksFile='../donnees/clean/RET_PX_LAST.csv'):
# Neural network inputs
inputNN = ut.getInputs(scalingFactor=self.scalingFactor,
stocksFile=stocksFile)
self.stockNames = inputNN.columns.values
train, validation, self.test = ut.splitData(inputNN,
self.trainUB,
self.validationLB,
self.validationUB,
self.testLB)
# Deal with denoising
self.y_train = train
if self.denoising: self.x_train = ut.noiseTrain2(train=train,
p=self.dropoutProba)
else: self.x_train = train
self.buildAutoencoder(inputDim=inputNN.shape[1])
self.fitAutoencoder(validation=validation)
return True
# Utils
## Plot and log purpose
def displayMetrics(self,
outputDir='../results/dae/neuralNetwork/graphes/',
bplotPreds=True,
bplotError=True,
bplotResiduals=True):
logger.info('%s;%f;%f', '_'.join(self.parametersSet), self.score, self.smoothness)
if bplotPreds: ut.plotPreds(self.predictionTest,
self.test,
outputDir=outputDir,
parametersSet=self.parametersSet)
if bplotError: ut.plotError(self.history,
outputDir=outputDir,
parametersSet=self.parametersSet)
if bplotResiduals: ut.plotResiduals(residuals=self.residualTrain,
outputDir=outputDir,
parametersSet=self.parametersSet,
who='train')
if bplotResiduals: ut.plotResiduals(residuals=self.residualTest,
outputDir=outputDir,
parametersSet=self.parametersSet,
who='test')
return True
## Score purpose
def getMetrics(self):
# Score: loss on test set
self.score = self.autoencoder.evaluate(self.test.as_matrix(),
self.test.as_matrix(),
verbose=0)
# Score: smoothness on test set
self.smoothness = measureSmoothness(dataFrame=self.residualTest, nMax=300, normThreshold=0.005)
return True
def getParametersSet(self, strForm=True):
parametersSet = [self.scalingFactor, self.encoding_dim, self.denoising, self.dropoutProba, self.optimizer,
self.loss, self.nb_epoch, self.batch_size, self.activFirstLayer, self.activSecondLayer]
if strForm: parametersSet = [str(parameter) for parameter in parametersSet]
return parametersSet
def releaseResources(self):
self.predictionTrain = None
self.predictionTest = None
self.residualTrain = None
self.residualTest = None
self.x_train = None
self.y_train = None
self.test = None
return True
def saveOutput(self, outputDir='../results/dae/neuralNetwork/predictions/'):
rescaledTest = self.predictionTest / self.scalingFactor
rescaledTest.to_csv(path_or_buf=outputDir + 'test_' + '_'.join(self.parametersSet) + '.csv',
sep=';',
index_label='Date')
rescaledTrain = self.predictionTrain / self.scalingFactor
rescaledTrain.to_csv(path_or_buf=outputDir + 'train_' + '_'.join(self.parametersSet) + '.csv',
sep=';',
index_label='Date')
return True
def setPredsAndResiduals(self):
# Predicitions on test and train
# Train predictions are only useful from the finance point of view,
# but strictly irrelevant from the machine learning point of view
self.predictionTrain = self.predict(inputToPredict=self.y_train) # Clear input
self.predictionTest = self.predict(inputToPredict=self.test)
# Residuals
self.residualTrain = self.y_train - self.predictionTrain
self.residualTest = self.test - self.predictionTest
return True
# In[ ]:
# Split denoising/non denoising ae in a fashion and easy way
def processFitting(params, denoising):
encoding_dim, nb_epoch, batch_size, dropoutProba = (None, None, None, None)
if not denoising: encoding_dim, nb_epoch, batch_size = params
else: encoding_dim, nb_epoch, batch_size, dropoutProba = params
autoencoder = BasicAutoencoder(scalingFactor=scalingFactor,
encoding_dim=encoding_dim,
denoising=denoising,
dropoutProba=dropoutProba,
optimizer=optimizer,
loss=loss,
nb_epoch=nb_epoch,
batch_size=batch_size,
activFirstLayer=activFirstLayer,
activSecondLayer=activSecondLayer,
trainUB=trainUB,
validationLB=validationLB,
validationUB=validationUB,
testLB=testLB)
autoencoder.learningProcess(bplotPreds=False, bplotError=True, bplotResiduals=False)
return True