-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcold_start_NN.py
executable file
·273 lines (207 loc) · 9.39 KB
/
cold_start_NN.py
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
269
270
271
272
273
import pandas as pd
import numpy as np
import os
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import MinMaxScaler
from joblib import Parallel, delayed
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Input, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras import optimizers
import keras_tuner as kt
from keras_tuner.engine.hyperparameters import HyperParameters
from keras_tuner import RandomSearch
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
import utils
class Availability_Agent_Neural_Network_cold_start(BaseEstimator,TransformerMixin):
def __init__(self, day,start,stop, model,cut):
#print('\n>>>>>init() Neural_Network_availability called\n')
self.day = day
self.start = start
self.stop = stop
self.model = model
self.cut = cut
def fit(self,X,y=None):
return self
def transform(self,X,y=None):
#print('\n>>>>>transform Neural_Network_availability called\n')
data = X.copy()
# Split data into training and test set
train = data.iloc[self.cut:24*self.day,:]
test = data.iloc[self.start*24:self.stop*24,:]
train = train.sample(frac=1).reset_index(drop=True)
test = test.sample(frac=1).reset_index(drop=True)
X_train = train.drop('User_aval',axis=1)
X_test = test.drop('User_aval',axis=1)
y_train = train['User_aval'].values
y_test = test['User_aval'].values
# Normalize the data
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Create and fit the neural network model
model = self.model
model.fit(X_train_scaled, y_train,
batch_size=20,
epochs=50,
verbose=0,
validation_data=(X_test_scaled, y_test))
# Perform the prediction
y_pred = model.predict(X_test_scaled)
y_pred = np.squeeze(y_pred)
# Evaluate the prediction
auc_score = roc_auc_score(y_test, y_pred)
return auc_score
class Availability_Agent_Neural_Network_tuning_cold_start(BaseEstimator,TransformerMixin):
def __init__(self,day,cut):
#print('\n>>>>>init() Neural_Network_availability called\n')
self.day = day
self.cut = cut
def fit(self,X,y=None):
return self
def transform(self,X,y=None):
#print('\n>>>>>transform Neural_Network_availability called\n')
data = X.copy()
seed = 42
# Split data into training and test set
train = data.iloc[self.cut:24*self.day,:]
train = train.sample(frac=1).reset_index(drop=True)
X_train = train.drop('User_aval',axis=1)
y_train = train['User_aval'].values
# Normalize the training set
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
# Initialize the Hyperband Tuner
tuner_search=kt.Hyperband(utils.build_model,
objective='val_accuracy',
max_epochs=10,
factor=3,
overwrite = True,
directory='output',project_name="Aval",)
# Stop training if the "val_loss" has not improved in 5 epochs
stop_early = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
tuner_search.search(X_train_scaled,y_train,epochs=50,validation_split=0.2,callbacks=[stop_early])
# Save best hyperparameters
best_hps=tuner_search.get_best_hyperparameters(num_trials=1)[0]
# Get the best model
model=tuner_search.get_best_models(num_models=1)[0]
# Get the summary of the model
model.summary()
return model
class Usage_Agent_Neural_Network_tuning_cold_start(BaseEstimator,TransformerMixin):
def __init__(self,num_devices,day,cut):
#print('\n>>>>>init() Neural_Network_usage_tuning called\n')
self.num_devices = num_devices
self.day = day
self.cut = cut
def fit(self,X,y=None):
return self
def transform(self,X,y=None):
#print('\n>>>>>transform Neural_Network_usage_tuning called\n')
data = X.copy()
# Get device usage columns
columns = data.columns.tolist()[-self.num_devices:]
best_hps_dict = {}
model_dict = {}
for col in columns:
train = data.iloc[self.cut:24*self.day,:]
X_train = train.drop(col,axis=1)
y_train = train[col].values
# Normalize training data
scaler = MinMaxScaler(feature_range = (0,1))
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
# Initialize the Hyperband Tuner
tuner_search=kt.Hyperband(utils.build_model_usage,
objective='val_accuracy',
max_epochs=20,
factor=3,
overwrite = True,
#directory='output_'+str(col),
directory=os.path.normpath('C:/Users/loeschml/Documents'),
project_name=str(col))
# Stop training if the "val_loss" has not improved in 5 epochs
stop_early = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
tuner_search.search(X_train_scaled,y_train,epochs=50,validation_split=0.2,callbacks=[stop_early])
# Save the best hyperparameters
best_hps=tuner_search.get_best_hyperparameters(num_trials=1)[0]
# Get the best model
model=tuner_search.get_best_models(num_models=1)[0]
# Get the summary of the model
model.summary()
best_hps_dict.update({col:best_hps})
model_dict.update({col:model})
return model_dict
class Usage_Agent_Neural_Network_cold_start(BaseEstimator,TransformerMixin):
def __init__(self,num_devices,day,start,stop,model_dict,cut):
#print('\n>>>>>init() Neural_Network_usage called\n')
self.num_devices = num_devices
self.day = day
self.model_dict = model_dict
self.start = start
self.stop = stop
self.cut = cut
def fit(self,X,y=None):
return self
def transform(self,X,y=None):
#print('\n>>>>>transform Neural_Network_usage called\n')
data = X.copy()
# Get device usage columns
columns = data.columns.tolist()[-self.num_devices:]
# Function to parallel the loop over the data columns indicating the usage of the devices
# to predict the device usage using a neural network model
def NN_device(data,col):
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score
usage_pred = pd.DataFrame()
auc_scores = pd.DataFrame()
# Split data into training and test set
train = data.iloc[self.cut:24*self.day,:]
test = data.iloc[24*self.start:24*self.stop,:]
X_train = train.drop(col,axis=1)
X_test = test.drop(col,axis=1)
y_train = train[col].values
y_test = test[col].values
# Normalize the training set
scaler = MinMaxScaler(feature_range = (0,1))
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Create and fit the model
batch_size = 64
epochs = 80
model = self.model_dict.get(col)
model.fit(X_train_scaled, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=0,
validation_split=0.2)
# Perform the prediction
y_pred = model.predict(X_test_scaled)
y_pred = np.squeeze(y_pred)
# Evaluate the model
auc = roc_auc_score(y_test, y_pred)
usage_pred[col] = y_pred
auc_scores = auc_scores.append({col:auc},ignore_index = True)
return usage_pred, auc_scores
# Call the NN_device function to get the usage prediction and its evaluation for each device
results = Parallel(n_jobs=29,backend='threading',verbose=2)(delayed(NN_device)(data,col) for col in columns)
# Convert the format of the results
flat = []
for l in results:
flat.extend(l)
result1 = []
result2 = []
for i in range(len(flat)):
if i%2==0:
result1.append(flat[i])
else:
result2.append(flat[i])
usage_pred = pd.concat(result1,axis=1)
auc_scores = pd.concat(result2,axis=1)
return auc_scores, usage_pred