转载

http://blog.csdn.net/mylove0414/article/details/56969181

http://blog.csdn.net/mylove0414/article/details/55805974

感谢原博主Scorpio_Lu!!!

在进行学习的时候,发现由于Tensorflow版本问题或程序bug,导致无法运行,故在原博主的基础上做了调整,以下均是干货。

环境信息:

操作系统:Win7

Anaconda版本: 4.2.9

Tensorflow版本:1.1.0

数据集:dataset_1.csv 和 dataset_2.csv,我不会发CSDN附件,如有需要的同学,可留下自己的邮箱,我会定期发送。

一、一维数据预测(stock_predict_1.py):

#coding=utf-8

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn

f=open('dataset_1.csv') 
df=pd.read_csv(f)    
data=np.array(df['max'])
data=data[::-1]

#plt.figure()
#plt.plot(data)
#plt.show()
normalize_data=(data-np.mean(data))/np.std(data) 
normalize_data=normalize_data[:,np.newaxis]

time_step=20     
rnn_unit=10      
batch_size=60    
input_size=1     
output_size=1    
lr=0.0006        
train_x,train_y=[],[]  
for i in range(len(normalize_data)-time_step-1):
    x=normalize_data[i:i+time_step]
    y=normalize_data[i+1:i+time_step+1]
    train_x.append(x.tolist())
    train_y.append(y.tolist())

X=tf.placeholder(tf.float32, [None,time_step,input_size])   
Y=tf.placeholder(tf.float32, [None,time_step,output_size])

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

def lstm(batch):     
    w_in=weights['in']
    b_in=biases['in']
    input=tf.reshape(X,[-1,input_size]) 
    input_rnn=tf.matmul(input,w_in)+b_in
    input_rnn=tf.reshape(input_rnn,[-1,time_step,rnn_unit])  
    #cell=tf.nn.rnn_cell.BasicLSTMCell(rnn_unit)
    cell=rnn.BasicLSTMCell(rnn_unit, reuse=tf.get_variable_scope().reuse)
    init_state=cell.zero_state(batch,dtype=tf.float32)
    output_rnn,final_states=tf.nn.dynamic_rnn(cell, input_rnn,initial_state=init_state, dtype=tf.float32)
    output=tf.reshape(output_rnn,[-1,rnn_unit])
    w_out=weights['out']
    b_out=biases['out']
    pred=tf.matmul(output,w_out)+b_out
    return pred,final_states

def prediction():
    with tf.variable_scope("sec_lstm", reuse=True):
        pred,_=lstm(1)   
    saver=tf.train.Saver(tf.global_variables())
    with tf.Session() as sess:
        saver.restore(sess, 'model_save1\\modle.ckpt')
        #I run the code in windows 10,so use  'model_save1\\modle.ckpt'
        #if you run it in Linux,please use  'model_save1/modle.ckpt'
        prev_seq=train_x[-1]
        predict=[]
        for i in range(100):
            next_seq=sess.run(pred,feed_dict={X:[prev_seq]})
            predict.append(next_seq[-1])
            prev_seq=np.vstack((prev_seq[1:],next_seq[-1]))
       
        plt.figure()
        plt.plot(list(range(len(normalize_data))), normalize_data, color='b')
        plt.plot(list(range(len(normalize_data), len(normalize_data) + len(predict))), predict, color='r')
        plt.show()
       
       
prediction()

二、多维数据预测(stock_predict_2.py)

#coding=utf-8

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn

rnn_unit=10       #隐层数量
input_size=7
output_size=1
lr=0.0006         #学习率
#——————————————————导入数据——————————————————————
f=open('dataset_2.csv')
df=pd.read_csv(f)     #读入股票数据
data=df.iloc[:,2:10].values  #取第3-10列

#获取训练集
def get_train_data(batch_size=60,time_step=20,train_begin=0,train_end=5800):
    batch_index=[]
    data_train=data[train_begin:train_end]
    normalized_train_data=(data_train-np.mean(data_train,axis=0))/np.std(data_train,axis=0)  #标准化
    train_x,train_y=[],[]   #训练集
    for i in range(len(normalized_train_data)-time_step):
       if i % batch_size==0:
           batch_index.append(i)
       x=normalized_train_data[i:i+time_step,:7]
       y=normalized_train_data[i:i+time_step,7,np.newaxis]
       train_x.append(x.tolist())
       train_y.append(y.tolist())
    batch_index.append((len(normalized_train_data)-time_step))
    return batch_index,train_x,train_y

#获取测试集
def get_test_data(time_step=20,test_begin=5800):
    data_test=data[test_begin:]
    mean=np.mean(data_test,axis=0)
    std=np.std(data_test,axis=0)
    normalized_test_data=(data_test-mean)/std  #标准化
    size=(len(normalized_test_data)+time_step-1)//time_step  #有size个sample
    test_x,test_y=[],[]
    for i in range(size-1):
       x=normalized_test_data[i*time_step:(i+1)*time_step,:7]
       y=normalized_test_data[i*time_step:(i+1)*time_step,7]
       test_x.append(x.tolist())
       test_y.extend(y)
    test_x.append((normalized_test_data[(i+1)*time_step:,:7]).tolist())
    test_y.extend((normalized_test_data[(i+1)*time_step:,7]).tolist())
    return mean,std,test_x,test_y

#——————————————————定义神经网络变量——————————————————
#输入层、输出层权重、偏置

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

#——————————————————定义神经网络变量——————————————————
def lstm(X):
   
    batch_size=tf.shape(X)[0]
    time_step=tf.shape(X)[1]
    w_in=weights['in']
    b_in=biases['in']
    input=tf.reshape(X,[-1,input_size])  #需要将tensor转成2维进行计算,计算后的结果作为隐藏层的输入
    input_rnn=tf.matmul(input,w_in)+b_in
    input_rnn=tf.reshape(input_rnn,[-1,time_step,rnn_unit])  #将tensor转成3维,作为lstm cell的输入
    #cell=tf.nn.rnn_cell.BasicLSTMCell(rnn_unit)
    cell=rnn.BasicLSTMCell(rnn_unit, reuse=tf.get_variable_scope().reuse)
    init_state=cell.zero_state(batch_size,dtype=tf.float32)
    output_rnn,final_states=tf.nn.dynamic_rnn(cell, input_rnn,initial_state=init_state, dtype=tf.float32)
    output=tf.reshape(output_rnn,[-1,rnn_unit])
    w_out=weights['out']
    b_out=biases['out']
    pred=tf.matmul(output,w_out)+b_out
    return pred,final_states

#————————————————训练模型————————————————————

def train_lstm(batch_size=60,time_step=20,train_begin=2000,train_end=5800):
    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)
    with tf.variable_scope("sec_lstm"):
        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)

with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for i in range(2000):     #这个迭代次数,可以更改,越大预测效果会更好,但需要更长时间
            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("Number of iterations:",i," loss:",loss_)
        print("model_save: ",saver.save(sess,'model_save2\\modle.ckpt'))
        #我是在window下跑的,这个地址是存放模型的地方,模型参数文件名为modle.ckpt
        #在Linux下面用 'model_save2/modle.ckpt'
        print("The train has finished")
train_lstm()

#————————————————预测模型————————————————————
def prediction(time_step=20):
    X=tf.placeholder(tf.float32, shape=[None,time_step,input_size])
    mean,std,test_x,test_y=get_test_data(time_step)
    with tf.variable_scope("sec_lstm",reuse=True):
        pred,_=lstm(X)
    saver=tf.train.Saver(tf.global_variables())
    with tf.Session() as sess:
        #参数恢复
        module_file = tf.train.latest_checkpoint('model_save2')
        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)])  #偏差程度
        print("The accuracy of this predict:",acc)
        #以折线图表示结果
        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()

prediction()





缘分天空之我的机器学习--(二)Tensorflow实例:利用LSTM预测股票每日最高价相关推荐

  1. DL之LSTM:基于tensorflow框架利用LSTM算法对气温数据集训练并回归预测

    DL之LSTM:基于tensorflow框架利用LSTM算法对气温数据集训练并回归预测 目录 输出结果 核心代码 输出结果 数据集 tensorboard可视化 iter: 0 loss: 0.010 ...

  2. 缘分天空之我的机器学习--(一)环境搭建

    一.原文链接:http://www.cnblogs.com/nosqlcoco/p/6923861.html 更正部分用红色加粗字体标注. 什么是 Anaconda? Anaconda is the ...

  3. TensorFlow实战——使用LSTM预测彩票

    原创文章,转载请注明出处: http://blog.csdn.net/chengcheng1394/article/details/78756522 请安装TensorFlow1.0,Python3. ...

  4. python 二分类的实例_keras分类之二分类实例(Cat and dog)

    1. 数据准备 在文件夹下分别建立训练目录train,验证目录validation,测试目录test,每个目录下建立dogs和cats两个目录,在dogs和cats目录下分别放入拍摄的狗和猫的图片,图 ...

  5. 关于机器学习的十个实例

    转载自:http://www.open-open.com/news/view/50f54b 英文原文:Practical Machine Learning Problems 机器学习是什么? 机器学习 ...

  6. Python 机器学习简单实例:KNN预测鸢尾花分类

    读研太忙了才发现一年没更新,就以当初学习机器学习的一个简单例子作为一个新的开始吧.以下为正文. 一.安装sklearn库 执行以下命令安装, 注意:在此之前需要提前安装numpy.matplotlib ...

  7. 【机器学习入门】(8) 线性回归算法:正则化、岭回归、实例应用(房价预测)附python完整代码和数据集

    各位同学好,今天我和大家分享一下python机器学习中线性回归算法的实例应用,并介绍正则化.岭回归方法.在上一篇文章中我介绍了线性回归算法的原理及推导过程:[机器学习](7) 线性回归算法:原理.公式 ...

  8. 机器学习 二分类分类阈值_分类指标和阈值介绍

    机器学习 二分类分类阈值_分类指标和阈值介绍_weixin_26752765的博客-CSDN博客 机器学习 二分类分类阈值_分类指标和阈值介绍_weixin_26752765的博客-CSDN博客

  9. BizTalk学习笔记系列之二:实例说明如何使用BizTalk

    BizTalk学习笔记系列之二:实例说明如何使用BizTalk --.BizTalk学习笔记系列之二<?XML:NAMESPACE PREFIX = O /> Aaron.Gao,2006 ...

最新文章

  1. oracle体系结构和组件图示,Oracle 体系结构组件
  2. ]数据结构:单链表之判断两个链表是否相交及求交点(带环、不带环)
  3. 大道至简第三章。感受。
  4. 黑色全屏个人主页bootstrap4模板
  5. OMNeT++学习程序 4
  6. 支付宝将砸十亿支持中国女足发展:她们才是第一女子天团
  7. cmd mysql 报错_Mysql报错问题汇总
  8. 旅游推荐系统毕业设计总结(包含旅游信息爬取、算法应用和旅游推荐系统实现)
  9. 深度学习三巨头也成了大眼萌,这个一键转换动画电影形象的网站「太火」了...
  10. 二进制除法原理——两种简便方法
  11. EasyDarwin开源流媒体服务器Golang版本:拉转推功能之拉流实现方法
  12. 源自神话的写作要义之英雄
  13. 智能相机与工业相机_使用智能手机相机后如何移动到专用相机
  14. 数据结构与算法学习笔记(五)树
  15. 多巴胺所表达的prediction error信号
  16. Pytorch(GPU)配环境原理:cuda+cudnn+pytorch配环境的每一步到底干了些什么?
  17. 怎样搭建企业内部知识库
  18. 台式计算机反复启动,台式机总是一直重启怎么办
  19. 注册了个今日头条的头条号
  20. idea里把选中的变为大写或小写快捷键

热门文章

  1. 回忆向——诺宝RC机器人仿真
  2. 如何写优雅的代码(1)——灵活使用goto和__try:评论反馈
  3. 用户运营中,培养种子用户的三种模式
  4. HTML5视差教程:青蛙,蝴蝶,草丛,池塘
  5. codeigniter如何开启关闭调试模式?
  6. 上千个常用软件,你对国产操作系统UOS有何期望?
  7. 2019顺丰科技笔试
  8. 电脑开机后设置应用程序延时启动
  9. go测试之Convey+monkey+coverage组合
  10. 什么是捷径?踩在大佬的肩膀上就是捷径!