今日完成LSTM模型的搭建和运行,其中的数据来源是tushare,具体见上一条:LSTM模型的期货预测day1_weixin_45607030的博客-CSDN博客_lstm预测期货
在这个模型中使用了7个特征值进行训练,预测下一日收盘价
部分数据:
代码部分分为两部分:模型的训练和预测
训练模型部分代码:
def train_lstm(batch_size=5,time_step=2,train_begin=0,train_end=150):
X=tf.placeholder(tf.float32, shape=[None,time_step,input_size])
Y=tf.placeholder(tf.float32, shape=[None,time_step,output_size])
batch_index,train_x,train_y=get_train_data(batch_size,time_step,train_begin,train_end)
pred,_=lstm(X)
#损失函数
loss=tf.reduce_mean(tf.square(tf.reshape(pred,[-1])-tf.reshape(Y, [-1])))
train_op=tf.train.AdamOptimizer(lr).minimize(loss)
saver=tf.train.Saver(tf.global_variables(),max_to_keep=15)
module_file = tf.train.latest_checkpoint('./')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
#saver.restore(sess, module_file)
#重复训练10000次
for i in range(150):
for step in range(len(batch_index)-1):
_,loss_=sess.run([train_op,loss],feed_dict={X:train_x[batch_index[step]:batch_index[step+1]],Y:train_y[batch_index[step]:batch_index[step+1]]})
print(i,loss_)
if i % 15==0:
print("保存模型:",saver.save(sess,'future.model',global_step=i))
预测部分代码:
def prediction(time_step=2):
X=tf.placeholder(tf.float32, shape=[None,time_step,input_size])
#Y=tf.placeholder(tf.float32, shape=[None,time_step,output_size])
mean,std,test_x,test_y=get_test_data(time_step)
pred,_=lstm(X)
saver=tf.train.Saver(tf.global_variables())
with tf.Session() as sess:
#参数恢复
module_file = tf.train.latest_checkpoint('./')
saver.restore(sess, module_file)
test_predict=[]
for step in range(len(test_x)-1):
prob=sess.run(pred,feed_dict={X:[test_x[step]]})
predict=prob.reshape((-1))
test_predict.extend(predict)
test_y=np.array(test_y)*std[7]+mean[7]
test_predict=np.array(test_predict)*std[7]+mean[7]
acc=np.average(np.abs(test_predict-test_y[:len(test_predict)])/test_y[:len(test_predict)]) #偏差
#以折线图表示结果
plt.figure()
plt.plot(list(range(len(test_predict))), test_predict, color='b')
plt.plot(list(range(len(test_y))), test_y, color='r')
plt.show()
print(acc)
结果:
总结:
1.训练所用的数据量不足,应该尽可能再多点样本
2.多层LSTM可能预测效果还有所增加,目前预测偏差约为3.6%,但作为期货的预测,存在杠杆,因此还需降低loss