(29-6-02)通过回测、ARIMA 和 GRU 预测股票价格:深度学习模型预测(2)

29.8.4  训练和测试数据集的划分

训练和测试数据集的划分是机器学习中评估模型在未见数据上的表现的重要过程。通过将数据集分成两个部分:训练集用于训练模型,测试集用于评估模型的性能,我们可以更好地了解模型对新数据的泛化能力。这一过程可以帮助我们避免过拟合,即模型在训练集上表现良好,但在测试集上表现不佳,因为模型过度学习了训练数据。

在本项目中,通过下面代码的功能是将数据集按照75%的比例划分为训练集和25%的比例划分为测试集。首先,它设定了一个阈值,将数据集分为训练数据和测试数据,然后输出训练集和测试集的形状。

# 设置数据划分的阈值
threshold = int(X.shape[0] * 0.75)  # 75%的数据用于训练

# 75%的数据用于训练
X_train, y_train = X[:threshold], y[:threshold]

# 25%的数据用于测试
X_test, y_test = X[threshold:], y[threshold:]

# 打印训练集和测试集的形状
print("X_train shape:", X_train.shape)
print("y_train shape:", y_train.shape)
print("X_test shape:", X_test.shape)
print("y_test shape:", y_test.shape)

执行后会输出:

X_train shape: (3468, 13, 13)
y_train shape: (3468,)
X_test shape: (1156, 13, 13)
y_test shape: (1156,)

29.8.5  构建和训练模型

接下来开始构建和训练模型,在这一步中主要实现下面的功能:

  1. 设置模型架构:将定义模型架构,包括一个或多个层的类型、神经元的数量、激活函数和输入形状。
  2. 编译模型:接下来,将通过指定损失函数、优化器以及任何其他希望监控的指标来编译模型。
  3. 训练模型:最后,将通过指定训练的轮数、批次大小以及训练数据来训练模型。
  4. 评估模型:一旦模型训练完成,我们将通过计算在验证数据上的准确性和其他性能指标来评估模型。

(1)下面代码定义并打印了一个用于时间序列预测的神经网络模型。模型架构包括一个输入层与训练数据形状相同,一个包含64个隐藏状态的GRU层,一个具有8个神经元并使用ReLU激活函数的全连接层,最后是一个输出层,用线性激活函数预测单一目标值。

# 定义一个Sequential模型
model = Sequential()

# 添加一个与训练数据形状相同的输入层
model.add(InputLayer((X_train.shape[1], X_train.shape[2])))

# 添加一个具有64个隐藏状态的GRU层
model.add(GRU(64))

# 添加一个具有8个神经元并使用ReLU激活的Dense层
model.add(Dense(8, 'relu'))

# 添加一个具有1个神经元并使用线性激活的输出层
model.add(Dense(1, 'linear'))

# 打印模型的摘要
model.summary()

执行后输出:

2024-08-23 21:35:23.769436: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:23.773514: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:23.774280: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:23.776147: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2024-08-23 21:35:23.776519: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:23.777502: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:23.778408: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:27.591823: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:27.592657: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:27.593387: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:937] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2024-08-23 21:35:27.593991: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1510] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 15185 MB memory:  -> device: 0, name: Tesla P100-PCIE-16GB, pci bus id: 0000:00:04.0, compute capability: 6.0
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
gru (GRU)                    (None, 64)                15168     
_________________________________________________________________
dense (Dense)                (None, 8)                 520       
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 9         
=================================================================
Total params: 15,697
Trainable params: 15,697
Non-trainable params: 0
_________________________________________________________________

(2)下面代码创建了一个早期停止回调,用于监控模型在验证集上的损失,并在训练过程中根据设置的条件停止训练。然后,代码编译了模型,设置了均方误差作为损失函数,使用Adam优化器,并通过根均方误差作为评估指标。最后,在训练集上训练模型,并在验证集上进行验证,同时应用早期停止回调。

# 创建一个早期停止回调以监控验证损失
callback = EarlyStopping(
    # 监控验证损失
    monitor="val_loss",
    # 损失变化的最小值,才算作改进
    min_delta=0.001,
    # 如果连续5个周期没有改进则停止训练
    patience=5,
    # 输出详细模式
    verbose=1,
    # 自动选择模式
    mode="auto",
    # 监控数量的基准值
    baseline=None,
    # 是否从最佳周期恢复模型权重
    restore_best_weights=False
)

# 编译模型
model.compile(loss='mse', optimizer=Adam(learning_rate=0.001), metrics=[RootMeanSquaredError()])

# 训练模型
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=100, callbacks=callback)

执行后会输出:

2024-08-23 21:35:28.634027: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)
Epoch 1/100
2024-08-23 21:35:30.804070: I tensorflow/stream_executor/cuda/cuda_dnn.cc:369] Loaded cuDNN version 8005
109/109 [==============================] - 4s 7ms/step - loss: 6.7591e-04 - root_mean_squared_error: 0.0260 - val_loss: 0.0035 - val_root_mean_squared_error: 0.0595
Epoch 2/100
109/109 [==============================] - 0s 4ms/step - loss: 1.7683e-05 - root_mean_squared_error: 0.0042 - val_loss: 0.0033 - val_root_mean_squared_error: 0.0571
Epoch 3/100
109/109 [==============================] - 0s 4ms/step - loss: 1.0447e-05 - root_mean_squared_error: 0.0032 - val_loss: 0.0033 - val_root_mean_squared_error: 0.0576
Epoch 4/100
109/109 [==============================] - 0s 4ms/step - loss: 7.8711e-06 - root_mean_squared_error: 0.0028 - val_loss: 0.0034 - val_root_mean_squared_error: 0.0584
Epoch 5/100
109/109 [==============================] - 0s 4ms/step - loss: 6.9226e-06 - root_mean_squared_error: 0.0026 - val_loss: 0.0033 - val_root_mean_squared_error: 0.0574
Epoch 6/100
109/109 [==============================] - 0s 4ms/step - loss: 6.7276e-06 - root_mean_squared_error: 0.0026 - val_loss: 0.0035 - val_root_mean_squared_error: 0.0588
Epoch 00006: early stopping

29.8.6  使用 GRU 进行预测

门控递归单元(GRU)是一种用于处理序列数据的递归神经网络(RNN)变体。GRU 通过引入门控机制来解决传统 RNN 在长序列训练中遇到的梯度消失和爆炸问题。它包含两个主要的门控:重置门和更新门。重置门决定了之前状态对当前计算的影响程度,而更新门则控制了当前状态对模型的影响。GRU 相较于长短期记忆(LSTM)网络,结构更简单,计算更高效,能够在处理序列数据时提供更好的性能。使用 GRU 进行预测时需要注意:

  1. 确保数据规范化:在将数据输入 GRU 模型之前,必须确保数据已经规范化。这有助于确保模型不会对某些特征产生偏倚。
  2. 选择合适的学习率:选择一个既不太大也不太小的学习率。这将有助于确保模型不会过拟合或欠拟合数据。
  3. 使用适当的正则化:正则化有助于防止过拟合和欠拟合。使用适当的正则化技术,如 dropout、L2 正则化或早期停止,以确保模型不会过拟合或欠拟合数据。
  4. 调整模型超参数:调整模型的超参数,如层数、每层的神经元数量、优化器等,以确保模型能够在未见数据上良好地进行泛化。
  5. 使用良好的验证策略:一个好的验证策略对于确保模型在未见数据上能够良好地泛化非常重要。使用交叉验证、保留法或自助法等良好的验证策略,以确保模型能够良好地泛化。

(1)使用训练好的 GRU 模型对测试数据集 X_test 进行预测,并将预测结果转换为一维数组。随后,创建一个数据框 test_results 来对比预测值与实际值,并显示这些值。

# 使用 GRU 模型对 X_test 进行预测,然后将数据转换为一维数组
test_predictions = model.predict(X_test).flatten()
# 创建一个数据框来对比测试预测值和实际值
test_results = pd.DataFrame(data={'Test Predictions': test_predictions, 'Actuals': y_test})
# 显示这些值
test_results

执行后会输出:

Test Predictions	Actuals
0	0.377864	0.376329
1	0.378204	0.380764
2	0.378463	0.381507
3	0.375202	0.376793
4	0.374757	0.371249
...	...	...
1151	0.586198	0.593833
1152	0.592010	0.601970
1153	0.590334	0.602508
1154	0.589119	0.592959
1155	0.598000	0.622413
1156 rows × 2 columns

(2)绘制目标值和预测值有助于可视化模型的表现,并查看预测结果与目标值的接近程度。这可以帮助识别模型中的错误,并检查需要额外关注的地方。此外,对模型的表现进行时间上的比较也是有帮助的,这使得调整模型以获得更好的结果变得更加容易。下面代码绘制了使用GRU模型进

# 绘制预测值
plt.plot(test_results['Test Predictions']) 
# 绘制实际值
plt.plot(test_results['Actuals'])
# 移除顶部边框
plt.gca().spines['top'].set_visible(False)
# 移除右侧边框
plt.gca().spines['right'].set_visible(False)
# 添加图例
plt.legend(['Predictions', 'Actuals'])
# 设置 y 轴标签
plt.ylabel('Predictions / Actuals')
# 设置 x 轴标签
plt.xlabel('Time')
# 设置图表标题
plt.title('Predictions and Actuals over time, GRU Model', fontsize=18)
# 显示图表
plt.show()

执行效果如图29-25所示,展示了预测值和实际值的时间序列图,并进行了图表的美化处理,包括添加图例、标签、标题,以及去除图表的顶部和右侧边框。

图29-25  测试集上的预测图

29.8.7  模型评估

模型评估是机器学习中的关键步骤,用于验证模型的性能和有效性。通过评估,数据科学家可以确定模型是否能够准确地预测结果,识别潜在的过拟合或欠拟合问题,并确保模型在实际应用中的表现与预期一致。评估过程通常包括计算各种性能指标,如准确率、精确率、召回率和均方误差,以确保模型能够对新数据做出有效的预测,并在实际应用中发挥其预期作用。

在本项目中,模型评估非常重要,因为它有助于确保机器学习模型正常工作,并适合其预期用途。通过进行模型评估,数据科学家可以确保模型经过优化,能够最佳地表示数据并提供准确的预测。通过下面的代码计算并打印GRU模型在测试集上的均方误差(MSE)。均方误差是衡量模型预测值与实际值之间差异的标准指标,用于评估模型的性能。

print('MSE of the GRU model ::', round(mse(test_results['Test Predictions'], test_results['Actuals']),6))

执行后会输出:

MSE of the GRU model : 0.003459

上面的输出结果表示 GRU 模型在测试数据上的均方误差(MSE)为 0.003459,这是衡量模型预测准确性的一种方式,数值越小表明模型的预测越接近实际值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农三叔

感谢鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值