使用Python和TensorFlow实现基于LSTM网络的单特征预测回归任务
单特征:数据集中只包含2列,时间列+价格列,仅利用价格来预测价格
目录
一、数据集
二、任务目标
三、代码实现
1、从本地路径中读取数据文件
2、数据归一化
3、创建配置类,将LSTM的各个超参数声明为变量,便于后续使用
4、创建时间序列数据
5、划分数据集
6、定义LSTM网络
(1)创建顺序模型实例
(2)添加LSTM层
(3)添加全连接层
7、编译LSTM模型
8、训练模型
9、模型预测
10、数据反归一化
11、绘制图像
12、完整版代码
一、数据集
自建数据集–【load.xlsx】。包含2列:
二、任务目标
实现基于时间序列的单特征价格预测
三、代码实现
1、从本地路径中读取数据文件
# 字符串前的r表示一个"原始字符串",raw string
# 文件路径中包含多个反斜杠。如果我们不使用原始字符串(即不使用r前缀),那么Python会尝试解析\U、\N等作为转义序列,这会导致错误
data = pd.read_excel(r'E:\load.xlsx', index_col='date')
# print(data)
prices = data['price'].values
# print(prices)
打印data:
打印prices:
2、数据归一化
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_prices = scaler.fit_transform(prices.reshape(-1, 1)) # 二维数组
# print(scaled_prices)
打印归一化后的价格数据:
3、创建配置类,将LSTM的各个超参数声明为变量,便于后续使用
class Config():
timestep = 7 # 时间步长,滑动窗口大小
feature_size = 1 # 每个步长对应的特征数量,这里只使用1维,每天的价格数据
batch_size = 1 # 批次大小
output_size = 1 # 单输出任务,输出层为1,预测未来1天的价格
hidden_size = 128 # 隐藏层大小
num_layers = 1 # lstm的层数
learning_rate = 0.0001 # 学习率
epochs = 500 # 迭代轮数
model_name = 'lstm' # 模型名
best_loss = 0 # 记录损失
activation = 'relu' # 定义激活函数
config = Config()
4、创建时间序列数据
# 创建时间序列数据
X, y = [], []
for i in range(len(scaled_prices) - config.timestep):
# 从当前索引i开始,取sequence_length个连续的价格数据点,并将其作为特征添加到列表 X 中。
X.append(scaled_prices[i: i + config.timestep])
# 将紧接着这sequence_length个时间点的下一个价格数据点作为目标添加到列表y中。
y.append(scaled_prices[i + config.timestep])
X = np.array(X)
print(X)
y = np.array(y)
print(y)
打印特征数据:
打印标签数据:
5、划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, shuffle=False)
6、定义LSTM网络
(1)创建顺序模型实例
model = Sequential()
(2)添加LSTM层
model.add(LSTM(activation=config.activation, units=config.hidden_size, input_shape=(config.timestep, config.feature_size)))
(3)添加全连接层
model.add(Dense(config.output_size))
7、编译LSTM模型
model.compile(optimizer='adam', loss='mean_squared_error')
8、训练模型
history = model.fit(x=X_train, y=y_train, epochs=config.epochs, batch_size=config.batch_size, verbose=2)
9、模型预测
predictions = model.predict(X_test)
10、数据反归一化
y_test_true_unnormalized = scaler.inverse_transform(y_test)
y_test_preds_unnormalized = scaler.inverse_transform(predictions)
11、绘制图像
# 设置图形的大小为10x5单位
plt.figure(figsize=(10, 5))
# 绘制真实的测试集标签,使用圆圈('o')作为标记,并命名为'True Values'
plt.plot(y_test_true_unnormalized, label='True Values', marker='o')
# 绘制模型的预测值,使用叉号('x')作为标记,并命名为'Predictions'
plt.plot(y_test_preds_unnormalized, label='Predictions', marker='x')
# 设置图形的标题
plt.title('Comparison of True Values and Predictions')
# 设置x轴的标签
plt.xlabel('Time Steps')
# 设置y轴的标签
plt.ylabel('Prices')
# 显示图例
plt.legend()
# 显示图形
plt.show()
12、完整版代码
import pandas as pd
import numpy as np
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot as plt
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
class Config():
timestep = 7
hidden_size = 128
batch_size = 1
output_size = 1
epochs = 500
feature_size = 1
activation = 'relu'
config = Config()
# dataframe对象
qy_data = pd.read_excel(r'E:\load.xlsx', index_col='date')
# print(qy_data)
# numpy数组 一维
prices = qy_data['price'].values
# print(prices)
scaler = MinMaxScaler()
# 归一化后变成二维数组
scaled_prices = scaler.fit_transform(prices.reshape(-1, 1))
# print(scaled_prices)
# Create time series data
X, y = [], []
for i in range(len(scaled_prices) - config.timestep):
X.append(scaled_prices[i: i + config.timestep])
y.append(scaled_prices[i + config.timestep])
X = np.array(X)
# print(X)
y = np.array(y)
# print(y)
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, shuffle=False)
# Define the LSTM mode
model = Sequential()
model.add(LSTM(activation=config.activation, units=config.hidden_size, input_shape=(config.timestep, config.feature_size)))
model.add(Dense(config.output_size))
# Compile the model
# adam默认学习率是0.01
model.compile(optimizer='adam', loss='mean_squared_error')
model.save('LSTM.h5')
# Train the model
history = model.fit(x=X_train, y=y_train, epochs=config.epochs, batch_size=config.batch_size, verbose=2)
# Predictions
predictions = model.predict(X_test)
# Inverse transform predictions and true values
y_test_true_unnormalized = scaler.inverse_transform(y_test)
y_test_preds_unnormalized = scaler.inverse_transform(predictions)
# Plot true values and predictions
plt.figure(figsize=(10, 5))
plt.plot(y_test_true_unnormalized, label='True Values', marker='o')
plt.plot(y_test_preds_unnormalized, label='Predictions', marker='x')
plt.title('Comparison of True Values and Predictions')
plt.xlabel('Time Steps')
plt.ylabel('Prices')
plt.legend()
plt.show()
作者:Star_KeyW