利用深度学习模型BiLSTM进行数据预测和分析

  1. 导入必要的库和模块:

```python

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import StandardScaler

from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score

import matplotlib.pyplot as plt

import numpy as np

import tensorflow as tf

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Bidirectional, LSTM, Dense

```

  1. 加载数据并准备训练集和测试集:

```python

data = pd.read_excel('c.xlsx').iloc[0:, 1:]

X, y = data.iloc[:, 0:-1], data.iloc[:, -1]

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

```

  1. 缩放特征:

```python

scaler = StandardScaler()

X_train_scaled = scaler.fit_transform(X_train)

X_test_scaled = scaler.transform(X_test)

```

  1. 构建 BiLSTM 模型并进行训练:

```python

model = Sequential()

model.add(Bidirectional(LSTM(units=64, return_sequences=True), input_shape=(X_train_scaled.shape[1], X_train_scaled.shape[2])))

model.add(Dense(1)) # Regression problems typically have output layer with one neuron

model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(X_train_scaled, y_train, epochs=10, batch_size=32)

```

  1. 在测试集上进行预测并评估模型:

```python

y_pred = model.predict(X_test_scaled)

mse = mean_squared_error(y_test, y_pred)

rmse = np.sqrt(mse)

mae = mean_absolute_error(y_test, y_pred)

r2 = r2_score(y_test, y_pred)

print("RMSE:", rmse)

print("MAE:", mae)

print("R²:", r2)

```

  1. 绘制拟合对比曲线图:

```python

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

plt.plot(range(len(y_test)), y_test, color='darkorange', label='Actual')

plt.plot(range(len(y_pred)), y_pred, color='navy', linewidth=2, label='Predicted')

plt.xlabel('Sample Index')

plt.ylabel('Target Variable')

plt.title('BiLSTM Regression Fit Comparison')

plt.legend()

plt.grid(True)

plt.show()

```

相关推荐
Lethehong1 小时前
昇腾Atlas 800T平台下Qwen-14B大语言模型的SGLang适配与性能实测
人工智能·语言模型·sglang·昇腾npu
杜子不疼.1 小时前
Spring AI 与向量数据库:构建企业级 RAG 智能问答系统
数据库·人工智能·spring
ayingmeizi1631 小时前
AI CRM赋能全链路数字化如何重塑医械企业渠道竞争力?
人工智能
————A1 小时前
从 RAG 召回失败到故障链推理
人工智能·rag
Chase_______2 小时前
AI提效指南:Nano Banana 生成精美PPT与漫画
人工智能·powerpoint
雨大王5122 小时前
汽车产业供应链优化的可行策略及案例分析
人工智能·机器学习
梁辰兴2 小时前
三星自研GPU剑指AI芯片霸权,2027年能否撼动英伟达?
人工智能·gpu·芯片·电子·ai芯片·三星·梁辰兴
吴佳浩9 小时前
Python入门指南(七) - YOLO检测API进阶实战
人工智能·后端·python
tap.AI9 小时前
RAG系列(二)数据准备与向量索引
开发语言·人工智能
老蒋新思维9 小时前
知识IP的长期主义:当AI成为跨越增长曲线的“第二曲线引擎”|创客匠人
大数据·人工智能·tcp/ip·机器学习·创始人ip·创客匠人·知识变现