当前位置: 首页 > article >正文

LSTM 与随机森林的对比

LSTM 与随机森林的对比

特性

LSTM

随机森林

适用场景

适合复杂的时间序列数据,能捕捉长时依赖

适合短期预测,适用于较小数据集

计算成本

训练成本较高,需要GPU加速

计算成本较低,易于并行化

可解释性

较低,难以理解内部状态

较高,可解释性强

对噪声的鲁棒性

对噪声敏感,可能需要更大数据量

对噪声较鲁棒,适用于非平稳数据

总结3点

  1. LSTM 适用于长时间依赖的序列预测,适合非线性、时序特征复杂的问题。

  2. 随机森林适用于短期时间序列预测,对于非时间依赖特征有较好的处理能力,计算效率高且易于解释。

  3. 实际应用时可以结合两者,如先用随机森林提取特征,再输入 LSTM 进行预测,提升预测精度。

完整案例

这个案例涉及 LSTM 和随机森林在时间序列预测中的完整流程。

包括:

  • 数据生成(模拟时间序列数据)

  • 数据预处理(特征工程、数据分割)

  • 模型训练(LSTM 和随机森林)

  • 可视化分析

  • 超参数优化(调优策略和优化点)

  • 最终结论(对比 LSTM 和随机森林的预测效果)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

# 1. 生成模拟时间序列数据
def generate_data(n=500):
    np.random.seed(42)
    time = np.arange(n)
    trend = 0.05 * time
    seasonality = 10 * np.sin(time * (2 * np.pi / 50))
    noise = np.random.normal(0, 2, n)
    data = trend + seasonality + noise
    return pd.DataFrame({'time': time, 'value': data})

data = generate_data()

# 2. 数据预处理
scaler = MinMaxScaler()
data['scaled_value'] = scaler.fit_transform(data[['value']])

# 3. 创建特征和标签
def create_features(data, window=10):
    X, y = [], []
    for i in range(len(data) - window):
        X.append(data['scaled_value'].iloc[i:i+window].values)
        y.append(data['scaled_value'].iloc[i+window])
    return np.array(X), np.array(y)

X, y = create_features(data)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)

# 4. 训练随机森林模型
rf = RandomForestRegressor(n_estimators=100)
rf.fit(X_train, y_train)
rf_preds = rf.predict(X_test)

# 5. 训练 LSTM 模型(使用 PyTorch)
class LSTMModel(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, output_size):
        super(LSTMModel, self).__init__()
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, output_size)
    
    def forward(self, x):
        lstm_out, _ = self.lstm(x)
        return self.fc(lstm_out[:, -1, :])

input_size = 1
hidden_size = 50
num_layers = 2
output_size = 1

model = LSTMModel(input_size, hidden_size, num_layers, output_size)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

X_train_torch = torch.tensor(X_train, dtype=torch.float32).unsqueeze(-1)
y_train_torch = torch.tensor(y_train, dtype=torch.float32).unsqueeze(-1)
X_test_torch = torch.tensor(X_test, dtype=torch.float32).unsqueeze(-1)

epochs = 20
for epoch in range(epochs):
    model.train()
    optimizer.zero_grad()
    outputs = model(X_train_torch)
    loss = criterion(outputs, y_train_torch)
    loss.backward()
    optimizer.step()
    print(f'Epoch {epoch+1}/{epochs}, Loss: {loss.item()}')

model.eval()
lstm_preds = model(X_test_torch).detach().numpy()

# 6. 可视化
plt.figure(figsize=(12, 8))
sns.set_style("darkgrid")

plt.subplot(2, 2, 1)
plt.plot(data['time'], data['value'], color='blue', label='Original Data')
plt.title("Original Time Series Data")
plt.legend()

plt.subplot(2, 2, 2)
plt.plot(y_test, label='True', color='black')
plt.plot(rf_preds, label='RF Prediction', color='red')
plt.title("Random Forest Prediction")
plt.legend()

plt.subplot(2, 2, 3)
plt.plot(y_test, label='True', color='black')
plt.plot(lstm_preds, label='LSTM Prediction', color='green')
plt.title("LSTM Prediction")
plt.legend()

plt.subplot(2, 2, 4)
plt.plot(y_test, label='True', color='black')
plt.plot(rf_preds, label='RF', color='red')
plt.plot(lstm_preds, label='LSTM', color='green')
plt.title("Model Comparison")
plt.legend()

plt.tight_layout()
plt.show()

图片

  1. 随机森林调优:增加 n_estimators=200,限制 max_depth=10 以避免过拟合。

  2. LSTM 模型优化

    • hidden_size=64 提高表达能力。

    • num_layers=3 使模型更深。

    • dropout=0.2 以减少过拟合。

    • epochs=50 确保充分训练,并在每 10 轮打印损失值。

  3. 进一步优化

    • 适当调整 batch_size,提高训练效率。

    • 尝试 GRU 以减少计算开销。


http://www.kler.cn/a/558473.html

相关文章:

  • LeetCode216
  • Python 的 Lambda 函数及应用场景
  • Stm32中SysTick 定时器的使用
  • Ubuntu 下 nginx-1.24.0 源码分析 - ngx_array_init 函数
  • 深度学习课程作业(Week1)
  • Websocket——心跳检测
  • 【愚公系列】《Python网络爬虫从入门到精通》027-初识Pandas和Series对象
  • 【Bert】自然语言(Language Model)入门之---Bert
  • C++学习笔记第一天(vs工程创建+基本知识)
  • 基于ffmpeg+openGL ES实现的视频编辑工具-环境搭建(三)
  • C++ 模板初阶
  • Cesium开发--自定义Primitive实现3D Gaussian Splatting渲染
  • 学习数据结构(11)二叉树(堆)下
  • 【目标检测】【YOLOv12】YOLOv12:Attention-Centric Real-Time Object Detectors
  • Jenkins 视图(View)
  • Python爬虫系列教程之第十三篇:构建高可用爬虫系统 —— 混合架构与自动化监控
  • TCP...
  • 量化自学 - 金融理论与python - Net Present Value 净现值
  • 智能自动化新纪元:AI与UiPath RPA的协同应用场景与技术实践
  • 【Python爬虫(42)】分布式爬虫:规模扩展与稳健维护之道