使用CNN提取股票价格特征-解决Conv1D ValueError: One of the dimensions in the output is <= 0 错误

本文将介绍如何使用CNN提取股票价格特征,并解决在构建模型时出现的“ValueError: One of the dimensions in the output is <= 0”错误。

代码示例

import pandas as pd
import numpy as np

# 加载数据
data = pd.read_excel('E:\pythonProject5\深度学习\新建 XLS 工作表.xls')

# 提取每日开盘价、收盘价、最高价和最低价
open_prices = data['开盘'].values
close_prices = data['收盘'].values
high_prices = data['最高'].values
low_prices = data['最低'].values

# 将价格数据转换为二维数组
prices = np.array([open_prices, close_prices, high_prices, low_prices])
prices = np.transpose(prices)

from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout

# 定义CNN模型
model = Sequential()
model.add(Conv1D(64, 3, activation='relu', input_shape=(prices.shape[1], 1)))
model.add(MaxPooling1D(2))
model.add(Conv1D(32, 3, activation='relu', strides=1))
model.add(MaxPooling1D(2))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='linear'))

model.summary()

# 将数据转换为三维数组
prices = np.expand_dims(prices, axis=2)

# 将数据输入模型
features = model.predict(prices)

# 提取特征
features = np.squeeze(features)                                                         

Traceback (most recent call last):
  File "E:\pythonProject5\深度学习\vf.py", line 24, in <module>
    model.add(Conv1D(32, 3, activation='relu', strides=1))
  File "C:\Users\Administrator\anaconda3\lib\site-packages\tensorflow\python\trackable\base.py", line 205, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\Administrator\anaconda3\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Administrator\anaconda3\lib\site-packages\keras\layers\convolutional\base_conv.py", line 354, in compute_output_shape
    raise ValueError(
ValueError: One of the dimensions in the output is <= 0 due to downsampling in conv1d_1. Consider increasing the input size. Received input shape [None, 1, 64] which would produce output shape with a zero or negative value in a dimension.

错误原因

这个错误提示是因为在第二个卷积层中使用了 stride=1,但是经过第一个 MaxPooling1D 层后,输出的特征图大小已经被缩小了一半,导致第二个卷积层输出的特征图大小为0或负数。

解决方法

  1. 调整卷积层的参数: 可以尝试调整卷积核大小、步长等参数,确保第二个卷积层的输出特征图大小大于0。
  2. 增加输入数据的大小: 可以尝试增加输入数据的大小,例如增加时间序列长度,从而避免特征图大小缩减到0。
  3. 使用Padding: 可以考虑在卷积层中使用 padding='same' 来保留特征图大小,避免特征图被缩减。

总结

本文介绍了使用CNN提取股票价格特征的示例代码,并分析了“ValueError: One of the dimensions in the output is <= 0”错误的原因和解决方法。希望本文能对您理解CNN模型构建和解决错误有所帮助。

注意: 本文仅供参考,实际应用中需要根据具体情况进行调整。

使用CNN提取股票价格特征-解决Conv1D ValueError: One of the dimensions in the output is <= 0 错误

原文地址: https://www.cveoy.top/t/topic/oZUt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录