您的位置:首页 > 其它

tensorflow1.1/RNN预测

2017-07-29 19:06 381 查看

环境:tensorflow1.1,python3,matplotlib2.02

#coding:utf-8
from tensorflow.contrib import rnn
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pickle
import matplotlib.pyplot as plt

#加载数据
with open('price.pickle','rb') as f:
(train_data,train_labels,pred_value,pred) = pickle.load(f)

train_data = np.array(train_data).astype(np.float32)
train_labels = np.array(train_labels).astype(np.float32)
pred_value = np.array(pred_value).astype(np.float32)

time_step = 1
input_size = 1
n_hidden_units = 128
batch_size = 100
learning_rate = 0.001

xs = tf.placeholder(tf.float32,[None,time_step,input_size])
#输出和xs形状相同
ys = tf.placeholder(tf.float32,[None,time_step,input_size])

#定义weights和biases
weights = {
'in':tf.Variable(tf.random_normal([input_size,n_hidden_units])),
'out':tf.Variable(tf.random_normal([n_hidden_units,input_size]))
}

biases = {
'in':tf.Variable(tf.constant(0.1,shape=[n_hidden_units])),
'out':tf.Variable(tf.constant(0.1,shape=[input_size]))
}

#RNN输出二维数据,输入二维数据
def RNN(x,weights,biases):
#输入(batch_size,time_step,inpyt_size)----->rnn输入形状(batch_size,input_size)
x = tf.unstack(x,time_step,1)
lstm_cell = rnn.BasicLSTMCell(n_hidden_units,forget_bias=1.0)
#返回outputs,主线state,分线state
outputs,states = rnn.static_rnn(lstm_cell,x,dtype=tf.float32)
return tf.matmul(outputs[-1],weights['out'])+biases['out']

output = RNN(xs,weights,biases)
#将数据转为三维
output_reshape = tf.reshape(output,[-1,time_step,input_size])
#output_reshape = output.reshape(-1,time_step,input_size)
cost = tf.losses.mean_squared_error(labels=ys,predictions=output_reshape)
train = tf.train.AdamOptimizer(learning_rate).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
k_step = []
for step in range(10):
k = 0
while k < int(train_data.shape[0]/100):
batch_x = train_data[k*100:(k+1)*100]
batch_y = train_data[k*100:(k+1)*100]
batch_x = batch_x.reshape(int(batch_size/time_step),time_step,input_size)
batch_y = batch_y.reshape(int(batch_size/time_step),time_step,input_size)
k = k+1
_,c = sess.run([train,cost],feed_dict={xs:batch_x,ys:batch_y})
c = c*100000000
print('cost:',c,'step:',step)
k_step.append(int(step))
predict = sess.run(output,feed_dict={xs:pred_value.reshape(10,time_step,input_size)})
#print('prediction value is',pred)
plt.plot(k_step,predict)
plt.title('2017 price prediction:')
plt.xticks([0,2,4,6,8],[pred[0],pred[2],pred[4],pred[6],pred[8]],rotation=12)
plt.grid(True)
plt.show()


结果:

数据集:链接:http://pan.baidu.com/s/1jHNPJJC 密码:gbyu



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tensorflow rnn 预测