1. 程式人生 > >Tensorflow例項:利用LSTM預測股票每日最高價(二)

Tensorflow例項:利用LSTM預測股票每日最高價(二)

根據股票歷史資料中的最低價、最高價、開盤價、收盤價、交易量、交易額、跌漲幅等因素,對下一日股票最高價進行預測。

實驗用到的資料長這個樣子:
這裡寫圖片描述

label是標籤y,也就是下一日的最高價。列C——I為輸入特徵。
本例項用前5800個數據做訓練資料。

匯入包及宣告常量

import pandas as pd
import numpy as np
import tensorflow as tf

#定義常量
rnn_unit=10       #hidden layer units
input_size=7      
output_size=1
lr=0.0006         #學習率

匯入資料

f=open('dataset.csv') 
df=pd.read_csv(f)     #讀入股票資料
data=df.iloc[:,2:10].values   #取第3-10列

生成訓練集、測試集

考慮到真實的訓練環境,這裡把每批次訓練樣本數(batch_size)、時間步(time_step)、訓練集的數量(train_begin,train_end)設定為引數,使得訓練更加機動。

#——————————獲取訓練集——————————
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=[],[] #訓練集x和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

構建神經網路

#——————————————————定義神經網路變數——————————————————
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)
    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_rnn是記錄lstm每個輸出節點的結果,final_states是最後一個cell的結果
    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=80,time_step=15,train_begin=0,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)
    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)
        #重複訓練2000次
        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(i,loss_)
            if i % 200==0:
                print("儲存模型:",saver.save(sess,'stock2.model',global_step=i))

嗯,這裡說明一下,這裡的引數是基於已有模型恢復的引數,意思就是說之前訓練過模型,儲存過神經網路的引數,現在再取出來作為初始化引數接著訓練。如果是第一次訓練,就用sess.run(tf.global_variables_initializer()),也就不要用到 module_file = tf.train.latest_checkpoint() 和saver.store(sess, module_file)了。

測試

#————————————————預測模型————————————————————
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)
    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)]) #acc為測試集偏差

最後的結果畫出來是這個樣子:

這裡寫圖片描述
紅色折線是真實值,藍色折線是預測值

偏差大概在1.36%

程式碼和資料上傳到了github上,想要的戳全部程式碼

注!:如要轉載,請經過本人允許並註明出處!

相關推薦

Tensorflow例項利用LSTM預測股票每日最高價

根據股票歷史資料中的最低價、最高價、開盤價、收盤價、交易量、交易額、跌漲幅等因素,對下一日股票最高價進行預測。 實驗用到的資料長這個樣子: label是標籤y,也就是下一日的最高價。列C——I為輸入特徵。 本例項用前5800個數據做訓練資料。

Tensorflow例項利用LSTM預測股票每日最高價

這一部分主要涉及迴圈神經網路的理論,講的可能會比較簡略。 什麼是RNN RNN全稱迴圈神經網路(Recurrent Neural Networks),是用來處理序列資料的。在傳統的神經網路模型中,從輸入層到隱含層再到輸出層,層與層之間是全連線的,每層之間

實測 《Tensorflow實例利用LSTM預測股票每日最高價》的結果

直接 batch Language name 開盤 num 完全 tor 運行 近期股市行情牛轉熊,大盤一直下探!由3200跌到了2700,想必很多人被深套了。這時想起人工智能能否預測股市趨勢?RNN能否起作用?   這時便從網上找下教程,發現網上有個例子,

人工智慧深度學習-Tensorflow例項利用LSTM預測股票每日最高價

LSTM全稱長短期記憶人工神經網路(Long-Short Term Memory),是對RNN的變種。舉個例子,假設我們試著去預測“I grew up in France… 中間隔了好多好多字……I speak fluent __”下劃線的詞。我們拍腦瓜子想這個詞應該是French。對於迴圈神經網路

利用LSTM預測股票最高價

import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf f=open('G:\\Kaggle\\RNN\\LSTM\\

Python時間序列LSTM預測系列學習筆記2-單變數

本文是對: https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/ https://blog.csdn.net/iyangdi/article/deta

Python時間序列LSTM預測系列學習筆記1-單變數

本文是對: https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/ https://blog.csdn.net/iyangdi/article/deta

Python時間序列LSTM預測系列學習筆記11-多步預測

本文是對: https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ https://blog.csdn.net/iyangdi/

Python時間序列LSTM預測系列學習筆記10-多步預測

本文是對: https://machinelearningmastery.com/multi-step-time-series-forecasting-long-short-term-memory-networks-python/ https://blog.csdn.net/iyangdi/

Python時間序列LSTM預測系列學習筆記9-多變數

本文是對: https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/ https://blog.csdn.net/iyangdi/article/details/77881755

Python時間序列LSTM預測系列學習筆記8-多變數

本文是對: https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/ https://blog.csdn.net/iyangdi/article/details/77879232

Python時間序列LSTM預測系列學習筆記7-多變數

本文是對: https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/ https://blog.csdn.net/iyangdi/article/details/77877410

Python時間序列LSTM預測系列學習筆記6-單變數

本文是對: https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/ https://blog.csdn.net/iyangdi/article/deta

Python時間序列LSTM預測系列學習筆記5-單變數

本文是對: https://machinelearningmastery.com/time-series-forecasting-long-short-term-memory-network-python/ https://blog.csdn.net/iyangdi/article/deta

從rnn到lstm,再到seq2seq

app 感受 ima bsp expand images cat https github 從圖上可以看出來,decode的過程其實都是從encode的最後一個隱層開始的,如果encode輸入過長的話,會丟失很多信息,所以設計了attation機制。 attati

生物特征識別小面積指紋識別算法

dpi 如果 mage 卷積 噪聲 狀態 AMM 計算 log 算法(一)已經介紹了一種小面積指紋識別算法可選的方案,是一種經典的方案,對於面積足夠大且level2特征高於最小限制時,為一種低內存占用,快速的實現方法。但在某些應用場中中(比如終端中,要求占用面積較小,且面

Python基礎班每日整理

每日 設置 語法 基礎 大件 例如 計算 str 功能 02_Python基礎_day02 Python中註釋的作用?單行和多行註釋在程序中對某些代碼進行標註說明,增強程序的可讀性。單行註釋:以#號開頭,再加一個空格,後面跟上註釋內容TODO註釋:# TODO 註釋內容

【python】爬蟲篇python對於html頁面的解析

我,菜雞,有什麼錯誤,還望大家批評指出!! 前言: 根據自己寫的上一篇文章,我繼續更第二部分的內容,詳情請點選如下連結 【python】爬蟲篇:python連線postgresql(一):https://blog.csdn.net/lsr40/article/details/833118

Python小程式——利用wordcloud庫生成詞雲

wordcloud庫利用wordcloud物件生成詞雲,其中可以配置很多屬性,讓你的詞雲更加個性化。 w_cloud = wordcloud.WordCloud( font_path=font, background_color=None, mode="RGBA", # 背

利用nodejs實現商品管理系統

下面實現商品管理系統 第一步:對應的ejs與資料交換的編寫格式。 商品列表介面product.ejs <% for(var i=0;i<list.length;i++){%> <tr>