LSTM_预测价格问题_keras_代码实操
0、问题描述
使用Bicton数据集,对close数据进行预测,使用60个数据点预测第61个数据点。
下载数据集:Bitcoin Historical Data
前期已经使用了MLP和RNN进行预测:这里
1、
没有写完,明天再写:)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import warnings
from sklearn.metrics import mean_absolute_error
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout,Flatten
warnings.filterwarnings("ignore")
## 1、导入数据
bit_data = pd.read_csv("bitstampUSD_1-min_data_2012-01-01_to_2021-03-31.csv")
## 2、数据预处理
"""
将时间戳转成日期形式
划分训练集和测试集(最后60行)
将close值归一化在0-1之间
选择 60 个数据点作为 x-train,选择第 61 个数据点作为 y-train。
"""
bit_data["date"] = pd.to_datetime(bit_data["Timestamp"],unit="s").dt.date
group=bit_data.groupby("date")
data=group["Close"].mean()
close_train=data.iloc[:len(data)-60]
close_test=data.iloc[len(close_train):]
close_train=np.array(close_train)
close_train=close_train.reshape(close_train.shape[0],1)
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler(feature_range=(0,1))
close_scaled=scaler.fit_transform(close_train)
timestep=60
x_train=[]
y_train=[]
for i in range(timestep,close_scaled.shape[0]):
x_train.append(close_scaled[i-timestep:i,0])
y_train.append(close_scaled[i,0])
x_train,y_train=np.array(x_train),np.array(y_train)
x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],1) #reshaped for RNN
print("x-train-shape= ",x_train.shape)
print("y-train-shape= ",y_train.shape)
## 3、创建模型
model = Sequential()
model.add(Dense(56, input_shape=(x_train.shape[1],1), activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Flatten())
model.add(Dense(1))
model.compile(optimizer="adam",loss="mean_squared_error")
## 4、训练
model.fit(x_train,y_train,epochs=50,batch_size=64)
## 5、预测
inputs=data[len(data)-len(close_test)-timestep:]
inputs=inputs.values.reshape(-1,1)
inputs=scaler.transform(inputs)
x_test=[]
for i in range(timestep,inputs.shape[0]):
x_test.append(inputs[i-timestep:i,0])
x_test=np.array(x_test)
x_test=x_test.reshape(x_test.shape[0],x_test.shape[1],1)
predicted_data=model.predict(x_test)
predicted_data=scaler.inverse_transform(predicted_data)
data_test=np.array(close_test)
data_test=data_test.reshape(len(data_test),1)
## 6、绘制预测图
plt.figure(figsize=(8,4), dpi=80, facecolor='w', edgecolor='k')
plt.plot(data_test,color="r",label="true result")
plt.plot(predicted_data,color="b",label="predicted result")
plt.legend()
plt.xlabel("Time(60 days)")
plt.ylabel("Values")
plt.grid(True)
plt.show()