iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0
Software Development

LSTM結合Yolo v8對於多隻斑馬魚行為分析系列 第 22

day 22 yolo結合lstm去評斷空氣品質系統

  • 分享至 

  • xImage
  •  

今天是第二十二天我們可以寫一空氣品質系統結合了lstm與yolo以下是程式碼

import cv2
import numpy as np
import torch
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# YOLOv8 模型加載 (假設使用 YOLOv8)
model = torch.hub.load('ultralytics/yolov8', 'yolov8x')  # 使用 YOLOv8

def detect_pollution_sources(image_path):
    img = cv2.imread(image_path)
    results = model(img)  # 執行 YOLO 檢測
    return results.pandas().xyxy[0]  # 返回檢測結果

def preprocess_data(pollution_data, time_series_data):
    # 假設 pollution_data 是一個 DataFrame,其中包含 YOLO 檢測到的污染源數據
    pollution_features = pollution_data[['class', 'confidence']].groupby('class').count()  # 簡單示例
    pollution_features = pollution_features.values.flatten()

    # 處理時間序列數據
    time_series_data = time_series_data[['PM2.5', 'PM10', 'CO2']]
    time_series_data = time_series_data.values

    # 合併 YOLO 特徵與時間序列數據
    combined_data = np.hstack([time_series_data, pollution_features])
    
    return combined_data

def build_lstm_model(input_shape):
    model = Sequential()
    model.add(LSTM(50, return_sequences=True, input_shape=input_shape))
    model.add(LSTM(50))
    model.add(Dense(1))  # 預測未來的空氣質量
    model.compile(optimizer='adam', loss='mse')
    return model

def train_model(model, train_data, train_labels):
    model.fit(train_data, train_labels, epochs=10, batch_size=32)
    return model

# 模擬影像 YOLO 檢測
image_path = 'city_image.jpg'
pollution_data = detect_pollution_sources(image_path)

# 模擬時間序列數據
time_series_data = pd.read_csv('air_quality_data.csv')

# 數據預處理
combined_data = preprocess_data(pollution_data, time_series_data)

# 準備 LSTM 模型輸入
train_data = combined_data[:-1]
train_labels = combined_data[1:, 0]  # 假設我們預測 PM2.5 濃度
train_data = train_data.reshape((train_data.shape[0], 1, train_data.shape[1]))

# 構建並訓練 LSTM 模型
input_shape = (train_data.shape[1], train_data.shape[2])
lstm_model = build_lstm_model(input_shape)
lstm_model = train_model(lstm_model, train_data, train_labels)

# 使用 LSTM 模型進行預測
predictions = lstm_model.predict(train_data)
print("未來空氣質量預測:", predictions)

1. 載入 YOLO 模型

import cv2
import numpy as np
import torch
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# YOLOv8 模型加載 (假設使用 YOLOv8)
model = torch.hub.load('ultralytics/yolov8', 'yolov8x')  # 使用 YOLOv8

這部分代碼引入了一些所需的庫,包括 cv2(OpenCV,用於影像處理),numpy(用於數學運算),torch(PyTorch,用於深度學習模型),pandas(用於處理資料框),以及 tensorflow(用於構建 LSTM 模型)。接著,它透過 PyTorch 的 torch.hub 介面來加載 YOLOv8 模型,這個模型可以用來在影像中檢測物體。

2. YOLO 檢測功能

def detect_pollution_sources(image_path):
    img = cv2.imread(image_path)
    results = model(img)  # 執行 YOLO 檢測
    return results.pandas().xyxy[0]  # 返回檢測結果

這個函數 detect_pollution_sources 負責使用 YOLO 模型來檢測影像中的污染源:

  • image_path:影像檔案的路徑。
  • cv2.imread:讀取影像。
  • model(img):用 YOLO 模型對影像進行物體檢測。
  • results.pandas().xyxy[0]:將 YOLO 檢測結果轉換為 Pandas DataFrame,方便後續處理。

3. 數據預處理

def preprocess_data(pollution_data, time_series_data):
    # 假設 pollution_data 是一個 DataFrame,其中包含 YOLO 檢測到的污染源數據
    pollution_features = pollution_data[['class', 'confidence']].groupby('class').count()  # 簡單示例
    pollution_features = pollution_features.values.flatten()

    # 處理時間序列數據
    time_series_data = time_series_data[['PM2.5', 'PM10', 'CO2']]
    time_series_data = time_series_data.values

    # 合併 YOLO 特徵與時間序列數據
    combined_data = np.hstack([time_series_data, pollution_features])
    
    return combined_data

這個函數 preprocess_data 負責將 YOLO 檢測結果與時間序列數據結合在一起,形成 LSTM 模型的輸入:

  • pollution_data:來自 YOLO 的檢測數據(包括污染源的類別和信心值)。
  • groupby('class').count():根據檢測到的類別對污染源數據進行分組和計數,這是一個簡單的特徵提取方法。
  • time_series_data[['PM2.5', 'PM10', 'CO2']]:提取時間序列數據中的空氣質量指標,如 PM2.5、PM10 和 CO2。
  • np.hstack([time_series_data, pollution_features]):將 YOLO 提取的特徵和時間序列數據合併在一起。

4. 構建 LSTM 模型

def build_lstm_model(input_shape):
    model = Sequential()
    model.add(LSTM(50, return_sequences=True, input_shape=input_shape))
    model.add(LSTM(50))
    model.add(Dense(1))  # 預測未來的空氣質量
    model.compile(optimizer='adam', loss='mse')
    return model

這個函數 build_lstm_model 創建了一個用於預測未來空氣質量的 LSTM 模型:

  • Sequential():初始化一個序列模型。
  • LSTM(50, return_sequences=True):添加第一層 LSTM 層,具有 50 個記憶單元,並返回序列(允許堆疊多層 LSTM)。
  • LSTM(50):第二層 LSTM 層。
  • Dense(1):全連接層,用於最終的預測輸出(這裡預測一個數值)。
  • compile(optimizer='adam', loss='mse'):編譯模型,使用 Adam 優化器和均方誤差損失函數。

5. 模型訓練

def train_model(model, train_data, train_labels):
    model.fit(train_data, train_labels, epochs=10, batch_size=32)
    return model

這個函數 train_model 負責訓練 LSTM 模型:

  • model.fit(train_data, train_labels, epochs=10, batch_size=32):使用給定的訓練數據和標籤進行模型訓練,設定訓練的迭代次數(epochs=10)和每批次處理的樣本數量(batch_size=32)。

6. 主程式

# 模擬影像 YOLO 檢測
image_path = 'city_image.jpg'
pollution_data = detect_pollution_sources(image_path)

# 模擬時間序列數據
time_series_data = pd.read_csv('air_quality_data.csv')

# 數據預處理
combined_data = preprocess_data(pollution_data, time_series_data)

# 準備 LSTM 模型輸入
train_data = combined_data[:-1]
train_labels = combined_data[1:, 0]  # 假設我們預測 PM2.5 濃度
train_data = train_data.reshape((train_data.shape[0], 1, train_data.shape[1]))

# 構建並訓練 LSTM 模型
input_shape = (train_data.shape[1], train_data.shape[2])
lstm_model = build_lstm_model(input_shape)
lstm_model = train_model(lstm_model, train_data, train_labels)

# 使用 LSTM 模型進行預測
predictions = lstm_model.predict(train_data)
print("未來空氣質量預測:", predictions)

這部分代碼是程式的主流程,將 YOLO 和 LSTM 結合起來:

  1. YOLO 檢測:對影像 city_image.jpg 進行 YOLO 檢測,得到污染源數據 pollution_data
  2. 時間序列數據讀取:從 CSV 檔案中讀取空氣質量的時間序列數據。
  3. 數據預處理:將 YOLO 檢測結果與時間序列數據結合起來,形成 combined_data
  4. LSTM 模型輸入準備:將 combined_data 轉換為 LSTM 模型的輸入格式。train_data 是模型的輸入數據,train_labels 是對應的目標數據(如未來 PM2.5 濃度)。
  5. 構建並訓練 LSTM 模型:根據輸入數據的形狀構建 LSTM 模型,並使用訓練數據進行訓練。
  6. 模型預測:使用訓練好的 LSTM 模型進行未來空氣質量的預測,並輸出結果。

這個系統可以根據城市影像中的污染源,結合歷史空氣質量數據,來預測未來的空氣質量趨勢。


上一篇
day 21lstm預測晶圓良率結合yolo淘汰不良的晶圓
下一篇
day 23 lstm結合yolo分析人類情感推薦景點系統
系列文
LSTM結合Yolo v8對於多隻斑馬魚行為分析29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言