作者:Siddharth M翻译:王可汗校对:欧阳锦 本文约1300字,建议阅读6分钟本文教你如何利用LSTM网络预测股价走势,并对开盘和收盘价进行可视化。
长短时记忆(LSTM)是一种能增加递归神经网络(RNN)记忆的模型。递归神经网络保留短期记忆,因为它们允许在当前神经网络中更早地确定信息。对于即时任务,RNN使用早期的数据,但我们可能没有利用神经元所有的早期信息。在RNN中,LSTM得到了广泛的应用。视频、自然语言处理、地理空间和时间序列等多个应用领域中,都证实了LSTM的有效性。
RNN的一个主要问题是梯度消失问题,它是由于在RNN块中重复使用相同的参数而产生的。我们必须在每个时间步中尝试使用不同的参数来克服这个问题。
我们努力在这样的情况下找到平衡。 在生成变长序列的同时,我们在每一步引入新的参数,同时保持可学习参数的总数量不变。我们引入了基于门控机制的RNN单元,如LSTM和GRU。
门控单元保存内部变量,即利用其中的门。每个时间步的每个门的值取决于该时间步的信息,包括早期状态。然后,门的值乘以不同的权重变量来影响它们。时间序列数据是在一段时间内收集的一系列数据值,允许我们跟踪一段时间内的差异。时间序列数据可以以毫秒、天和年为单位跟踪进程。
早期,我们把时间序列数据视为静态的;每天气温下的高点和低点,股市的开盘价和收盘价。现在我们将进入编码部分。我们将在股票数据集上实现LSTM。
https://github.com/PacktPublishing/Learning-Pandas-Second-Edition/blob/master/data/goog.csv
读取数据:
gstock_data = pd.read_csv('data.csv')
gstock_data .head()
该数据集包含14列与时间序列(如日期)和不同的变量(如close、high、low和volume)相关。我们将使用开盘价和收盘价来用LSTM进行时间序列预测。
gstock_data = gstock_data [['date','open','close']]
gstock_data ['date'] = pd.<a onclick="parent.postMessage({'referent':'.pandas.to_datetime'}, '*')">to_datetime(gstock_data ['date'].apply(lambda x: x.split()[0]))
gstock_data .set_index('date',drop=True,inplace=True)
gstock_data .head()
我们在这里进行了一些特征提取。我们从整个日期变量中单独取日期。现在,我们可以使用matplotlib来可视化可用数据,并查看数据中的价格值是如何显示的。如下所示的价格-日期图中绿色表示开盘价,红色表示收盘价。
fg,ax=plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.subplots'}, '*')">subplots(1,2,figsize=(20,7))
ax[0].plot(gstock_data ['open'],label='Open',color='green')
ax[0].set_xlabel('Date',size=15)
ax[0].set_ylabel('Price',size=15)
ax[0].legend()
ax[1].plot(gstock_data ['close'],label='Close',color='red')
ax[1].set_xlabel('Date',size=15)
ax[1].set_ylabel('Price',size=15)
ax[1].legend()
fg.show()
我们必须在使用LSTM应用在股票价格之前对这些数据进行预处理。在fit_transform函数的帮助下转换数据中的值。Min-max scaler用于缩放数据,以便我们可以对所有的价格值归一化 然后,我们使用80%的数据进行训练,其余20%用于测试,并将它们分配到单独的变量中。
from sklearn.preprocessing import MinMaxScaler
Ms = MinMaxScaler()
gstock_data [gstock_data .columns] = Ms.fit_transform(gstock_data )
training_size = round(len(gstock_data ) * 0.80)
train_data = gstock_data [:training_size]
test_data = gstock_data [training_size:]
创建一个函数,以便我们可以创建用于训练和测试的序列。
def create_sequence(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..dataset'}, '*')">dataset):
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..sequences'}, '*')">sequences = []
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..labels'}, '*')">labels = []
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..start_idx'}, '*')">start_idx = 0
for <a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..stop_idx'}, '*')">stop_idx in range(50,len(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..dataset'}, '*')">dataset)):
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..sequences'}, '*')">sequences.append(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..dataset'}, '*')">dataset.iloc[<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..start_idx'}, '*')">start_idx:<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..stop_idx'}, '*')">stop_idx])
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..labels'}, '*')">labels.append(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..dataset'}, '*')">dataset.iloc[<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..stop_idx'}, '*')">stop_idx])
<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..start_idx'}, '*')">start_idx += 1
return (np.<a onclick="parent.postMessage({'referent':'.numpy.array'}, '*')">array(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..sequences'}, '*')">sequences),np.<a onclick="parent.postMessage({'referent':'.numpy.array'}, '*')">array(<a onclick="parent.postMessage({'referent':'.kaggle.usercode.22406117.81090952.create_sequence..labels'}, '*')">labels))
train_seq, train_label = create_sequence(train_data)
test_seq, test_label = create_sequence(test_data)
在下一步中,我们创建LSTM模型。在本文中,我们将使用从Keras导入的Sequential模型,并导入所需的库。
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM, Bidirectional
我们在模型中使用了两个LSTM层,并在层与层之间使用dropout以实现正则化。在LSTM参数中分配的单元数是50个。Dropout为10%。损失函数是均方误差并使用Adam优化器优化问题的损失函数。平均绝对误差是我们在LSTM网络中使用的评估度量,因为它与时间序列数据相关。
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape = (train_seq.shape[1], train_seq.shape[2])))
model.add(Dropout(0.1))
model.add(LSTM(units=50))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_absolute_error'])
model.summary()
model.fit(train_seq, train_label, epochs=80,validation_data=(test_seq, test_label), verbose=1)
test_predicted = model.predict(test_seq)
test_inverse_predicted = MMS.inverse_transform(test_predicted)
将数据与我们的模型拟合后,我们用它进行预测。 我们必须用逆变换使得变换后的函数返回原值。现在我们可以使用这些数据来可视化预测 。
# Merging actual and predicted data for better visualization
gs_slic_data = pd.concat([gstock_data .iloc[-202:].copy(),pd.DataFrame(test_inverse_predicted,columns=['open_predicted','close_predicted'],index=gstock_data .iloc[-202:].index)], axis=1)
gs_slic_data[['open','close']] = MMS.inverse_transform(gs_slic_data[['open','close']])
gs_slic_data.head()
gs_slic_data[['open','open_predicted']].plot(figsize=(10,6))
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.xticks'}, '*')">xticks(rotation=45)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.xlabel'}, '*')">xlabel('Date',size=15)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.ylabel'}, '*')">ylabel('Stock Price',size=15)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.title'}, '*')">title('Actual vs Predicted for open price',size=15)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.show'}, '*')">show()
gs_slic_data[['close','close_predicted']].plot(figsize=(10,6))
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.xticks'}, '*')">xticks(rotation=45)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.xlabel'}, '*')">xlabel('Date',size=15)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.ylabel'}, '*')">ylabel('Stock Price',size=15)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.title'}, '*')">title('Actual vs Predicted for close price',size=15)
plt.<a onclick="parent.postMessage({'referent':'.matplotlib.pyplot.show'}, '*')">show()
在本文中,我们利用LSTM研究了股票价格并将开盘和收盘价可视化。
参考:
https://the-learning-machine.com/article/dl/long-short-term-memory
https://www.kaggle.com/amarsharma768/stock-price-prediction-using-lstm/notebook
原文标题:
Stock price using LSTM and its implementation
原文链接:
https://www.analyticsvidhya.com/blog/2021/12/stock-price-prediction-using-lstm/
编辑:黄继彦
校对:林亦霖
译者简介
王可汗,清华大学机械工程系直博生在读。曾经有着物理专业的知识背景,研究生期间对数据科学产生浓厚兴趣,对机器学习AI充满好奇。期待着在科研道路上,人工智能与机械工程、计算物理碰撞出别样的火花。希望结交朋友分享更多数据科学的故事,用数据科学的思维看待世界。