1.导包(安装好tensorflow2)
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, SimpleRNN
from sklearn.model_selection import train_test_split
import pandas as pd
2.设置时间步和用于存储损失和未来预测的数据列表
time_step = 7
loss_metrics_data = []
future_predictions_data = []
3.从序列数据中提取输入特征和目标
def extract_data(data, time_step):
X = []
y = []
for i in range(len(data) - time_step):
X.append([a for a in data[i:i + time_step]])
y.append(data[i + time_step])
X = np.array(X)
X = X.reshape(X.shape[0], X.shape[1], 1)
return X, y
4.读取数据
df = pd.read_csv("单品编号_售价_销量_品种(完整时间)(异常值处理).csv")
数据集如下:
5.根据分类名称和销售日期对销量求和
grouped = df.groupby(['分类名称', '销售日期'])['销量(千克)'].sum().reset_index()
6.创建一个字典,每个类别对应一个 DataFrame
dfs = {}
for category in grouped['分类名称'].unique():
dfs[category] = grouped[grouped['分类名称'] == category]
y = dfs[category]['销量(千克)']
7.将数据分为训练集和测试集
train, test = train_test_split(y, test_size=0.25, shuffle=False)
train = train.reset_index(drop=True)
test = test.reset_index(drop=True)
max_train = max(train)
train_norm = train / max_train
test_norm = test / max_train
8.提取时间序列特征
X_train, y_train = extract_data(train_norm, time_step)
X_test, y_test = extract_data(test_norm, time_step)
9.绘制训练数据
fig1 = plt.figure(figsize=(8, 5))
plt.plot(train)
plt.xlabel("时间")
plt.ylabel("销量")
plt.show()
10.创建并训练 Simple RNN 模型
model = Sequential()
model.add(SimpleRNN(units=8, input_shape=(time_step, 1), activation='relu'))
model.add(Dense(units=1, activation='linear'))
model.compile(optimizer='adam', loss="mean_squared_error")
model.summary()
model.fit(X_train, y_train, batch_size=128, epochs=300)
11.使用模型进行预测
y_pred = model.predict(X_test)
12.反归一化预测值和测试值
y_pred_original = y_pred * max_train
y_test_original = np.array(y_test) * max_train
13.绘制真实值和预测值的图形
plt.figure(figsize=(15, 6))
plt.plot(y_test_original, label="真实值", color='blue')
plt.plot(y_pred_original, label="预测值", color='red')
plt.title(f"{category} 的预测")
plt.xlabel("时间步")
plt.ylabel("数值")
plt.legend()
plt.show()
14.计算损失函数指标
mse_values = []
loss_test = tf.losses.mean_squared_error(y_test, y_pred).numpy()
mse_values.append(loss_test)
average_mse = np.mean(mse_values)
print(f"{category} 测试集上的损失 (MSE): {average_mse}")
rmse = np.sqrt(average_mse)
print(f"{category} 的 RMSE: {rmse}")
mape = 100 * np.mean(np.abs((y_test_original - y_pred_original) / y_test))
print(f"{category} 的 MAPE: {mape}%")
rmspe = 100 * np.sqrt(np.mean(((y_test_original - y_pred_original) / y_test) ** 2))
print(f"{category} 的 RMSPE: {rmspe}%")
mae = np.mean(np.abs(y_test_original - y_pred_original))
print(f"{category} 的 MAE: {mae}")
naive_forecast_error = np.mean(np.abs(y_test_original[1:] - y_test_original[:-1]))
mase = mae / naive_forecast_error
print(f"{category} 的 MASE: {mase}")
15.获取未来7天的预测
last_data = np.array(test_norm[-time_step:]).reshape(1, time_step, 1)
future_predictions = []
for _ in range(7):
future_pred = model.predict(last_data)
future_predictions.append(future_pred[0][0])
last_data = np.append(last_data[0][1:], future_pred).reshape(1, time_step, 1)
16.反归一化未来预测值
future_predictions = np.array(future_predictions) * max_train
print(f"{category} 的未来7天预测: {future_predictions}")