利用深度学习模型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()

```

相关推荐
艾醒5 分钟前
大模型面试题剖析:全量微调与 LoRA 微调
人工智能·python·算法
云烟成雨TD10 分钟前
NumPy 2.x 完全指南【三十二】通用函数(ufunc)之数学运算函数
python·机器学习·numpy
可触的未来,发芽的智生13 分钟前
微论-突触的作用赋能思考(可能是下一代人工智能架构的启发式理论)
人工智能·神经网络·架构·启发式算法
ZHOU_WUYI15 分钟前
介绍GSPO:一种革命性的语言模型强化学习算法
人工智能·算法·语言模型
listhi52024 分钟前
三电平逆变器SVPWM控制(无解耦功能)与谐波分析
算法·机器学习·支持向量机
机器之心28 分钟前
首个为具身智能而生的大规模强化学习框架RLinf!清华、北京中关村学院、无问芯穹等重磅开源
人工智能·openai
朱程1 小时前
写给自己的 LangChain 开发教程(四):RAG(1)
前端·人工智能
在钱塘江1 小时前
Langgraph从新手到老师傅-2-Agent是什么
人工智能·python
袁庭新1 小时前
2025年08月总结
人工智能·aigc
DreamLife☼1 小时前
工业 5G + AI:智能制造的未来引擎
人工智能·5g·ai·制造·控制·工业·scada