forked from RubensZimbres/Repo-2016
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython - Keras Multi Layer Perceptron
More file actions
71 lines (57 loc) · 2.16 KB
/
Python - Keras Multi Layer Perceptron
File metadata and controls
71 lines (57 loc) · 2.16 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
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.callbacks import LearningRateScheduler,EarlyStopping, ModelCheckpoint
from keras import backend as K
epochs = 50
learning_rate = 0.01
decay_rate = 2e-6
momentum = 0.9
reg=0.001
sd=[]
class LossHistory(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.losses = [1,1]
def on_epoch_end(self, batch, logs={}):
self.losses.append(logs.get('loss'))
sd.append(step_decay(len(self.losses)))
print('learning rate:', step_decay(len(self.losses)))
print('derivative of loss:', 2*np.sqrt((self.losses[-1])))
def my_init(shape, name=None):
value = np.random.random(shape)
return K.variable(value, name=name)
def step_decay(losses):
if float(2*np.sqrt(np.array(history.losses[-1])))<1.1:
lrate=0.01*1/(1+0.1*len(history.losses))
momentum=0.2
decay_rate=0.0
return lrate
else:
lrate=0.01
return lrate
model = Sequential()
model.add(Dense(16, input_dim=12, init=my_init))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(Activation('softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.97, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,metrics=['accuracy'])
aa=pd.read_csv('questao1NN.csv',sep=',',header=0)
y_train=np.array(pd.get_dummies(aa['Desligamento'][0:1800]))
y_test=np.array(pd.get_dummies(aa['Desligamento'][1801:1999]))
X_train=np.array(aa.ix[:,2:14][0:1800])
X_test=np.array(aa.ix[:,2:14][1801:1999])
history=LossHistory()
lrate=LearningRateScheduler(step_decay)
model.fit(X_train, y_train,nb_epoch=epochs,batch_size=100,callbacks=[history,lrate])
model.evaluate(X_train, y_train, batch_size=16)
model.predict(X_train, batch_size=32, verbose=0)
pred2=model.predict_classes(X_test, batch_size=32, verbose=0)
print('Accuracy Test Set=',len(np.where(pred2-aa['Desligamento'][1801:1999]==0)[0])/198)
''' Must apply a threshold to deal wih imbalanced classes'''