LSTM预测cosX

根据sin(X)的图像,预测cos(X)。
有些地方看懂,记录一下,原地址https://github.com/MorvanZhou/Tensorflow-Tutorial/tree/master/tutorial-contents

import tensorflow.compat.v1 as tf
import tensorflow as tf2
tf.disable_v2_behavior()
import numpy as np
import matplotlib.pyplot as plt# Hyper Parameters
#这里batch_size=1
TIME_STEP = 10       # rnn time step
INPUT_SIZE = 1      # rnn input size
CELL_SIZE = 32      # rnn cell size
LR = 0.02           # learning rate# show data
# steps = np.linspace(0, np.pi*2, 100, dtype=np.float32)
# x_np = np.sin(steps)
# y_np = np.cos(steps)
# plt.plot(steps, y_np, 'r-', label='target (cos)')
# plt.plot(steps, x_np, 'b-', label='input (sin)')
# plt.legend(loc='best')
# plt.show()# tensorflow placeholders
tf_x = tf.placeholder(tf.float32, [None, TIME_STEP, INPUT_SIZE])
tf_y = tf.placeholder(tf.float32, [None, TIME_STEP, INPUT_SIZE])
tf_bsize = tf.placeholder(tf2.int32,[])# RNN
#num_units:int类型,LSTM单元中的神经元数量,即输出神经元数量
rnn_cell = tf.nn.rnn_cell.LSTMCell(num_units=CELL_SIZE)
init_s = rnn_cell.zero_state(batch_size=tf_bsize, dtype=tf.float32)    # very first hidden state
outputs, final_s = tf.nn.dynamic_rnn(rnn_cell,                   # cell you have chosentf_x,                       # inputinitial_state=init_s,       # the initial hidden statetime_major=False,           # False: (batch, time step, input); True: (time step, batch, input)
)# reshape 3D output to 2D for fully connected layer
outs2D = tf.reshape(outputs, [-1, CELL_SIZE])
net_outs2D = tf.layers.dense(outs2D, INPUT_SIZE)# reshape back to 3D
outs = tf.reshape(net_outs2D, [-1, TIME_STEP, INPUT_SIZE])# compute cost
#mean_squared_error:均方误差,数组对应位置做减法,平方和求均值
loss = tf.losses.mean_squared_error(labels=tf_y, predictions=outs)
train_op = tf.train.AdamOptimizer(LR).minimize(loss)sess = tf.Session()
sess.run(tf.global_variables_initializer())     # initialize var in graphplt.figure(1, figsize=(12, 5))
plt.ion()       # continuously plotfor step in range(60):start, end = step * np.pi, (step+1)*np.pi   # time range# use sin predicts cos# steps = np.linspace(start, end, TIME_STEP)steps = np.linspace(start, end, TIME_STEP)# shape (batch, time_step, input_size)x = np.sin(steps)[np.newaxis, :, np.newaxis]y = np.cos(steps)[np.newaxis, :, np.newaxis]# first state, no any hidden stateif 'final_s_' not in globals():feed_dict = {tf_x: x, tf_y: y,tf_bsize:1}# has hidden state, so pass it to rnnelse:feed_dict = {tf_x: x, tf_y: y, init_s: final_s_,tf_bsize:1}_, pred_, final_s_ = sess.run([train_op, outs, final_s], feed_dict)     # train# plottingplt.plot(steps, y.flatten(), 'r')plt.plot(steps, pred_.flatten(), 'b--')plt.ylim((-1.2, 1.2))plt.draw()plt.pause(0.05)plt.ioff()
plt.show()


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部