使用Python实现Attention-CNN-BiLSTM模型进行股票价格预测实例

实现Attention-CNN-BiLSTM模型用于时间序列预测(如股票价格预测)的项目需要多个部分的设计,包括数据获取、模型构建、训练和评估。以下是一个详细的项目实例,包含完整的代码和示例数据。

一、模型基本介绍

Attention-CNN-BiLSTM模型

  • CNN(卷积神经网络):用于提取局部特征,能够捕捉短期依赖。
  • BiLSTM(双向长短期记忆网络):能够处理长时间序列数据,双向结构可以获取过去和未来的信息。
  • Attention机制:能够动态关注时间序列中重要的信息,有助于提升模型的预测性能。

二、环境配置

1. 软件环境

  • Python 3.x
  • TensorFlow 2.x PyTorch
  • 其他必要库:NumPy, Pandas, Matplotlib, scikit-learn

2. 安装依赖 使用pip安装所需的库:

bash复制代码

pip install numpy pandas matplotlib scikit-learn tensorflow

如果使用PyTorch,请根据系统配置安装PyTorch

三、数据准备

这里我们将使用股票市场数据,您可以从Yahoo FinanceAlpha Vantage等网站获取数据。在这里,我们将生成一个简单的示例数据集。

 

import pandas as pd

# 生成示例股票价格数据

def generate_stock_data(num_samples=1000):

    np.random.seed(42)

    dates = pd.date_range(start='2020-01-01', periods=num_samples)

    prices = np.random.rand(num_samples) * 100  # 随机生成价格

    return pd.DataFrame({'Date': dates, 'Close': prices})

# 生成数据

stock_data = generate_stock_data()

print(stock_data.head())

四、数据预处理

将数据集分为训练集和测试集,并进行标准化处理。

 reshape(-1, 1)

scaler = MinMaxScaler()

data_scaled = scaler.fit_transform(data)

# 创建时间序列数据集

def create_dataset(data, time_step=1):

    X, y = [], []

    for i in range(len(data) - time_step - 1):

        X.append(data[i:(i + time_step), 0])

        y.append(data[i + time_step, 0])

    return np.array(X), np.array(y)

time_step = 10

X, y = create_dataset(data_scaled, time_step)

# 拆分数据集

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 重塑输入数据以适应LSTM [样本数, 时间步, 特征数]

X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)

X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)

五、模型实现

以下是Attention-CNN-BiLSTM模型的实现示例。

 

        super(AttentionLayer, self).__init__()

    def call(self, inputs):

        # 计算注意力权重

        attention_probs = layers.Dense(units=inputs.shape[-1], activation='softmax')(inputs)

        context_vector = layers.Dot(axes=[1, 1])([attention_probs, inputs])

        return context_vector

class AttentionCNNBiLSTM(models.Model):

    def __init__(self, time_steps):

        super(AttentionCNNBiLSTM, self).__init__()

        self.cnn = layers.Conv1D(filters=64, kernel_size=3, padding='same', activation='relu')

        self.bilstm = layers.Bidirectional(layers.LSTM(50, return_sequences=True))

        self.attention = AttentionLayer()

        self.flatten = layers.Flatten()

        self.dense = layers.Dense(1# 输出层

    def call(self, inputs):

        x = self.cnn(inputs)

        x = self.bilstm(x)

        x = self.attention(x)

        am', loss='mean_squared_error')

# 打印模型结构

model.summary()

六、模型训练

python复制代码

# 训练模型

history = model.fit(X_train, y_train, epochs=50, batch_size=32, validation_data=(X_test, y_test))

七、模型评估

使用MAEMSEMAPE等指标评估模型效果。

 

mae = mean_absolute_error(y_test_inverse, y_pred_inverse)

mse = mean_squared_error(y_test_inverse, y_pred_inverse)

mape = np.mean(np.abs((y_test_inverse - y_pred_inverse) / y_test_inverse)) * 100

print(f'MAE: {mae:.4f}, MSE: {mse:.4f}, MAPE: {mape:.2f}%')

# 可视化训练过程

import matplotlib.pyplot as plt

plt.plot(history.history['loss'], label='train_loss')

plt.plot(history.history['val_loss'], label='val_loss')

plt.title('Model Loss')

plt.xlabel('Epochs')

plt.ylabel('Loss')

plt.legend()

plt.show()

# 可视化预测结果

plt.figure(figsize=(10, 6))

plt.plot(y_test_inverse, label='True Price', color='blue')

plt.plot(y_pred_inverse, label='Predicted Price', color='orange')

 

plt.legend()

plt.show()

八、总结

本项目展示了如何使用Python实现Attention-CNN-BiLSTM模型进行股票价格预测。通过有效的数据预处理和模型训练,模型能够在测试集上实现较低的MAEMSEMAPE,并达到较高的预测准确率。

更多详细内容请访问

使用Python实现Attention-CNN-BiLSTM模型进行股票价格预测实例(包含详细的完整的程序和数据)资源-CSDN文库  https://download.csdn.net/download/xiaoxingkongyuxi/89834082

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xiaoxingkongyuxi

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值