第R4周:LSTM-火災溫度預測

文章目錄

  • 一、前期準備工作
    • 1.導入數據
    • 2. 數據集可視化
  • 二、構建數據集
    • 1. 數據集預處理
    • 2. 設置X, y
    • 3. 劃分數據集
  • 三、模型訓練
    • 1. 構建模型
    • 2. 定義訓練函數
    • 3. 定義測試函數
    • 4. 正式訓練模型
  • 四、模型評估
    • 1. Loss圖片
    • 2. 調用模型進行預測
    • 3. R2值評估
  • 總結:

  • 🍨 本文為🔗365天深度學習訓練營 中的學習記錄博客
  • 🍖 原作者:K同學啊

一、前期準備工作

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

1.導入數據

data = pd.read_csv("woodpine2.csv")data
TimeTem1CO 1Soot 1
00.00025.00.0000000.000000
10.22825.00.0000000.000000
20.45625.00.0000000.000000
30.68525.00.0000000.000000
40.91325.00.0000000.000000
...............
5943366.000295.00.0000770.000496
5944366.000294.00.0000770.000494
5945367.000292.00.0000770.000491
5946367.000291.00.0000760.000489
5947367.000290.00.0000760.000487

5948 rows × 4 columns

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:]dataFrame
Tem1CO 1Soot 1
025.00.0000000.000000
125.00.0000000.000000
225.00.0000000.000000
325.00.0000000.000000
425.00.0000000.000000
............
5943295.00.0000770.000496
5944294.00.0000770.000494
5945292.00.0000770.000491
5946291.00.0000760.000489
5947290.00.0000760.000487

5948 rows × 3 columns

二、構建數據集

1. 數據集預處理

from sklearn.preprocessing import MinMaxScalerdataFrame = 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))dataFrame.shape
(5948, 3)

2. 設置X, y

width_X = 8
width_y = 1##取前8個時間段的Tem1、CO 1、Soot 1為X,第9個時間段的Tem1為y。
X = []
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)X.shape, y.shape
((5939, 8, 3), (5939, 1, 1))

檢查數據集中是否有空值

print(np.any(np.isnan(X)))
print(np.any(np.isnan(y)))
False
False

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)
X_train.shape, y_train.shape
(torch.Size([5000, 8, 3]), torch.Size([5000, 1, 1]))
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)

三、模型訓練

1. 構建模型

class model_lstm(nn.Module):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):out, hidden1 = self.lstm0(x) out, _ = self.lstm1(out, hidden1) out    = self.fc0(out) return out[:, -1:, :]   #取1個預測值,否則經過lstm會得到8*1個預測model = model_lstm()
model
model_lstm((lstm0): LSTM(3, 320, batch_first=True)(lstm1): LSTM(320, 320, batch_first=True)(fc0): Linear(in_features=320, out_features=1, bias=True)
)
model(torch.rand(30,8,3)).shape
torch.Size([30, 1, 1])

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

3. 定義測試函數

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)# 計算lossy_pred = model(x)loss        = loss_fn(y_pred, y)test_loss += loss.item()test_loss /= num_batchesreturn test_loss

4. 正式訓練模型

#設置GPU訓練
device=torch.device("cuda" if torch.cuda.is_available() else "cpu")
device

device(type=‘cpu’)

#訓練模型
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)

learning rate = 0.09990 Epoch: 1, Train_loss:0.00123, Test_loss:0.01228
learning rate = 0.09961 Epoch: 2, Train_loss:0.01404, Test_loss:0.01183
learning rate = 0.09911 Epoch: 3, Train_loss:0.01365, Test_loss:0.01135
learning rate = 0.09843 Epoch: 4, Train_loss:0.01321, Test_loss:0.01085
learning rate = 0.09755 Epoch: 5, Train_loss:0.01270, Test_loss:0.01029
learning rate = 0.09649 Epoch: 6, Train_loss:0.01212, Test_loss:0.00968
learning rate = 0.09524 Epoch: 7, Train_loss:0.01144, Test_loss:0.00901
learning rate = 0.09382 Epoch: 8, Train_loss:0.01065, Test_loss:0.00827
learning rate = 0.09222 Epoch: 9, Train_loss:0.00975, Test_loss:0.00748
learning rate = 0.09045 Epoch:10, Train_loss:0.00876, Test_loss:0.00665
learning rate = 0.08853 Epoch:11, Train_loss:0.00769, Test_loss:0.00580
learning rate = 0.08645 Epoch:12, Train_loss:0.00658, Test_loss:0.00497
learning rate = 0.08423 Epoch:13, Train_loss:0.00548, Test_loss:0.00418
learning rate = 0.08187 Epoch:14, Train_loss:0.00444, Test_loss:0.00346
learning rate = 0.07939 Epoch:15, Train_loss:0.00349, Test_loss:0.00283
learning rate = 0.07679 Epoch:16, Train_loss:0.00268, Test_loss:0.00230
learning rate = 0.07409 Epoch:17, Train_loss:0.00200, Test_loss:0.00188
learning rate = 0.07129 Epoch:18, Train_loss:0.00147, Test_loss:0.00154
learning rate = 0.06841 Epoch:19, Train_loss:0.00107, Test_loss:0.00129
learning rate = 0.06545 Epoch:20, Train_loss:0.00078, Test_loss:0.00110
learning rate = 0.06243 Epoch:21, Train_loss:0.00057, Test_loss:0.00096
learning rate = 0.05937 Epoch:22, Train_loss:0.00042, Test_loss:0.00085
learning rate = 0.05627 Epoch:23, Train_loss:0.00032, Test_loss:0.00078
learning rate = 0.05314 Epoch:24, Train_loss:0.00025, Test_loss:0.00072
learning rate = 0.05000 Epoch:25, Train_loss:0.00021, Test_loss:0.00068
learning rate = 0.04686 Epoch:26, Train_loss:0.00017, Test_loss:0.00065
learning rate = 0.04373 Epoch:27, Train_loss:0.00015, Test_loss:0.00062
learning rate = 0.04063 Epoch:28, Train_loss:0.00014, Test_loss:0.00060
learning rate = 0.03757 Epoch:29, Train_loss:0.00013, Test_loss:0.00059
learning rate = 0.03455 Epoch:30, Train_loss:0.00012, Test_loss:0.00058
learning rate = 0.03159 Epoch:31, Train_loss:0.00012, Test_loss:0.00057
learning rate = 0.02871 Epoch:32, Train_loss:0.00011, Test_loss:0.00056
learning rate = 0.02591 Epoch:33, Train_loss:0.00011, Test_loss:0.00055
learning rate = 0.02321 Epoch:34, Train_loss:0.00011, Test_loss:0.00055
learning rate = 0.02061 Epoch:35, Train_loss:0.00011, Test_loss:0.00055
learning rate = 0.01813 Epoch:36, Train_loss:0.00012, Test_loss:0.00055
learning rate = 0.01577 Epoch:37, Train_loss:0.00012, Test_loss:0.00055
learning rate = 0.01355 Epoch:38, Train_loss:0.00012, Test_loss:0.00056
learning rate = 0.01147 Epoch:39, Train_loss:0.00012, Test_loss:0.00056
learning rate = 0.00955 Epoch:40, Train_loss:0.00013, Test_loss:0.00057
learning rate = 0.00778 Epoch:41, Train_loss:0.00013, Test_loss:0.00058
learning rate = 0.00618 Epoch:42, Train_loss:0.00014, Test_loss:0.00058
learning rate = 0.00476 Epoch:43, Train_loss:0.00014, Test_loss:0.00059
learning rate = 0.00351 Epoch:44, Train_loss:0.00014, Test_loss:0.00059
learning rate = 0.00245 Epoch:45, Train_loss:0.00014, Test_loss:0.00059
learning rate = 0.00157 Epoch:46, Train_loss:0.00014, Test_loss:0.00060
learning rate = 0.00089 Epoch:47, Train_loss:0.00014, Test_loss:0.00060
learning rate = 0.00039 Epoch:48, Train_loss:0.00014, Test_loss:0.00060
learning rate = 0.00010 Epoch:49, Train_loss:0.00014, Test_loss:0.00060
learning rate = 0.00000 Epoch:50, Train_loss:0.00014, Test_loss:0.00060
==================== Done ====================

四、模型評估

1. Loss圖片

import matplotlib.pyplot as plt
from datetime import datetime
current_time = datetime.now() # 獲取當前時間plt.figure(figsize=(5, 3),dpi=120)plt.plot(train_loss    , label='LSTM Training Loss')
plt.plot(test_loss, label='LSTM Validation Loss')plt.title('Training and Validation Loss')
plt.xlabel(current_time) # 打卡請帶上時間戳,否則代碼截圖無效
plt.legend()
plt.show()

在這里插入圖片描述

2. 調用模型進行預測

predicted_y_lstm = sc.inverse_transform(model(X_test).detach().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()

在這里插入圖片描述

3. R2值評估

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)

均方根誤差: 6.92733
R2: 0.83259

總結:

本周主要學習了LSTM模型,并且通過實踐更加深入地了解到了LSTM模型。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/78433.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/78433.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/78433.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

toCharArray作用

toCharArray() 是 Java 中 String 類的一個方法&#xff0c;其作用是將字符串對象轉換為一個字符數組。下面為你詳細介紹其用法、原理和示例。 方法定義 toCharArray() 方法在 java.lang.String 類里被定義&#xff0c;方法簽名如下 public char[] toCharArray() 此方法沒有…

STM32八股【6】-----CortexM3的雙堆棧(MSP、PSP)設計

STM32的線程模式&#xff08;Thread Mode&#xff09;和內核模式&#xff08;Handler Mode&#xff09;以及其對應的權級和堆棧指針 線程模式&#xff1a; 正常代碼執行時的模式&#xff08;如 main 函數、FreeRTOS任務&#xff09; 可以是特權級&#xff08;使用MSP&#xff…

驅動支持的最高CUDA版本與實際安裝的Runtime版本

查看電腦上安裝的CUDA版本的多種方法&#xff0c;適用于不同系統和場景。 方法一&#xff1a;通過命令行工具 1. 查看CUDA Driver API版本&#xff08;顯卡驅動支持的CUDA版本&#xff09; 命令&#xff1a;nvidia-smi操作&#xff1a; 打開終端&#xff08;Windows為CMD/Pow…

Python CT圖像預處理——基于ITK-SNAP

Python CT圖像預處理——nii格式讀取、重采樣、窗寬窗位設置_python讀取nii-CSDN博客 基于原文指出以下幾個問題&#xff1a;文件路徑設置模糊&#xff1b;nilabel里面使用的get_data() 方法已經過時&#xff1b;需要導入scikit-image&#xff0c;還要導入一個matplotlib。 一…

【MQ篇】RabbitMQ之消息持久化!

目錄 一、 交換機持久化 (Exchange Persistence)二、 隊列持久化 (Queue Persistence)三、 消息持久化 (Message Persistence)四、 持久化的“黃金三角” &#x1f531;&#xff1a;三者缺一不可&#xff01;五、 來&#xff0c;完整的代碼示例&#xff08;整合持久化和確認機制…

[AI技術(二)]JSONRPC協議MCPRAGAgent

Agent概述(一) AI技術基礎(一) JSON-RPC 2.0 協議詳解 JSON-RPC 2.0 是一種基于 JSON 的輕量級遠程過程調用(RPC)協議,旨在簡化跨語言、跨平臺的遠程通信。以下從協議特性、核心結構、錯誤處理、批量請求等角度進行詳細解析: 一、協議概述 1. 設計原則 ? 簡單性:…

LeetCode238_除自身以外數組的乘積

LeetCode238_除自身以外數組的乘積 標簽&#xff1a;#數組 #前綴和Ⅰ. 題目Ⅱ. 示例0. 個人方法一&#xff1a;暴力循環嵌套0. 個人方法二&#xff1a;前綴和后綴分別求積 標簽&#xff1a;#數組 #前綴和 Ⅰ. 題目 給你一個整數數組 nums&#xff0c;返回 數組 answer &#…

算法筆記.spfa算法(bellman-ford算法的改進)

題目&#xff1a;&#xff08;來源于AcWing&#xff09; 給定一個 n 個點 m 條邊的有向圖&#xff0c;圖中可能存在重邊和自環&#xff0c; 邊權可能為負數。 請你求出 1 號點到 n 號點的最短距離&#xff0c;如果無法從 1 號點走到 n 號點&#xff0c;則輸出 impossible。 …

07 Python 字符串全解析

文章目錄 一. 字符串的定義二. 字符串的基本用法1. 訪問字符串中的字符2. 字符串切片3. 字符串拼接4. 字符串重復5.字符串比較6.字符串成員運算 三. 字符串的常用方法1. len() 函數2. upper() 和 lower() 方法3. strip() 方法4. replace() 方法5. split() 方法 四. 字符串的進階…

Java集成Zxing和OpenCV實現二維碼生成與識別工具類

Java集成Zxing和OpenCV實現二維碼生成與識別工具類 本文將介紹如何使用Java集成Zxing和OpenCV庫&#xff0c;實現二維碼的生成和識別功能。識別方法支持多種輸入形式&#xff0c;包括File對象、文件路徑和Base64編碼。 一、環境準備 添加Maven依賴 <dependencies><…

【專題刷題】二分查找(二)

&#x1f4dd;前言說明&#xff1a; 本專欄主要記錄本人的基礎算法學習以及LeetCode刷題記錄&#xff0c;按專題劃分每題主要記錄&#xff1a;&#xff08;1&#xff09;本人解法 本人屎山代碼&#xff1b;&#xff08;2&#xff09;優質解法 優質代碼&#xff1b;&#xff…

Java—ThreadLocal底層實現原理

首先&#xff0c;ThreadLocal 本身并不提供存儲數據的功能&#xff0c;當我們操作 ThreadLocal 的時候&#xff0c;實際上操作線程對象的一個名為 threadLocals 成員變量。這個成員變量的類型是 ThreadLocal 的一個內部類 ThreadLocalMap&#xff0c;它是真正用來存儲數據的容器…

Elasticsearch(ES)中的腳本(Script)

文章目錄 一. 腳本是什么&#xff1f;1. lang&#xff08;腳本語言&#xff09;2. source&#xff08;腳本代碼&#xff09;3. params&#xff08;參數&#xff09;4. id&#xff08;存儲腳本的標識符&#xff09;5. stored&#xff08;是否為存儲腳本&#xff09;6. script 的…

客戶聯絡中心能力與客戶匹配方式

在數字化時代&#xff0c;客戶聯絡中心作為企業與客戶溝通的核心樞紐&#xff0c;其服務能力與客戶需求的精準匹配至關重要。隨著客戶期望的不斷提升&#xff0c;傳統的“一刀切”服務模式已難以滿足個性化需求&#xff0c;如何通過智能化的手段實現服務能力與客戶的高效匹配&a…

深入理解網絡原理:UDP協議詳解

在計算機網絡中&#xff0c;數據的傳輸是通過各種協議實現的&#xff0c;其中用戶數據報協議&#xff08;UDP&#xff0c;User Datagram Protocol&#xff09;作為一種重要的傳輸層協議&#xff0c;廣泛應用于實時通信、視頻流、在線游戲等場景。本文將深入探討UDP協議的特性、…

vscode切換Python環境

跑深度學習項目通常需要切換python環境&#xff0c;下面介紹如何在vscode切換python環境&#xff1a; 1.點擊vscode界面左上角 2.在彈出框選擇對應kernel

【MCP Node.js SDK 全棧進階指南】中級篇(4):MCP錯誤處理與日志系統

前言 隨著MCP應用的規模和復雜性增長,錯誤處理與日志系統的重要性也日益凸顯。一個健壯的錯誤處理策略和高效的日志系統不僅可以幫助開發者快速定位和解決問題,還能提高應用的可靠性和可維護性。本文作為中級篇的第四篇,將深入探討MCP TypeScript-SDK中的錯誤處理與日志系統…

【Qt】文件

&#x1f308; 個人主頁&#xff1a;Zfox_ &#x1f525; 系列專欄&#xff1a;Qt 目錄 一&#xff1a;&#x1f525; Qt 文件概述 二&#xff1a;&#x1f525; 輸入輸出設備類 三&#xff1a;&#x1f525; 文件讀寫類 四&#xff1a;&#x1f525; 文件和目錄信息類 五&…

代碼隨想錄算法訓練營第五十八天 | 1.拓撲排序精講 2.dijkstra(樸素版)精講 卡碼網117.網站構建 卡碼網47.參加科學大會

1.拓撲排序精講 題目鏈接&#xff1a;117. 軟件構建 文章講解&#xff1a;代碼隨想錄 思路&#xff1a; 把有向無環圖進行線性排序的算法都可以叫做拓撲排序。 實現拓撲排序的算法有兩種&#xff1a;卡恩算法&#xff08;BFS&#xff09;和DFS&#xff0c;以下BFS的實現思…

Qt實現語言切換的完整方案

在Qt中實現語言動態切換需要以下幾個關鍵步驟&#xff0c;我將提供一個完整的實現方案&#xff1a; 一、準備工作 在代碼中使用tr()標記所有需要翻譯的字符串 cpp button->setText(tr("Submit")); 創建翻譯文件 在.pro文件中添加&#xff1a; qmake TRANSLATION…