使用LSTM实现IBM股票价格预测
一、导入第三方库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
from keras.optimizers import SGD
二、加载历史数据文件
dataset = pd.read_csv("datasets_8388_11883_IBM_2006-01-01_to_2018-01-01.csv",index_col='Date',parse_dates=['Date'])
dataset.head()
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第1张图片](http://img.e-com-net.com/image/info8/b9d26d2e50e74c9198cf2ebb3b6c0110.jpg)
dataset.shape
train_set = dataset[:'2016'].iloc[:,1:2].values
test_set = dataset['2017':].iloc[:,1:2].values
train_set.shape
test_set.shape
三、定义显示函数
def plot_predictions(test_result, predict_result):
"""
test_result:真实值
predict_result: 预测值
"""
plt.plot(test_result,color='red',label='IBM True Stock Price')
plt.plot(predict_result,color='blue',label='IBM Predicted Stock Price')
plt.title('IBM Stock Price')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
四、绘制训练集和测试集的数据
dataset['High'][:'2016'].plot(figsize=(16,4),legend=True)
dataset['High']['2017':].plot(figsize=(16,4),legend=True)
plt.title('IBM Stock Price')
plt.legend(['Train set(before 2016)','Test set(after 2017)'])
plt.show()
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第2张图片](http://img.e-com-net.com/image/info8/36fcc2224c1c412a8c61a4f10f4662ce.jpg)
sc = MinMaxScaler(feature_range = [0,1])
train_set_scaled = sc.fit_transform(train_set)
X_train = []
y_train = []
for i in range(60, 2769) :
X_train.append(train_set_scaled[i-60:i,0])
y_train.append(train_set_scaled[i,0])
X_train, y_train = np.array(X_train) , np.array(y_train)
X_train.shape
X_train[0]
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第3张图片](http://img.e-com-net.com/image/info8/e182653538d44641bb1af9978e534138.jpg)
X_train = np.reshape(X_train,(X_train.shape[0],X_train.shape[1],1))
X_train.shape
五、搭建LSTM模型,进行训练和预测
model = Sequential()
model.add(LSTM(128,return_sequences=True,input_shape=(X_train.shape[1],1)))
model.add(Dropout(0.2))
model.add(LSTM(128,return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(128))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='rmsprop',loss='mse')
model.fit(X_train, y_train,epochs=20,batch_size=32)
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第4张图片](http://img.e-com-net.com/image/info8/e271b087067242099ef4491f1df1ebfc.jpg)
六、构建数据集,进行训练
dataset_total = pd.concat((dataset['High'][:'2016'],dataset['High']['2017':]),axis = 0)
dataset_total.shape
dataset_total
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第5张图片](http://img.e-com-net.com/image/info8/5433a8cb6e9b4571910536f485f16760.jpg)
inputs = dataset_total[len(train_set):].values
inputs = inputs.reshape(-1,1)
inputs.shape
inputs_scaled = sc.fit_transform(inputs)
七、构建测试集X_test,进行股价预测
dataset_total = pd.concat((dataset['High'][:'2016'],dataset['High']['2017':]),axis=0)
inputs = dataset_total[len(dataset_total) - len(test_set) - 60 :].values
inputs
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第6张图片](http://img.e-com-net.com/image/info8/4ffd59f5c87446ddae05585f472f90d2.jpg)
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
inputs.shape
X_test = []
for i in range(60,311):
X_test.append(inputs[i-60:i,0])
X_test = np.array(X_test)
X_test.shape
X_test = np.reshape(X_test,(X_test.shape[0],X_test.shape[1],1))
X_test.shape
predict_test = model.predict(X_test)
predict_test.shape
![在这里插入图片描述](http://img.e-com-net.com/image/info8/21bff5b058ce4c2898bb57c54adfe62c.jpg)
predict_stock_price = sc.inverse_transform(predict_test)
predict_stock_price
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第7张图片](http://img.e-com-net.com/image/info8/a0f1cdfbf80841fbbb2e8828d2e1d9b4.jpg)
plot_predictions(test_set,predict_stock_price)
![【机器学习实战】三、使用LSTM实现IBM股票价格预测_第8张图片](http://img.e-com-net.com/image/info8/d02aa37829eb47289bf2f645e9629e87.jpg)