Skip to content

Commit cef6f84

Browse files
committed
add color bar
1 parent 5537f67 commit cef6f84

File tree

3 files changed

+164
-2
lines changed

3 files changed

+164
-2
lines changed

tensorflowTUT/tf20_RNN2/full_code.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def RNN(X, weights, biases):
6767
# basic LSTM Cell.
6868
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden_units, forget_bias=1.0, state_is_tuple=True)
6969
# lstm cell is divided into two parts (c_state, h_state)
70-
_init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32)
70+
init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32)
7171

7272
# You have 2 options for following step.
7373
# 1: tf.nn.rnn(cell, inputs);
@@ -77,7 +77,7 @@ def RNN(X, weights, biases):
7777
# In here, we go for option 2.
7878
# dynamic_rnn receive Tensor (batch, steps, inputs) or (steps, batch, inputs) as X_in.
7979
# Make sure the time_major is changed accordingly.
80-
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=_init_state, time_major=False)
80+
outputs, final_state = tf.nn.dynamic_rnn(lstm_cell, X_in, initial_state=init_state, time_major=False)
8181

8282
# hidden layer for output as the final results
8383
#############################################
+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# visit https://morvanzhou.github.io/tutorials/ for more!
2+
3+
4+
# 22 scope (name_scope/variable_scope)
5+
from __future__ import print_function
6+
import tensorflow as tf
7+
tf.set_random_seed(1) # reproducible
8+
9+
10+
class TrainConfig:
11+
batch_size = 20
12+
time_steps = 20
13+
input_size = 10
14+
output_size = 2
15+
cell_size = 11
16+
learning_rate = 0.01
17+
18+
19+
class TestConfig(TrainConfig):
20+
time_steps = 1
21+
22+
23+
class RNN(object):
24+
25+
def __init__(self, config):
26+
self._batch_size = config.batch_size
27+
self._time_steps = config.time_steps
28+
self._input_size = config.input_size
29+
self._output_size = config.output_size
30+
self._cell_size = config.cell_size
31+
self._lr = config.learning_rate
32+
self._built_RNN()
33+
34+
def _built_RNN(self):
35+
with tf.variable_scope('inputs'):
36+
self._xs = tf.placeholder(tf.float32, [self._batch_size, self._time_steps, self._input_size], name='xs')
37+
self._ys = tf.placeholder(tf.float32, [self._batch_size, self._time_steps, self._output_size], name='ys')
38+
with tf.name_scope('RNN'):
39+
with tf.variable_scope('input_layer'):
40+
l_in_x = tf.reshape(self._xs, [-1, self._input_size], name='2_2D') # (batch*n_step, in_size)
41+
# Ws (in_size, cell_size)
42+
Wi = self._weight_variable([self._input_size, self._cell_size])
43+
print(Wi.name)
44+
# bs (cell_size, )
45+
bi = self._bias_variable([self._cell_size, ])
46+
# l_in_y = (batch * n_steps, cell_size)
47+
with tf.name_scope('Wx_plus_b'):
48+
l_in_y = tf.matmul(l_in_x, Wi) + bi
49+
l_in_y = tf.reshape(l_in_y, [-1, self._time_steps, self._cell_size], name='2_3D')
50+
51+
with tf.variable_scope('lstm_cell'):
52+
cell = tf.nn.rnn_cell.BasicRNNCell(self._cell_size)
53+
with tf.name_scope('initial_state'):
54+
self._cell_initial_state = cell.zero_state(self._batch_size, dtype=tf.float32)
55+
56+
self.cell_outputs = []
57+
cell_state = self._cell_initial_state
58+
for t in range(self._time_steps):
59+
if t > 0: tf.get_variable_scope().reuse_variables()
60+
cell_output, cell_state = cell(l_in_y[:, t, :], cell_state)
61+
self.cell_outputs.append(cell_output)
62+
self._cell_final_state = cell_state
63+
64+
with tf.variable_scope('output_layer'):
65+
# cell_outputs_reshaped (BATCH*TIME_STEP, CELL_SIZE)
66+
cell_outputs_reshaped = tf.reshape(tf.concat(1, self.cell_outputs), [-1, self._cell_size])
67+
Wo = self._weight_variable((self._cell_size, self._output_size))
68+
bo = self._bias_variable((self._output_size,))
69+
product = tf.matmul(cell_outputs_reshaped, Wo) + bo
70+
# _pred shape (batch*time_step, output_size)
71+
self._pred = tf.nn.relu(product) # for displacement
72+
73+
with tf.name_scope('cost'):
74+
_pred = tf.reshape(self._pred, [self._batch_size, self._time_steps, self._output_size])
75+
mse = self.ms_error(_pred, self._ys)
76+
mse_ave_across_batch = tf.reduce_mean(mse, 0)
77+
mse_sum_across_time = tf.reduce_sum(mse_ave_across_batch, 0)
78+
self._cost = mse_sum_across_time
79+
self._cost_ave_time = self._cost / self._time_steps
80+
81+
with tf.name_scope('trian'):
82+
self._lr = tf.convert_to_tensor(self._lr)
83+
self.train_op = tf.train.AdamOptimizer(self._lr).minimize(self._cost)
84+
85+
@staticmethod
86+
def ms_error(y_pre, y_target):
87+
return tf.square(tf.sub(y_pre, y_target))
88+
89+
@staticmethod
90+
def _weight_variable(shape, name='weights'):
91+
initializer = tf.random_normal_initializer(mean=0., stddev=0.5, )
92+
return tf.get_variable(shape=shape, initializer=initializer, name=name)
93+
94+
@staticmethod
95+
def _bias_variable(shape, name='biases'):
96+
initializer = tf.constant_initializer(0.1)
97+
return tf.get_variable(name=name, shape=shape, initializer=initializer)
98+
99+
100+
if __name__ == '__main__':
101+
train_config = TrainConfig()
102+
test_config = TestConfig()
103+
104+
# the wrong method to reuse parameters in train rnn
105+
with tf.variable_scope('train_rnn'):
106+
train_rnn1 = RNN(train_config)
107+
with tf.variable_scope('test_rnn'):
108+
test_rnn1 = RNN(test_config)
109+
110+
# the right method to reuse parameters in train rnn
111+
with tf.variable_scope('rnn') as scope:
112+
sess = tf.Session()
113+
train_rnn2 = RNN(train_config)
114+
scope.reuse_variables()
115+
test_rnn2 = RNN(test_config)
116+
sess.run(tf.initialize_all_variables())
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# visit https://morvanzhou.github.io/tutorials/ for more!
2+
3+
4+
# 22 scope (name_scope/variable_scope)
5+
from __future__ import print_function
6+
import tensorflow as tf
7+
tf.set_random_seed(1) # reproducible
8+
9+
with tf.name_scope("a_name_scope"):
10+
initializer = tf.constant_initializer(value=1)
11+
var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32, initializer=initializer)
12+
var2 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
13+
var21 = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)
14+
var22 = tf.Variable(name='var2', initial_value=[2.2], dtype=tf.float32)
15+
16+
17+
with tf.Session() as sess:
18+
sess.run(tf.initialize_all_variables())
19+
print(var1.name) # var1:0
20+
print(sess.run(var1)) # [ 1.]
21+
print(var2.name) # a_name_scope/var2:0
22+
print(sess.run(var2)) # [ 2.]
23+
print(var21.name) # a_name_scope/var2_1:0
24+
print(sess.run(var21)) # [ 2.0999999]
25+
print(var22.name) # a_name_scope/var2_2:0
26+
print(sess.run(var22)) # [ 2.20000005]
27+
28+
29+
with tf.variable_scope("a_variable_scope") as scope:
30+
initializer = tf.constant_initializer(value=3)
31+
var3 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
32+
var4 = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
33+
var4_reuse = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
34+
scope.reuse_variables()
35+
var3_reuse = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
36+
37+
with tf.Session() as sess:
38+
sess.run(tf.initialize_all_variables())
39+
print(var3.name) # a_variable_scope/var3:0
40+
print(sess.run(var3)) # [ 3.]
41+
print(var4.name) # a_variable_scope/var4:0
42+
print(sess.run(var4)) # [ 4.]
43+
print(var4_reuse.name) # a_variable_scope/var4_1:0
44+
print(sess.run(var4_reuse)) # [ 4.]
45+
print(var3_reuse.name) # a_variable_scope/var3:0
46+
print(sess.run(var3_reuse)) # [ 3.]

0 commit comments

Comments
 (0)