2
3
4
5
6
7
8
9
t_min, t_max = 0, 30
resolution = 0.1
def time_series(t):
return t * np.sin(t) / 3 + 2 * np.sin(t*5)
def next_batch(batch_size, n_steps):
t0 = np.random.rand(batch_size, 1) * (t_max - t_min - n_steps * resolution)
Ts = t0 + np.arange(0., n_steps + 1) * resolution
ys = time_series(Ts)
return ys[:, :-1].reshape(-1, n_steps, 1), ys[:, 1:].reshape(-1, n_steps, 1)
t = np.linspace(t_min, t_max, int((t_max - t_min) / resolution))
n_steps = 20
t_instance = np.linspace(12.2, 12.2 + resolution * (n_steps + 1), n_steps + 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
n_steps = 20
n_inputs =1
n_neurons = 100
X = tf.placeholder(tf.float32, [None, n_steps, n_inputs],name='X')
y = tf.placeholder(tf.float32, [None, n_steps, n_outputs],name='y')
cell = tf.contrib.rnn.BasicRNNCell(num_units=n_neurons, activation=tf.nn.relu )
rnn_outputs, states = tf.nn.dynamic_rnn(cell=cell, inputs=X, dtype=tf.float32)
n_outputs = 1
learning_rate = 0.001
stacked_rnn_outputs = tf.reshape(tensor=rnn_outputs, shape=[-1, n_neurons])
stacked_outputs = tf.layers.dense(inputs=stacked_rnn_outputs, units=n_outputs)
outputs = tf.reshape(tensor=stacked_outputs, shape=[-1, n_steps, n_outputs],name='outputs')
loss = tf.reduce_mean(tf.square(outputs - y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
training_op = optimizer.minimize(loss)
init = tf.global_variables_initializer()
saver = tf.train.Saver()
n_iterations = 1500
batch_size = 50
with tf.Session() as sess:
init.run()
for iteration in range(n_iterations):
X_batch, y_batch = next_batch(batch_size, n_steps)
sess.run(training_op, feed_dict={X:X_batch, y:y_batch})
if iteration %100 ==0:
mse = loss.eval(feed_dict={X:X_batch, y:y_batch})
print(iteration, "\tMSE:", mse)
X_new = time_series(np.array(t_instance[:-1].reshape(-1, n_steps, n_inputs)))
y_pred = sess.run(outputs, feed_dict={X: X_new})
saver.save(sess, "./my_time_series_model")
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
2.载入模型并用于预测
import tensorflow as tf
import numpy as np
1
2
def reset_graph(seed=42):
tf.reset_default_graph()
tf.set_random_seed(seed)
np.random.seed(seed)
reset_graph()
1
2
3
4
5
1.载入图结构和参数
sess = tf.Session()
saver = tf.train.import_meta_graph('./my_time_series_model.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
1
2
3
4
INFO:tensorflow:Restoring parameters from ./my_time_series_model
1
2.获取图
graph = tf.get_default_graph()
1
3.获取tensor
X = graph.get_tensor_by_name('X:0')
y = graph.get_tensor_by_name("y:0")
outputs = graph.get_tensor_by_name("outputs:0")
1
2
3
4.新的input准备
X_new = time_series(np.array(t_instance[:-1].reshape(-1, 20, 1)))
1
y.shape
1
TensorShape([Dimension(None), Dimension(20), Dimension(1)])
1
5.应用与预测
y_pred = sess.run(outputs, feed_dict={X: X_new})
1
print(y_pred)
1
[[[-3.44828582]
[-2.48405623]
[-1.13649726]
[ 0.71962416]
[ 2.01745081]
[ 3.13937259]
[ 3.54828739]
[ 3.36234236]
[ 2.77184248]
[ 2.10781217]
[ 1.64527285]
[ 1.5579648 ]
[ 1.87219918]
[ 2.7233479 ]
[ 3.85228252]
[ 5.06193066]
[ 6.07513857]
[ 6.63054752]
[ 6.59069633]
[ 5.9993453 ]]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
plt.title("Testing the model", fontsize=14)
plt.plot(t_instance[:-1], time_series(t_instance[:-1]), "bo", markersize=10, label="instance")
plt.plot(t_instance[1:], time_series(t_instance[1:]), "w*", markersize=10, label="target")
plt.plot(t_instance[1:], y_pred[0,:,0], "r.", markersize=10, label="prediction")
plt.legend(loc="upper left")
plt.xlabel("Time")
# save_fig("time_series_pred_plot")
plt.show()
1
2
3
4
5
6
7
8
9
n_steps=20
sequence1 = [0.]*20
for iteration in range(len(t) - n_steps):
X_batch = np.array(sequence1[-n_steps:]).reshape(1, 20, 1)
y_red = sess.run(outputs, feed_dict={X:X_batch})
sequence1.append(y_pred[0,-1,0])
sequence2 = [time_series(i*resolution+t_min+(t_max-t_min/3)) for i in range(20)]
for iteration in range(len(t) - n_steps):
X_batch = np.array(sequence2[-n_steps:]).reshape(1, n_steps, 1)
y_pred = sess.run(outputs, feed_dict={X:X_batch})
sequence2.append(y_pred[0,-1,0])
---------------------
作者:Jack_kun
来源:CSDN
原文:https://blog.csdn.net/Jack_kun/article/details/85006564
版权声明:本文为博主原创文章,转载请附上博文链接!