DAY 51 復習日

作業:day43的時候我們安排大家對自己找的數據集用簡單cnn訓練,現在可以嘗試下借助這幾天的知識來實現精度的進一步提高

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os# 設置隨機種子確保結果可復現
torch.manual_seed(42)
np.random.seed(42)# --- MODIFICATION 1: 更改為你的數據集路徑 ---
# 將 'path/to/your_dataset' 替換為你的數據集所在的根目錄
# Using a placeholder path. Please update this to your actual dataset path.
data_dir = r'/data/wangjinjun/learn/data/10 Big Cats of the Wild - Image Classification'
train_dir = os.path.join(data_dir, 'train')
test_dir = os.path.join(data_dir, 'test')# 檢查路徑是否存在
if not os.path.isdir(data_dir):print(f"Warning: Dataset directory not found at '{data_dir}'. "f"Please update the 'data_dir' variable to your dataset's path. "f"The script will fail if the path is not correct.")# Create dummy directories to allow the script to run without FileNotFoundError# You should replace this with your actual data.os.makedirs(train_dir, exist_ok=True)os.makedirs(test_dir, exist_ok=True)# Create dummy class folders and imagesfor d in [train_dir, test_dir]:for c in ['AFRICAN LEOPARD', 'TIGER']: # Example classesos.makedirs(os.path.join(d, c), exist_ok=True)Image.new('RGB', (100, 100)).save(os.path.join(d, c, 'dummy.jpg'))# --- MODIFICATION 2: 使用ImageFolder加載自定義數據集 ---
# 定義數據預處理步驟
transform = transforms.Compose([transforms.Resize((32, 32)),transforms.ToTensor(),transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])# 加載訓練集和測試集
trainset = torchvision.datasets.ImageFolder(root=train_dir, transform=transform)
testset = torchvision.datasets.ImageFolder(root=test_dir, transform=transform)# 從訓練數據集中自動獲取類別名稱和數量
classes = trainset.classes
num_classes = len(classes)
print(f"從數據集中找到 {num_classes} 個類別: {classes}")# 創建數據加載器
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2)# --- NEW: CBAM (Convolutional Block Attention Module) 實現 ---
class ChannelAttention(nn.Module):def __init__(self, in_planes, ratio=16):super(ChannelAttention, self).__init__()self.avg_pool = nn.AdaptiveAvgPool2d(1)self.max_pool = nn.AdaptiveMaxPool2d(1)self.fc = nn.Sequential(nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False),nn.ReLU(),nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False))self.sigmoid = nn.Sigmoid()def forward(self, x):avg_out = self.fc(self.avg_pool(x))max_out = self.fc(self.max_pool(x))out = avg_out + max_outreturn self.sigmoid(out)class SpatialAttention(nn.Module):def __init__(self, kernel_size=7):super(SpatialAttention, self).__init__()assert kernel_size in (3, 7), 'kernel size must be 3 or 7'padding = 3 if kernel_size == 7 else 1self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)self.sigmoid = nn.Sigmoid()def forward(self, x):avg_out = torch.mean(x, dim=1, keepdim=True)max_out, _ = torch.max(x, dim=1, keepdim=True)x = torch.cat([avg_out, max_out], dim=1)x = self.conv1(x)return self.sigmoid(x)class CBAM(nn.Module):def __init__(self, in_planes, ratio=16, kernel_size=7):super(CBAM, self).__init__()self.ca = ChannelAttention(in_planes, ratio)self.sa = SpatialAttention(kernel_size)def forward(self, x):x = self.ca(x) * xx = self.sa(x) * xreturn x# --- MODIFICATION 3: 動態調整CNN模型以適應你的數據集并集成CBAM ---
class SimpleCNN_CBAM(nn.Module):def __init__(self, num_classes):super(SimpleCNN_CBAM, self).__init__()self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)self.cbam1 = CBAM(32)self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)self.cbam2 = CBAM(64)self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)self.cbam3 = CBAM(128)self.pool = nn.MaxPool2d(2, 2)# 輸入特征數128 * 4 * 4取決于輸入圖像大小和網絡結構。# 由于我們將所有圖像調整為32x32,經過3次2x2的池化后,尺寸變為 32 -> 16 -> 8 -> 4。所以這里是4*4。self.fc1 = nn.Linear(128 * 4 * 4, 512)# **重要**: 輸出層的大小現在由num_classes決定self.fc2 = nn.Linear(512, num_classes)def forward(self, x):x = F.relu(self.conv1(x))x = self.cbam1(x)x = self.pool(x)x = F.relu(self.conv2(x))x = self.cbam2(x)x = self.pool(x)x = F.relu(self.conv3(x))x = self.cbam3(x)x = self.pool(x)x = x.view(-1, 128 * 4 * 4)x = F.relu(self.fc1(x))x = self.fc2(x)return x# 初始化模型,傳入你的數據集的類別數量
model = SimpleCNN_CBAM(num_classes=num_classes)
print("帶有CBAM模塊的模型已創建")# 如果有GPU則使用GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)# 訓練模型函數 (現在使用傳入的trainloader)
def train_model(model, trainloader, epochs=5):criterion = nn.CrossEntropyLoss()optimizer = torch.optim.Adam(model.parameters(), lr=0.001)print("開始訓練...")for epoch in range(epochs):running_loss = 0.0for i, data in enumerate(trainloader, 0):inputs, labels = datainputs, labels = inputs.to(device), labels.to(device)optimizer.zero_grad()outputs = model(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()running_loss += loss.item()if i % 100 == 99:print(f'[{epoch + 1}, {i + 1:5d}] 損失: {running_loss / 100:.3f}')running_loss = 0.0print("訓練完成")# 定義模型保存路徑
model_save_path = 'my_custom_cnn_cbam.pth'# 嘗試加載預訓練模型
try:model.load_state_dict(torch.load(model_save_path, map_location=device))print(f"已從 '{model_save_path}' 加載預訓練模型")
except FileNotFoundError:print("無法加載預訓練模型,將開始訓練新模型。")train_model(model, trainloader, epochs=5) # 訓練新模型torch.save(model.state_dict(), model_save_path) # 保存訓練好的模型print(f"新模型已訓練并保存至 '{model_save_path}'")# 設置模型為評估模式
model.eval()# Grad-CAM實現 (這部分無需修改)
class GradCAM:def __init__(self, model, target_layer):self.model = modelself.target_layer = target_layerself.gradients = Noneself.activations = Noneself.register_hooks()def register_hooks(self):def forward_hook(module, input, output):self.activations = output.detach()def backward_hook(module, grad_input, grad_output):self.gradients = grad_output[0].detach()self.target_layer.register_forward_hook(forward_hook)self.target_layer.register_backward_hook(backward_hook)def generate_cam(self, input_image, target_class=None):model_output = self.model(input_image)if target_class is None:target_class = torch.argmax(model_output, dim=1).item()self.model.zero_grad()one_hot = torch.zeros_like(model_output)one_hot[0, target_class] = 1model_output.backward(gradient=one_hot, retain_graph=True)gradients = self.gradientsactivations = self.activationsweights = torch.mean(gradients, dim=(2, 3), keepdim=True)cam = torch.sum(weights * activations, dim=1, keepdim=True)cam = F.relu(cam)cam = F.interpolate(cam, size=(32, 32), mode='bilinear', align_corners=False)cam = cam - cam.min()cam = cam / cam.max() if cam.max() > 0 else camreturn cam.cpu().squeeze().numpy(), target_class# --- 示例:對測試集中的一張圖片使用Grad-CAM ---
# 初始化Grad-CAM,目標層是最后一個卷積層
# 注意:我們將 Grad-CAM 目標層更改為 self.cbam3,以可視化注意力模塊后的特征圖
grad_cam = GradCAM(model, model.cbam3)# 從測試集中獲取一張圖片
if len(testset) > 0:img, label = testset[0]img_tensor = img.unsqueeze(0).to(device)# 生成CAMcam, predicted_class_idx = grad_cam.generate_cam(img_tensor)# 可視化結果def visualize_cam(img, cam, predicted_class, true_class):img = img.cpu().permute(1, 2, 0).numpy() # 轉換回 (H, W, C)# 反歸一化以便顯示img = img * 0.5 + 0.5img = np.clip(img, 0, 1)heatmap = plt.cm.jet(cam)heatmap = heatmap[:, :, :3] # 去掉alpha通道overlay = heatmap * 0.4 + img * 0.6plt.figure(figsize=(10, 5))plt.subplot(1, 3, 1)plt.imshow(img)plt.title(f'Original Image\nTrue: {true_class}')plt.axis('off')plt.subplot(1, 3, 2)plt.imshow(heatmap)plt.title('Grad-CAM Heatmap')plt.axis('off')plt.subplot(1, 3, 3)plt.imshow(overlay)plt.title(f'Overlay\nPredicted: {predicted_class}')plt.axis('off')plt.show()# 顯示結果predicted_class_name = classes[predicted_class_idx]true_class_name = classes[label]visualize_cam(img, cam, predicted_class_name, true_class_name)
else:print("Test set is empty. Cannot perform visualization.")

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

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

相關文章

針對網絡爬蟲的相關法律法規整理

在中國,網絡爬蟲的法律法規涉及多個層面,包括個人信息保護、數據安全、網絡安全、知識產權、反不正當競爭等。以下是詳細的法律法規分析及合規指南: 1. 核心法律法規及適用場景? ??(1)《民法典》——隱私權與個人信…

1.1_5_2 計算機網絡的性能指標(下)

繼續來看計算機網絡的性能指標,接下來我們探討時延,時延帶寬積和往返時延,以及信道利用率這幾個性能指標。 首先來看時延這個性能指標,英文叫delay,也有的教材,把它翻譯為延遲。所謂的時延,就是…

PP-OCRv2:超輕OCR系統的萬能包

PP-OCRv2:超輕OCR系統的萬能包摘要光學字符識別(OCR)系統已廣泛應用于多種場景,但設計兼顧精度與效率的OCR系統仍具挑戰性。我們此前提出的超輕量OCR系統PP-OCR在平衡兩者方面取得進展。本文進一步提出PP-OCRv2,通過五…

常見的軟件版本開源協議

開源軟件許可證核心指南 一、許可證基礎分類 1. 寬松型許可證(Permissive) 核心特征:允許閉源衍生,僅保留版權聲明適用場景:商業集成、快速開發代表協議: 📜 MIT 📜 Apache 2.0 &…

基于FPGA的一維序列三次樣條插值算法verilog實現,包含testbench

目錄 1.前言 2.算法運行效果圖預覽 3.算法運行軟件版本 4.部分核心程序 5.算法仿真參數 6.算法理論概述 7.參考文獻 8.算法完整程序工程 1.前言 三次樣條插值是一種在數據擬合和信號處理中廣泛應用的技術,它通過構造分段三次多項式來逼近給定的離散數據點&a…

RAG 之 Prompt 動態選擇的三種方式

“如果我有5個prompt模板,我想只選擇一個每次都自動五選一能做到嗎怎么做?” 完全可以做到。這在復雜的RAG或Agentic工作流中是一個非常普遍且關鍵的需求,通常被稱為“條件路由(Conditional Routing)”或“動態調度&am…

【ROS2 自動駕駛學習】02-安裝ROS2及其配套工具

目錄 一、設置語言環境 二、添加存儲庫 三、添加軟件源 四、安裝ROS2 五、配置環境 六、測試ROS2 七、安裝一些工具 7.1 terminator 7.2 colcon工具 7.3 tf工具 7.4 joint-state-publisher工具 7.5 urdf 八、安裝三方庫 8.1 Eigen 8.2 yaml-cpp 8.3 matplotl…

系統學習Python——并發模型和異步編程:基礎知識

分類目錄:《系統學習Python》總目錄 并行是并發的一種特殊情況。**所有并行系統都是并發的,但不是所有并發系統都是并行的。**在21世紀初,我們可以使用單核設備在GNU Linux上同時處理100個進程。一臺擁有4個CPU核的現代筆記本計算機&#xff…

睿爾曼系列機器人——以創新驅動未來,重塑智能協作新生態(下)

在智能制造與人工智能深度融合的當下,機器人技術正經歷從 “功能替代” 到 “價值共創” 的深刻躍遷。睿爾曼,作為全球超輕量仿人機械臂領域的先行者,始終秉持 “讓機器人觸手可及” 的使命,憑借底層技術的突破性進展,…

表征工程(Representation Engineering, RepE)

表征工程(Representation Engineering, RepE) 近年來,表征工程(Representation Engineering, RepE)在提升AI系統透明度和可控性方面取得了顯著進展。 一、大模型可解釋性與可控性的突破 核心論文:《Representation Engineering: A Top-Down Approach to AI Transparen…

國產ARM+FPGA工業開發平臺——GM-3568JHF

一、引言 隨著物聯網和國產替代需求的快速發展,嵌入式系統面臨計算性能與硬件靈活性的雙重挑戰。GM-3568JHF開發板基于國產“ARMFPGA”異構架構,結合瑞芯微RK3568J處理器與紫光同創Logos-2 FPGA芯片,支持國產自主操作系統,滿足通…

RISCV Linux 虛擬內存精講系列一 Sv39

筆者認為,Linux 操作系統(Operating System)最核心的機制是虛擬內存(Virtual Memory)。因為,操作系統主要作用是將硬件環境抽象起來,給在其中運行的應用(Applications)提…

【apply from: “$flutterRoot/packages/flutter_tools/gradle/flutter.gradle“作用】

這行代碼的作用是將 Flutter 的 Gradle 構建腳本集成到 Android 項目中,具體細節如下:作用解析:引入 Flutter 構建邏輯 flutter.gradle 是 Flutter SDK 的核心構建腳本,它負責: 編譯 Dart 代碼為原生二進制文件&#x…

深入理解JavaScript設計模式之命令模式

深入理解JavaScript設計模式之命令模式 文章目錄深入理解JavaScript設計模式之命令模式定義簡單命令模式組合命令模式使用命令模式實現文本編輯器目標關鍵類說明實現的效果交互邏輯流程所有代碼:總結定義 命令模式也是設計模式種相對于變焦簡單容易理解的一種設計模…

CSS 網頁布局:從基礎到進階

CSS 網頁布局:從基礎到進階 引言 隨著互聯網的飛速發展,網頁設計已經成為了一個不可或缺的領域。CSS(層疊樣式表)作為網頁設計中的關鍵工具,用于控制網頁元素的樣式和布局。本文將為您全面解析CSS網頁布局,…

【人工智能】大語言模型(LLM) NLP

大語言模型(LLM)& NLP1.大語言模型(LLM)1.1 一句話解釋1.2 更形象的比喻1.3 為什么叫 “大” 模型1.4 它能做什么1.5 現實中的例子2.對比 NLP2.1 用 “汽車進化” 比喻 NLP → LLM2.2 為什么說 LLM 屬于 NLP2.3 LLM 的 “革命…

Unity HDRP + Azure IoT 的 Python 后端實現與集成方案

Unity HDRP Azure IoT 的 Python 后端實現與集成方案 雖然Unity HDRP本身使用C#開發,但我們可以構建Python后端服務支持物聯網系統,并與Unity引擎深度集成。以下是完整的實現方案: 系統架構 #mermaid-svg-qCDb0g9Ik287Cg8X {font-family:&qu…

小黑黑日常積累大模型prompt句式2:【以段落的形式輸出,不分點列舉】【如果沒有相關內容則不輸出】【可讀性強】【輸出格式規范】

以段落的形式輸出,不分點列舉 每個標題下直接接續段落內容,不編號、不分點。......標題下直接接續段落內容,不繼續進行分點列舉。如果沒有相關內容則不輸出 若某一部分無法從原文中提取有效信息,則跳過該部分內容,不做…

React Native 基礎組件詳解<一>

一、Text組件 1)numberOfLines:顯示行數 2)ellipsizeMode:超出隱藏的位置 clip->裁掉 head/middle/ tail->點的位置 3)selectable: 是否可以選中 4)selectionColor:選中后的顏色 5&#…

異步編程(Promise/Generator/async)

1、Promise 2、Generator 3、async/await