写一个预测原油期货的程序,用GRU
时间: 2023-12-27 11:19:53 浏览: 194
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, GRU
# 读取数据
df = pd.read_csv('crude_oil.csv')
# 将日期列转换为Datetime格式
df['Date'] = pd.to_datetime(df['Date'])
# 将日期列作为索引
df.set_index('Date', inplace=True)
# 取出收盘价列
close_price = df['Close']
# 数据归一化处理
scaler = MinMaxScaler(feature_range=(0, 1))
close_price = scaler.fit_transform(np.array(close_price).reshape(-1, 1))
# 定义函数创建数据集
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i + look_back, 0])
return np.array(X), np.array(Y)
# 创建数据集,使用前60天数据预测下一天的收盘价
look_back = 60
X_train, Y_train = create_dataset(close_price, look_back)
# 将数据集转换为3D格式
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# 构建GRU模型
model = Sequential()
model.add(GRU(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(GRU(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(GRU(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 训练模型
model.fit(X_train, Y_train, epochs=100, batch_size=32)
# 使用模型预测未来7天的收盘价
future_days = 7
future_price = close_price[-look_back:]
predicted_price = []
for i in range(future_days):
x = future_price[-look_back:]
x = np.reshape(x, (1, look_back, 1))
y = model.predict(x)
predicted_price.append(y[0])
future_price = np.append(future_price, y, axis=0)
# 将预测的收盘价反归一化
predicted_price = scaler.inverse_transform(np.array(predicted_price).reshape(-1, 1))
# 输出预测结果
print(predicted_price)
阅读全文