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

```

相关推荐
冷yan~2 分钟前
构建下一代AI智能体:基于Spring AI的多轮对话应用
java·人工智能·spring·ai
fouen4 分钟前
【语义分割专栏】先导篇:评价指标(PA,CPA,IoU,mIoU,FWIoU,F1)
人工智能·算法·机器学习·计算机视觉
Jamence17 分钟前
多模态大语言模型arxiv论文略读(八十三)
论文阅读·人工智能·深度学习·语言模型·论文笔记
纪伊路上盛名在20 分钟前
LLM大语言模型系列1-token
字符编码·人工智能·语言模型·自然语言处理·token·文本处理
北温凉22 分钟前
【学习笔记】机器学习(Machine Learning) | 第七章|神经网络(2)
笔记·机器学习
Johny_Zhao24 分钟前
HSRP、GLBP、VRRP、NSRP 协议对比与配置指南
网络·人工智能·网络安全·信息安全·云计算·cisco·huawei·系统运维·华三
深蓝易网1 小时前
打破传统仓库管理困局:WMS如何重构出入库全流程
大数据·运维·人工智能·重构·数据分析·制造
FF-Studio1 小时前
【硬核数学】2. AI如何“学习”?微积分揭秘模型优化的奥秘《从零构建机器学习、深度学习到LLM的数学认知》
人工智能·深度学习·学习·机器学习·自然语言处理·微积分·高等数学
仙人掌_lz1 小时前
深入理解蒙特卡洛树搜索(MCTS):python从零实现
人工智能·python·算法·ai·强化学习·rl·mcts
追逐☞1 小时前
机器学习(14)——模型调参
人工智能·机器学习