-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py~
208 lines (160 loc) · 6.5 KB
/
test.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
import numpy as np
from semval2016_data import *
import tensorflow as tf
(X_train, y_train), (X_test, y_test) = load_a(test_split=0.2,cnn=False,sentiment_embeddings=False,Load_Test=False)
print(len(X_train), 'train sequences')
print(len(X_test), 'test sequences')
print('X_train shape:', X_train.shape)
print('X_test shape:', X_test.shape)
#hyperparameters
lr = 0.1
training_iters = 5
batch_size = 32
display_step = 1
n_inputs = 200
n_steps = 40
n_hidden_units = 100
n_classes = 3
# tf Graph input
x = tf.placeholder(tf.float32,[None,n_steps,n_inputs])
y = tf.placeholder(tf.float32,[None,n_classes])
#Define weights
weights = {
#(200,100)
'in':tf.Variable(tf.random_normal([n_inputs,n_hidden_units])),
#(128,10)
'out':tf.Variable(tf.random_normal([n_hidden_units,n_classes]))
}
biases = {
#(128,)
'in':tf.Variable(tf.constant(0.1,shape=[n_hidden_units,])),
#(10,)
'out':tf.Variable(tf.constant(0.1,shape=[n_classes,]))
}
def RNN(X,weights,biases):
# hidden layer for input to cell
#############################################
#X(128 batch,28 steps, 28 inputs)
# ==> (128*28,28 inputs)
X = tf.reshape(X,[-1,n_inputs])
# X_in ==> (128batch*28 steps,128 hidden)
X_in = tf.matmul(X,weights['in'])+biases['in']
# X_in ==> (128batch,28 steps,128 hidden)
X_in = tf.reshape(X_in,[-1,n_steps,n_hidden_units])
#cell
#############################################
# lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units,forget_bias=1.0,state_is_tuple=True)
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units,forget_bias=1.0)
# lstm cell is devided into two parts(c_state,m_state)
_init_state = lstm_cell.zero_state(batch_size,dtype=tf.float32)
outputs,states = tf.nn.dynamic_rnn(lstm_cell,X_in,initial_state=_init_state,time_major=False)
# hidden layer for output as the final results
###########################################################
##results = tf.matmul(states[1],weights['out'])+biases['out']
# or
# unpack to list[(batch,outputs)..]*steps
outputs = tf.unpack(tf.transpose(outputs,[1,0,2])) #state is the last outputs
results = tf.matmul(outputs[-1],weights['out'])+biases['out']
return results
pred = RNN(x,weights,biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
# Compute the number of training steps
step_in_epoch, steps_per_epoch = 0, int(math.floor(len(X_train)/batch_size))
num_steps = steps_per_epoch*config.training_iters
global_step = 0
train_step = 0
# Initialize the TensorFlow session
sess = tf.Session()
# Initialize the session
init = tf.initialize_all_variables()
sess.run(init)
for _ in range(num_steps):
################################################################
########################## TRAINING ############################
################################################################
index_start = step_in_epoch*batch_size
index_end = index_start+batch_size
# Actual training of the network
_, train_step, train_loss, learning_rate, train_summary = sess.run(
[train_op,
global_step,
model.loss,
model.learning_rate,
model.train_summary_op],
feed_dict={
model.inputs: X_train[index_start:index_end,],
model.targets: y_train[index_start:index_end,],
}
)
print("[%s] Step %05i/%05i, LR = %.2e, Loss = %.5f" %
(datetime.now().strftime("%Y-%m-%d %H:%M"), train_step, num_steps, learning_rate, train_loss))
# Save summaries to disk
summary_writer.add_summary(train_summary, train_step)
if train_step % 1000 == 0 and train_step > 0:
path = saver.save(sess, checkpoint_prefix, global_step=train_step)
print("[%s] Saving TensorFlow model checkpoint to disk." % datetime.now().strftime("%Y-%m-%d %H:%M"))
step_in_epoch += 1
################################################################
############### MODEL TESTING ON EVALUATION DATA ###############
################################################################
if step_in_epoch == steps_per_epoch:
# End of epoch, check some validation examples
print("#" * 100)
print("MODEL TESTING ON VALIDATION DATA (%i examples):" % num_validation)
for validation_step in range(int(math.floor(num_validation/config.batch_size))):
index_start = validation_step*config.batch_size
index_end = index_start+config.batch_size
validation_loss, predictions = sess.run([model.loss, model.predictions],
feed_dict={
model.inputs: X_validation[index_start:index_end,],
model.targets: y_validation[index_start:index_end,],
}
)
# Show a plot of the ground truth and prediction of the singla
if validation_step == 0:
plt.clf()
plt.title("Ground Truth and Predictions")
plt.plot(y_validation[index_start:index_start+50,0], label="signal 0 (input)")
plt.plot(predictions[0:50,0], ls='--', label="signal 0 (prediction)")
plt.plot(y_validation[index_start:index_start+50,1], label="signal 1 (input)")
plt.plot(predictions[0:50,1], ls='--', label="signal 1 (prediction)")
legend = plt.legend(frameon=True)
legend.get_frame().set_facecolor('white')
plt.draw()
plt.pause(0.001)
print("[%s] Validation Step %03i. Loss = %.5f" % (datetime.now().strftime("%Y-%m-%d %H:%M"), validation_step, validation_loss))
# Reset for next epoch
step_in_epoch = 0
# Shuffle training data
perm = np.arange(num_train)
np.random.shuffle(perm)
X_train = X_train[perm]
y_train = y_train[perm]
print("#" * 100)
# Destroy the graph and close the session
ops.reset_default_graph()
sess.close()
'''
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
train_op = tf.train.AdamOptimizer(lr).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred,tf.float32))
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
step = 0
while step*batch_size < training_iters:
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
batch_xs = batch_xs.reshape([batch_size,n_steps,n_inputs])
sess.run([train_op],feed_dict={
x:batch_xs,
y:batch_ys,
})
if step % 20 == 0:
print(sess.run(accuracy,feed_dict={
x:batch_xs,
y:batch_ys,
}))
step += 1
'''