-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsgdwithlr_run.py
198 lines (172 loc) · 8.68 KB
/
sgdwithlr_run.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
# -*- coding: utf-8 -*-
"""Copy of SGDwithLR_run
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1TIKANaym9HBgXrt02o4sVYxBwf2G_zQ5
"""
import warnings
import tensorflow as tf
from keras_utils import SGDwithLR,AdamwithClip,RMSpropwithClip
from keras import models
from keras_focused import SimpleFocusedRNN
from keras.optimizers import RMSprop
from keras.datasets import imdb
from keras.models import Sequential
from keras.preprocessing import sequence
from keras import layers
from keras.layers import Flatten,SimpleRNN
import numpy as np
import numpy
from keras import backend as K
def lr_settings(all_lr=0.01,sigma_lr=0.01,mu_lr=0.01,mom=0.9,decay_dict_lr=0.1):
lr_dict = {'all':all_lr,
'focus-1/Sigma_current:0': sigma_lr,'focus-1/Mu_current:0': mu_lr,'focus-1/kernel:0': all_lr,
'focus-1/Sigma_prev:0': sigma_lr,'focus-1/Mu_prev:0': mu_lr,'focus-1/recurrent_kernel:0': all_lr,
'dense-3/Weights:0':all_lr}
#lr_dict = {'all':0.0001}
mom_dict = {'all':mom}
#decay_dict = {'all':0.9}
#mom_dict = {'all':0.9,'focus-1/Sigma:0': 0.25,'focus-1/Mu:0': 0.25,
# 'focus-2/Sigma:0': 0.25,'focus-2/Mu:0': 0.25}
decay_dict = {'all':all_lr, 'focus-1/Sigma_current:0': decay_dict_lr,'focus-1/Mu_current:0':decay_dict_lr,'focus-1/Sigma_prev:0': decay_dict_lr,'focus-1/Mu_prev:0': decay_dict_lr}
#'focus-2/Sigma_current:0': 0.1,'focus-2/Mu_current:0': 0.1,'focus-2/Sigma_prev:0': 0.1,'focus-2/Mu_prev:0': 0.1}
clip_dict = {'focus-1/Sigma_current:0':(0.01,1.0),'focus-1/Mu_current:0':(0.0,1.0),'focus-1/Sigma_prev:0':(0.01,1.0),'focus-1/Mu_prev:0':(0.0,1.0)}
#'focus-2/Sigma_current:0':(0.05,1.0),'focus-2/Mu_current:0':(0.0,1.0),'focus-2/Sigma_prev:0':(0.05,1.0),'focus-2/Mu_prev:0':(0.0,1.0)}
return lr_dict,mom_dict,decay_dict,clip_dict
from keras.callbacks import Callback
class PrintLayerVariableStats(Callback):
def __init__(self,name,var,stat_functions,stat_names,num):
self.layername = name
self.varname = var
self.stat_list = stat_functions
self.stat_names = stat_names
self.num=num
def setVariableName(self,name, var):
self.layername = name
self.varname = var
def on_train_begin(self, logs={}):
all_params = self.model.get_layer(self.layername)._trainable_weights
all_weights = self.model.get_layer(self.layername).get_weights()
#print("self.model",self.model)
#print("all_params",all_params)
#print("self.layername",self.layername)
#print("self.varname",self.varname)
i=self.num
if(i == 0):
stat_str = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("\nStats for kernel:0 ", stat_str)
if(i == 1):
stat_str_1 = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("Stats for Sigma_current:0 ", stat_str_1)
if(i == 2):
stat_str_2 = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("Stats for Mu_current:0 ", stat_str_2)
if(i == 3):
stat_str_3 = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("Stats for recurrent_kernel:0 ", stat_str_3)
#def on_batch_end(self, batch, logs={}):
# self.record.append(logs.get('loss'))
def on_epoch_end(self, epoch, logs={}):
all_weights = self.model.get_layer(self.layername).get_weights()
i=self.num
if(i == 0):
stat_str = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("\nStats for kernel:0 ", stat_str)
if(i == 1):
stat_str_1 = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("Stats for Sigma_current:0 ", stat_str_1)
if(i == 2):
stat_str_2 = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("Stats for Mu_current:0 ", stat_str_2)
if(i == 3):
stat_str_3 = [n+str(s(all_weights[i])) for s,n in zip(self.stat_list,self.stat_names)]
print("Stats for recurrent_kernel:0 ", stat_str_3)
from keras.optimizers import SGD
def build_model(N=64,mod='dense', optimizer_s='SGDwithLR',dropout=0.2, recurrent_dropout=0.2, init_sigma_current= 0.1, init_sigma_prev=0.1,num_epochs=15,sgd_settings=None,dataset_percantage=100):
top_words = 5000
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)
# truncate and pad input sequences
max_review_length = 500
if dataset_percantage == 100:
X_train = sequence.pad_sequences(X_train, maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test, maxlen=max_review_length)
elif dataset_percantage == 75:
X_train = sequence.pad_sequences(X_train[0:18750], maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test[0:18750], maxlen=max_review_length)
y_train = y_train[0:18750]
y_test = y_test[0:18750]
elif dataset_percantage == 50:
X_train = sequence.pad_sequences(X_train[0:12500], maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test[0:12500], maxlen=max_review_length)
y_train = y_train[0:12500]
y_test = y_test[0:12500]
elif dataset_percantage == 25:
X_train = sequence.pad_sequences(X_train[0:6250], maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test[0:6250], maxlen=max_review_length)
y_train = y_train[0:6250]
y_test = y_test[0:6250]
elif dataset_percantage == 10:
X_train = sequence.pad_sequences(X_train[0:2500], maxlen=max_review_length)
X_test = sequence.pad_sequences(X_test[0:2500], maxlen=max_review_length)
y_train = y_train[0:2500]
y_test = y_test[0:2500]
embedding_vecor_length = 32
model = Sequential()
model.add(layers.Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
#model.add(Flatten())
if mod=='simplernn':
model.add(SimpleRNN(100))
elif mod=='focused':
model.add(SimpleFocusedRNN(units=N,
name='focus-1',
kernel_initializer='he_normal',
dropout=dropout,
recurrent_dropout=recurrent_dropout,
init_sigma_current=init_sigma_current,
init_sigma_prev=init_sigma_prev))
model.add(layers.Dense(1,name='dense-3',activation='sigmoid'))
if optimizer_s == 'SGDwithLR' and sgd_settings != None:
decay_epochs =[3,5,8,11]
opt = SGDwithLR(lr=sgd_settings[0], momentum=sgd_settings[1],decay=sgd_settings[2],clips=sgd_settings[3],decay_epochs=decay_epochs,verbose=1)#, decay=None)
elif optimizer_s == 'AdamwithClip':
opt=AdamwithClip()
elif optimizer_s=='RMSpropwithClip':
opt = RMSpropwithClip(lr=0.001, rho=0.9, epsilon=None, decay=0.0,clips=clip_dict)
elif optimizer_s == 'adam':
opt='adam'
else:
opt= SGD(lr=0.01, momentum=0.9)#, decay=None)
print("opt= ",opt)
model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])
stat_func_name = ['max: ', 'mean: ', 'min: ', 'var: ', 'std: ']
stat_func_list = [np.max, np.mean, np.min, np.var, np.std]
callbacks = []
pr_0 = PrintLayerVariableStats("focus-1","kernel:0",stat_func_list,stat_func_name,0)
pr_1 = PrintLayerVariableStats("focus-1","Sigma_current:0",stat_func_list,stat_func_name,1)
pr_2 = PrintLayerVariableStats("focus-1","Mu_current:0",stat_func_list,stat_func_name,2)
pr_3 = PrintLayerVariableStats("focus-1","recurrent_kernel:0",stat_func_list,stat_func_name,3)
callbacks+=[pr_0,pr_1,pr_2,pr_3]
print(model.summary())
model.fit(X_train, y_train, epochs=num_epochs, batch_size=64,verbose=1,callbacks=callbacks)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
return model
for i in range(0,5):
dataset_percantage=50 #use dataset %10,%25,%50,%75
K.clear_session()
mod='focused'
N=100
all_lr=0.01
sigma_lr=0.01
mu_lr=0.01
mom=0.9
decay_dict_lr=0.1
numpy.random.seed(7)
# load the dataset but only keep the top n words, zero the rest
sgd_settings=lr_settings(all_lr=all_lr,sigma_lr=sigma_lr,mu_lr=mu_lr,mom=mom,decay_dict_lr=decay_dict_lr)
print(sgd_settings[0])
model = build_model(N,mod,optimizer_s='SGDwithLR',num_epochs=15,sgd_settings=sgd_settings,dataset_percantage=dataset_percantage)
all_lr+=0.001
sigma_lr+=0.001
mu_lr+=0.001