深度学习R4周:LSTM-火灾温度预测

embedded/2025/2/15 21:40:06/
  • 🍨 本文为🔗365天深度学习训练营中的学习记录博客
  • 🍖 原作者:K同学啊

任务:

数据集中提供了火灾温度(Tem1)、一氧化碳浓度(CO 1)烟雾浓度(Soot 1)。随着时间变化数据,需要根据这些数据对未来某一时刻的火灾温度做出预测。

要求:

1.了解LSTM是什么,并使用其构建一个完整的程序

2.R2达到0.83

拔高:

使用第1-8个时刻的数据预测第9-10个时刻的温度数据

一、理论知识基础

1.LSTM原理

LSTM---RNN进阶版

如果RNN的最大限度是理解一句话,则LSTM的最大限度是理解一段话。

具体:

LSTM,长短期记忆网络(Long Short Term Memory networks),一种特有的RNN,能够学习到长期依赖关系。

所有的循环神经网络都有着重复的神经网络模块形成链的形式。在普通的RNN中、重复模块结构非常简单,其结构如下:

LSTM避免了长期以来的问题、可以记住长期信息! LSTM内部有较为复杂的结构,能通过门控状态来选择调整传输的信息,需要长时间记忆的信息,忘记不重要的信息。

 2.LSTM的数据处理流程

将时序数据(LSTM输入数据)以可视化形式呈现。

 

 

 根据输入的数据结构、预测输出、程序可以分为以下六类:

 3.代码实现

1.前期准备

1.1导入数据

import torch.nn.functional as F
import numpy  as np
import pandas as pd
import torch
from   torch  import nn

数据:训练营提供

data = pd.read_csv('/PythonProject/woodpine2.csv')print(data)

结果输出:

因为过年,台式机不在身边,尝试在线代码平台。

问题:Module Not FoundError:No module named ‘torch’

这个在线平台与平常学习环境很类似,比较好上手,但还没有找到如何安装torch的正确方法。

显示已经装好torch,但实际上没有办法继续使用,还在寻找更合适的方法。

1.2数据集可视化

import matplotlib.pyplot as plt
import seaborn as snsplt.rcParams['savefig.dpi'] = 500 #图片像素
plt.rcParams['figure.dpi']  = 500 #分辨率fig, ax =plt.subplots(1,3,constrained_layout=True, figsize=(14, 3))sns.lineplot(data=data["Tem1"], ax=ax[0])
sns.lineplot(data=data["CO 1"], ax=ax[1])
sns.lineplot(data=data["Soot 1"], ax=ax[2])
plt.show()

结果输出:

dataFrame = data.iloc[:,1:] 
print(dataFrame)

2.构建数据集

2.1数据集预处理

from sklearn.preprocessing import MinMaxScaler      dataFrame = data.iloc[:,1:].copy()      
sc  = MinMaxScaler(feature_range=(0, 1)) #将数据归一化,范围是0到1for i in ['CO 1', 'Soot 1', 'Tem1']:dataFrame[i] = sc.fit_transform(dataFrame[i].values.reshape(-1, 1))print(dataFrame.shape)

2.2设置x、y

width_X = 8
width_y = 1X = []
y = []in_start = 0for _, _ in data.iterrows():in_end  = in_start + width_Xout_end = in_end   + width_yif out_end < len(dataFrame):X_ = np.array(dataFrame.iloc[in_start:in_end , ])y_ = np.array(dataFrame.iloc[in_end  :out_end, 0])X.append(X_)y.append(y_)in_start += 1X = np.array(X)
y = np.array(y).reshape(-1,1,1)print(X.shape, y.shape)

结果输出:

2.3划分数据集

X_train = torch.tensor(np.array(X[:5000]), dtype=torch.float32)
y_train = torch.tensor(np.array(y[:5000]), dtype=torch.float32)X_test  = torch.tensor(np.array(X[5000:]), dtype=torch.float32)
y_test  = torch.tensor(np.array(y[5000:]), dtype=torch.float32)print(X_train.shape, y_train.shape)

结果输出:

from torch.utils.data import TensorDataset, DataLoadertrain_dl = DataLoader(TensorDataset(X_train, y_train),batch_size=64, shuffle=False)test_dl  = DataLoader(TensorDataset(X_test, y_test),batch_size=64, shuffle=False)

 3.模型训练

3.1构建LSTM模型

# 构建模型  
class model_lstm(nn.Module): classmodel_lstm(classmodel_lstm):  def __init__(self):   super(model_lstm, self).__init__()   self.lstm0 = nn.LSTM(input_size=3 ,hidden_size=320,    num_layers=1, batch_first=True)   self.lstm1 = nn.LSTM(input_size=320 ,hidden_size=320,num_layers=1, batch_first=True)   self.fc0   = nn.Linear(320, 1)   def forward(self, x): Defforward(self,x):  out, hidden1 = self.lstm0(x)    out, _ = self.lstm1(out, hidden1)    out    = self.fc0(out)    return out[:, -1:, :]   #取2个预测值,否则经过lstm会得到8*2个预测  model = model_lstm()   
print(model   model模型)

修改后得到

model(torch.rand(30,8,3)).shape
 

3.2定义训练/测试函数

# 定义训练函数
import copy
def train(train_dl, model, loss_fn, opt, lr_scheduler=None):size        = len(train_dl.dataset)  num_batches = len(train_dl)   train_loss  = 0  # 初始化训练损失和正确率for x, y in train_dl:  x, y = x.to(device), y.to(device)# 计算预测误差pred = model(x)          # 网络输出loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距# 反向传播opt.zero_grad()  # grad属性归零loss.backward()  # 反向传播opt.step()       # 每一步自动更新# 记录losstrain_loss += loss.item()if lr_scheduler is not None:lr_scheduler.step()print("learning rate = {:.5f}".format(opt.param_groups[0]['lr']), end="  ")train_loss /= num_batchesreturn train_loss
# 定义测试函数  
def test (dataloader, model, loss_fn):  size        = len(dataloader.dataset)  # 测试集的大小  num_batches = len(dataloader)          # 批次数目  test_loss   = 0  # 当不进行训练时,停止梯度更新,节省计算内存消耗  with torch.no_grad():  for x, y in dataloader:  x, y = x.to(device), y.to(device)  # 计算loss  y_pred = model(x)  loss        = loss_fn(y_pred, y)  test_loss += loss.item()  test_loss /= num_batches  return test_loss  

3.3正式训练

#设置GPU训练
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
deviceX_test = X_test.to(device)#训练模型
model = model_lstm()
model = model.to(device)
loss_fn    = nn.MSELoss() # 创建损失函数
learn_rate = 1e-1   # 学习率
opt        = torch.optim.SGD(model.parameters(),lr=learn_rate,weight_decay=1e-4)
epochs     = 50
train_loss = []
test_loss  = []
lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(opt,epochs, last_epoch=-1) for epoch in range(epochs):model.train()epoch_train_loss = train(train_dl, model, loss_fn, opt, lr_scheduler)model.eval()epoch_test_loss = test(test_dl, model, loss_fn)train_loss.append(epoch_train_loss)test_loss.append(epoch_test_loss)template = ('Epoch:{:2d}, Train_loss:{:.5f}, Test_loss:{:.5f}')print(template.format(epoch+1, epoch_train_loss,  epoch_test_loss))print("="*20, 'Done', "="*20)

让同学帮忙跑了代码,得到部分结果

4.模型评估

4.1 LOSS图

import matplotlib.pyplot as plt   importmatplotlib.pyplotaspltplt.figure(figsize=(5, 3),dpi=120) 图(图大小=(5.3),dpi=120)  plt.plot(train_loss    , label='LSTM Training Loss') plt.plot(train_loss,Label ='LSTM训练损失')  
plt.plot(test_loss, label='LSTM Validation Loss') plt.plot(test_loss,tag ="LSTM验证丢失")  plt.title('Training and Validation Loss') plt.title(“培训和验证损失”)  
plt.legend() legend()  
plt.show() plt.show)搜索结果  

4.2调用模型进行预测

# 测试集输入模型进行预测
# predicted_y_lstm = sc.inverse_transform(model(X_test).detach().numpy().reshape(-1,1))   
predicted_y_lstm = sc.inverse_transform(model(X_test).detach().cpu().numpy().reshape(-1,1))
y_test_1         = sc.inverse_transform(y_test.reshape(-1,1))
y_test_one       = [i[0] for i in y_test_1]
predicted_y_lstm_one = [i[0] for i in predicted_y_lstm]plt.figure(figsize=(5, 3),dpi=120)
# 画出真实数据和预测数据的对比曲线
plt.plot(y_test_one[:2000], color='red', label='real_temp')
plt.plot(predicted_y_lstm_one[:2000], color='blue', label='prediction')plt.title('Title')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()

4.3R2值评估

from sklearn import metrics
"""
RMSE :均方根误差  ----->  对均方误差开方
R2   :决定系数,可以简单理解为反映模型拟合优度的重要的统计量
"""
RMSE_lstm  = metrics.mean_squared_error(predicted_y_lstm_one, y_test_1)**0.5
R2_lstm    = metrics.r2_score(predicted_y_lstm_one, y_test_1)print('均方根误差: %.5f' % RMSE_lstm)
print('R2: %.5f' % R2_lstm)

二、总结

这周真的很混乱,身边没有台式机,在线平台也没有想象中好用,可能是我没有找到方式。LSTM学习掌握的很一般,明天就能有台式机。重新修改学习记录。文字知识已大致掌握,还需要代码加强。

LSTM的优点:

1.解决梯度消失问题:传统的RNN在处理长序列时容易出现梯度消失的问题,导致难以训练。
2.捕捉长期依赖关系:相比传统的RNN,LSTM有更好的记忆性能,可以在处理序列数据时保留较远的上下文信息。
3.可以学习到时序特征:LSTM具有对时间的敏感性,能够学习到时序数据中的模式和特征。这使得LSTM在时间序列预测、信号处理等任务中具有优势。

LSTM的缺点:

1.计算优化
2.模型简化
3.数据增强和迁移学习

这周真是失败的一次学习打卡。。。困难多多


http://www.ppmy.cn/embedded/162510.html

相关文章

游戏引擎学习第99天

仓库:https://gitee.com/mrxiao_com/2d_game_2 黑板&#xff1a;制作一些光场(Light Field) 当前的目标是为游戏添加光照系统&#xff0c;并已完成了法线映射&#xff08;normal maps&#xff09;的管道&#xff0c;但还没有创建可以供这些正常映射采样的光场。为了继续推进&…

DDoS技术解析

这里是Themberfue 今天我们不聊别的&#xff0c;我们聊聊著名的网络攻击手段之一的 DDoS&#xff0c;看看其背后的技术细节。 DoS 了解 DDoS 前&#xff0c;先来讲讲 DoS 是什么&#xff0c;此 DoS 而不是 DOS 操作系统啊。1996年9月6日&#xff0c;世界第三古老的网络服务提供…

Redis 数据类型 Zset 有序集合

有序集合相对于字符串、列表、哈希、集合来说会有⼀些陌⽣。它保留了集合不能有重复成员的特点&#xff0c;但与集合不同的是&#xff0c;有序集合中的每个元素都有⼀个唯⼀的浮点类型的分数&#xff08;score&#xff09;与之关 联&#xff0c;着使得有序集合中的元素是可以维…

基于SSM+uniapp的数学辅导小程序+LW示例参考

1.项目介绍 系统角色&#xff1a;管理员、普通用户功能模块&#xff1a;用户管理、学习中心、知识分类管理、学习周报管理、口算练习管理、试题管理、考试管理、错题本等技术选型&#xff1a;SSM&#xff0c;Vue&#xff08;后端管理web&#xff09;&#xff0c;uniapp等测试环…

Docker 镜像的构建与管理(二)

四、Docker 镜像管理 4.1 镜像的拉取与推送 在 Docker 的世界里&#xff0c;镜像的拉取与推送是与镜像仓库进行交互的基本操作。通过这些操作&#xff0c;我们可以方便地获取所需的镜像&#xff0c;以及将自己构建的镜像分享到仓库中&#xff0c;实现资源的共享与复用。 拉取…

一文深入了解DeepSeek-R1:模型架构

本文深入探讨了 DeepSeek-R1 模型架构。让我们从输入到输出追踪 DeepSeek-R1 模型&#xff0c;以找到架构中的新发展和关键部分。DeepSeek-R1 基于 DeepSeek-V3-Base 模型架构。本文旨在涵盖其设计的所有重要方面。 &#x1f4dd; 1. 输入上下文长度 DeepSeek-R1的输入上下文长…

SpringBoot 统一功能处理

1. 拦截器 引入 上个章节我们完成了强制登录的功能, 后端程序根据Session来判断用户是否登录, 但是实现⽅法是⽐较麻烦的 • 需要修改每个接⼝的处理逻辑 • 需要修改每个接⼝的返回结果 • 接⼝定义修改, 前端代码也需要跟着修改 有没有更简单的办法, 统⼀拦截所有的请求,…

NLP Word Embeddings

Word representation One-hot形式 在上一周介绍RNN类模型时&#xff0c;使用了One-hot向量来表示单词的方式。它的缺点是将每个单词视为独立的&#xff0c;算法很难学习到单词之间的关系。 比如下面的例子&#xff0c;即使语言模型已经知道orange juice是常用组合词&#xf…