国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

這篇具有很好參考價(jià)值的文章主要介紹了時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

一、對(duì)時(shí)間序列的理解:

? ? ? ? 時(shí)間序列是按照一定時(shí)間間隔排列的數(shù)據(jù),時(shí)間間隔可以是任意時(shí)間單位,通過對(duì)時(shí)間序列的分析,我們可以探尋到其中的現(xiàn)象以及變化規(guī)律,并將這些信息用于預(yù)測。這就需要一系列的模型,用于將原始時(shí)間序列數(shù)據(jù)放進(jìn)模型中進(jìn)行訓(xùn)練,并用訓(xùn)練好的時(shí)間序列模型來預(yù)測未知的時(shí)間序列。

提供的數(shù)據(jù):

? ? ? ? “中國平安”2016-2018年股票數(shù)據(jù),背景為平安保險(xiǎn)集團(tuán)。數(shù)據(jù)預(yù)覽如下:

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

?通過預(yù)覽數(shù)據(jù),可知此次實(shí)驗(yàn)的數(shù)據(jù)屬性為date(日期)、open(開盤價(jià))、high(最高價(jià))、low(最低價(jià))、close(收盤價(jià))以及volume(成交量)

? ? ? ? 其中,我們要實(shí)現(xiàn)股票預(yù)測,需要著重對(duì)close(收盤價(jià))一列進(jìn)行探索性分析。

二、使用LSTM進(jìn)行時(shí)序預(yù)測

? ? ? ? 模型介紹:

? ? ? ? 包括遺忘門、輸入門、輸出門。LSTM將這些卡口作為去除或者增加細(xì)胞狀態(tài)的工具。門是一種讓信息選擇式通過的方法,他們包含一個(gè)sigmoid神經(jīng)網(wǎng)絡(luò)層和一個(gè)按位的乘法操作。

? ? ? ? 其中,每一個(gè)sigmoid會(huì)輸出0到1之間的數(shù)值,描述每個(gè)部分有多少量可以通過。0表示不允許任何量通過,1表示允許任意量通過。

? ? ? ? LSTM通過三個(gè)門,保護(hù)和控制細(xì)胞狀態(tài)。

建模思路(包括數(shù)據(jù)處理、模型分塊、建模、模型優(yōu)化、檢驗(yàn)等)

(1)數(shù)據(jù)處理:

? ? ? ? 導(dǎo)入數(shù)據(jù),提取數(shù)據(jù)集的date日期和close收盤價(jià)兩列,作為建模預(yù)測的對(duì)象。

? ? ? ? 模型分塊,設(shè)置測試集規(guī)模以及滑塊大小,現(xiàn)將數(shù)據(jù)歸一化處理,轉(zhuǎn)化為tensor可以識(shí)別的數(shù)據(jù),再將原數(shù)據(jù)設(shè)定為滑塊為1,每調(diào)用1批次的數(shù)據(jù),將其添加到列表,從而實(shí)現(xiàn)二維數(shù)據(jù)轉(zhuǎn)三維數(shù)據(jù),再切分訓(xùn)練集、測試集。

? ? ?建模步驟(依據(jù)上述思路進(jìn)行建模,詳細(xì)描述過程)

? ? ? ? 定義網(wǎng)絡(luò)層:LSTM層(神經(jīng)元個(gè)數(shù):16,激活函數(shù):relu)

? ? ? ? 全連接層(神經(jīng)元個(gè)數(shù):1,激活函數(shù):relu,正則化:l2范數(shù))

? ? ? ? 模型實(shí)例化并裝配網(wǎng)絡(luò)(優(yōu)化器:采用自適應(yīng)梯度優(yōu)化算法Adam,學(xué)習(xí)率設(shè)定為0.1,損失函數(shù)采用交叉熵函數(shù),評(píng)價(jià)指標(biāo)采用準(zhǔn)確率)

? ? ? ? 訓(xùn)練模型,設(shè)定訓(xùn)練批次為50,每批次樣本量為100.

#使用LSTM進(jìn)行預(yù)測
import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
from tensorflow.keras.layers import Input,Dropout,Dense,LSTM
from tensorflow.keras.models import Model
from tensorflow.keras import regularizers
import tensorflow.keras as keras
np.random.seed(100)
# 選取隨機(jī)種子個(gè)數(shù)100個(gè)

????????

# 設(shè)置神經(jīng)網(wǎng)絡(luò)參數(shù)
# 提取收盤價(jià)
y=stock['close']
print(y)
# 數(shù)據(jù)預(yù)處理
test_ratio=0.4
windows=1
# 設(shè)置滑塊大小
# 定義測試集規(guī)模
# # 通過比例切分
# 測試集大小
from sklearn.preprocessing import MinMaxScaler
data_lsvm=y.values

scaler=MinMaxScaler(feature_range=(0, 1))
data_lsvm=scaler.fit_transform(data_lsvm.reshape(-1,1))



print(data_lsvm)


cut=round(test_ratio* data_lsvm.shape[0])
print(data_lsvm.shape[0])
print('切分:',cut)
train,test=data_lsvm[:data_lsvm.shape[0]-cut,:],data_lsvm[data_lsvm.shape[0]-cut:,:]
amount_of_features=data_lsvm.shape[1]
lstm_input=[]
data_temp=data_lsvm
for i in range(len(data_temp)-windows):

    lstm_input.append(data_lsvm[i:i+windows,:])
lstm_input=np.array(lstm_input)
lstm_output=y[:-windows]

lstm_output=np.array(lstm_output)
x_train,y_train,x_test,y_test=lstm_input[:data_lsvm.shape[0]-cut,:],lstm_output[:data_lsvm.shape[0]-cut],lstm_input[data_lsvm.shape[0]-cut:,:],lstm_output[data_lsvm.shape[0]-cut:]
print(x_train.shape,y_train.shape,x_test.shape,y_test.shape)
x_train
mn_units=16
dropout=0.01
# # 定義網(wǎng)絡(luò)全連接層
#
def lstm_model():
    inputs=Input(shape=(windows,amount_of_features))

    # lstm層
    rnn = LSTM(units=mn_units, activation='relu',return_sequences=False)(inputs)
    dense=Dropout(dropout)(rnn)
#     dense1=Dense(16,activation='sigmoid',kernel_regularizer=regularizers.l2(0.1))(dense)
#     dense2=Dense(8,activation='relu',kernel_regularizer=regularizers.l2(0.1))(dense)
    outputs=Dense(1,activation='relu',kernel_regularizer=regularizers.l2(0.5))(dense)
    model=Model(inputs=inputs,outputs=outputs)

    model.compile(optimizer=keras.optimizers.Adam(0.1),loss=tf.losses.BinaryCrossentropy(),metrics=['accuracy'])

    model.summary()
    return model
#
batch_size=100
#
epoch=50
# 訓(xùn)練網(wǎng)絡(luò)
mymodel=lstm_model()
history = mymodel.fit(x_train,y_train,batch_size=batch_size,epochs=epoch)
y_train_predict=mymodel.predict(x_test)

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

fig= plt.figure(figsize=(8, 5))
plt.plot(history.history['loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.show()

(3)預(yù)測結(jié)果(數(shù)據(jù)、擬合圖等)

評(píng)估結(jié)果:

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

隨著訓(xùn)練次數(shù)增多,loss值逐漸減小。

將預(yù)測后的數(shù)據(jù)進(jìn)行評(píng)估,并將預(yù)測結(jié)果反歸一化,如圖:

# print(mymodel.metrics_names)
loss,acc=mymodel.evaluate(x_test,y_test)
print('評(píng)估結(jié)果',loss,acc)

y_train_predict=mymodel.predict(x_train)#預(yù)測結(jié)果
y_test_predict=mymodel.predict(x_test)#預(yù)測結(jié)果
print('預(yù)測結(jié)果',y_train_predict,y_test_predict)
print(y_test_predict.shape)

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

#反歸一化


trainPredict=scaler.inverse_transform(y_train_predict)
testPredict = scaler.inverse_transform(y_test_predict)
data_lsvmx=scaler.inverse_transform(data_lsvm)
# y_test = scaler.inverse_transform(y_test)
print(len(trainPredict),len(testPredict))
data_lsvmx

?反歸一化后的結(jié)果:

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

# 預(yù)測結(jié)果

testPredict=pd.DataFrame(testPredict)
close_new=testPredict
close_new.columns=['new_close']
stock_new=stock.iloc[:-windows,:]

# 訓(xùn)練集預(yù)測結(jié)果
trainPredict=pd.DataFrame(trainPredict)
train_date=stock_new[:data_lsvm.shape[0]-cut].loc[:,['date']]
new_date_train=train_date.reset_index()

new_date_train=new_date_train.drop('index',axis=1)
print(new_date_train)
new_date=stock_new[data_lsvm.shape[0]-cut:].loc[:,['date']]
new_date=new_date.reset_index()
new_date=new_date.drop('index',axis=1)
# date=pd.concat([new_date_train,new_date],axis=0)
new_predict=pd.concat([new_date,close_new],axis=1)

新的預(yù)測結(jié)果:

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

?作圖:

# 構(gòu)建通過訓(xùn)練集進(jìn)行預(yù)測的圖表數(shù)據(jù)
predict_train_plot = np.empty_like(data_lsvm)
predict_train_plot[:, :] = np.nan
predict_train_plot[:data_lsvm.shape[0]-cut, :] = trainPredict
# 構(gòu)建通過測試集進(jìn)行預(yù)測的圖表數(shù)據(jù)
predict_test_plot = np.empty_like(data_lsvm)
predict_test_plot[:, :] = np.nan
predict_test_plot[data_lsvmx.shape[0]-cut+1:, :] = testPredict

# 原數(shù)據(jù)
data_plot = np.empty_like(data_lsvmx)
data_plot[:, :] = np.nan
data_plot[:, :] = data_lsvmx

# # 構(gòu)建通過原數(shù)據(jù)進(jìn)行擬合的圖表數(shù)據(jù)
date=stock.loc[:,['date']]
type(date["date"])

最后繪制預(yù)測圖:

fig2 = plt.figure(figsize=(10, 5))
dataset = scaler.inverse_transform(data_lsvm)
plt.plot(date["date"],predict_train_plot, color='green')
plt.plot(date["date"],predict_test_plot, color='red')
plt.plot(date["date"],data_plot, color='blue')
plt.xticks(range(0,730,80))
plt.show()

時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例

?????????通過構(gòu)建訓(xùn)練集進(jìn)行預(yù)測的圖表數(shù)據(jù)和通過測試集進(jìn)行預(yù)測的圖表數(shù)據(jù),以及原數(shù)據(jù)的圖表數(shù)據(jù)。

? ? ? ? 由圖可知,該模型預(yù)測的價(jià)格走勢和原數(shù)據(jù)走勢大體吻合。文章來源地址http://www.zghlxwxcb.cn/news/detail-468972.html

到了這里,關(guān)于時(shí)間序列預(yù)測股票數(shù)據(jù)—以LSTM模型為例的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包