小熊飛槳練習冊-05水果資料集
簡介
小熊飛槳練習冊-05水果資料集,本專案開發和測驗均在 Ubuntu 20.04 系統下進行,
專案最新代碼查看主頁:小熊飛槳練習冊
百度飛槳 AI Studio 主頁:小熊飛槳練習冊-05水果資料集
Ubuntu 系統安裝 CUDA 參考:Ubuntu 百度飛槳和 CUDA 的安裝
檔案說明
| 檔案 | 說明 |
|---|---|
| train.py | 訓練程式 |
| test.py | 測驗程式 |
| test-gtk.py | 測驗程式 GTK 界面 |
| report.py | 報表程式 |
| onekey.sh | 一鍵獲取資料到 dataset 目錄下 |
| get-data.sh | 獲取資料到 dataset 目錄下 |
| make-images-labels.py | 生成訓練集影像路徑和標簽的文本檔案 |
| check-data.sh | 檢查 dataset 目錄下的資料是否存在 |
| mod/resnet.py | ResNet 網路模型 |
| mod/dataset.py | ImageClass 影像分類資料集決議 |
| mod/utils.py | 雜項 |
| mod/config.py | 配置 |
| mod/report.py | 結果報表 |
| dataset | 資料集目錄 |
| params | 模型引數保存目錄 |
| log | VisualDL 日志保存目錄 |
資料集
資料集來源于百度飛槳公共資料集:水果資料集
一鍵獲取資料
- 運行腳本,包含以下步驟:獲取資料,生成影像路徑和標簽的文本檔案,檢查資料,
如果運行在本地計算機,下載完資料,檔案放到 dataset 目錄下,在專案目錄下運行下面腳本,
如果運行在百度 AI Studio 環境,查看 data 目錄是否有資料,在專案目錄下運行下面腳本,
bash onekey.sh
獲取資料
如果運行在本地計算機,下載完資料,檔案放到 dataset 目錄下,在專案目錄下運行下面腳本,
如果運行在百度 AI Studio 環境,查看 data 目錄是否有資料,在專案目錄下運行下面腳本,
bash get-data.sh
生成影像路徑和標簽的文本檔案
獲取資料后,在專案目錄下運行下面腳本,生成影像路徑和標簽的文本檔案,包含:
- 訓練集 train-images-labels.txt
- 測驗集 test-images-labels.txt
python3 make-images-labels.py all ./dataset fruits/apple 0 fruits/banana 1 fruits/grape 2 fruits/orange 3 fruits/pear 4
分類標簽
- apple 0
- banana 1
- grape 2
- orange 3
- pear 4
檢查資料
獲取資料完畢后,在專案目錄下運行下面腳本,檢查 dataset 目錄下的資料是否存在,
bash check-data.sh
網路模型
網路模型使用 ResNet 網路模型 來源百度飛槳教程和網路,
ResNet 網路模型 參考: 百度飛槳教程
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
class ResNetBlock(nn.Layer):
"""
ResNetBlock 模塊
"""
def __init__(self, channels, stride=1, sample_stride=2, is_sample=False, is_simple=False):
"""
ResNetBlock 模塊
Args:
channels (list|tuple): 3個, 0輸入通道, 1中間通道, 2輸出通道
stride (int, optional): 模塊步幅,默認 1.
sample_stride (int, optional): 采樣模塊步幅,默認 2
is_sample (bool, optional): 是否采樣模塊,默認 False, 默認 不是采樣模塊
is_simple (bool, optional): 是否簡易模塊,默認 False, 默認 不是簡易模塊
"""
super(ResNetBlock, self).__init__()
self.is_sample = is_sample # 是否采樣模塊
self.is_simple = is_simple # 是否簡易模塊
in_channels = channels[0] # 輸入通道
mid_channels = channels[1] # 中間通道
out_channels = channels[2] # 輸出通道
# 殘差模塊
self.block = nn.Sequential()
if (is_simple):
# 簡易模塊
self.block = nn.Sequential(
nn.Conv2D(in_channels=in_channels, out_channels=mid_channels,
kernel_size=3, stride=stride, padding=1),
nn.BatchNorm(num_channels=mid_channels),
nn.ReLU(),
nn.Conv2D(in_channels=mid_channels, out_channels=out_channels,
kernel_size=3, stride=1, padding=1),
nn.BatchNorm(num_channels=out_channels)
)
else:
# 正常模塊
self.block = nn.Sequential(
nn.Conv2D(in_channels=in_channels, out_channels=mid_channels,
kernel_size=1, stride=1, padding=0),
nn.BatchNorm(num_channels=mid_channels),
nn.ReLU(),
nn.Conv2D(in_channels=mid_channels, out_channels=mid_channels,
kernel_size=3, stride=stride, padding=1),
nn.BatchNorm(num_channels=mid_channels),
nn.ReLU(),
nn.Conv2D(in_channels=mid_channels, out_channels=out_channels,
kernel_size=1, stride=1, padding=0),
nn.BatchNorm(num_channels=out_channels)
)
if (is_sample):
# 采樣模塊
self.sample_block = nn.Sequential(
nn.Conv2D(in_channels=in_channels, out_channels=out_channels,
kernel_size=1, stride=sample_stride, padding=0),
nn.BatchNorm(num_channels=out_channels)
)
def forward(self, x):
residual = x
y = self.block(x)
if (self.is_sample):
residual = self.sample_block(x)
x = paddle.add(x=residual, y=y)
x = F.relu(x)
return x
class ResNet(nn.Layer):
"""
ResNet 網路模型
輸入影像大小為 224 x 224
"""
def __init__(self, blocks, num_classes=10, is_simple=False):
"""
ResNet 網路模型
Args:
blocks (list|tuple): 每模塊數量
num_classes (int, optional): 分類數量, 默認 10
is_simple (bool, optional): 是否簡易模塊,默認 False, 默認 不是簡易模塊
Raises:
Exception: 分類數量 num_classes < 2
"""
super(ResNet, self).__init__()
if num_classes < 2:
raise Exception(
"分類數量 num_classes 必須大于等于 2: {}".format(num_classes))
self.num_classes = num_classes # 分類數量
self.is_simple = is_simple # 是否簡易模塊
# 簡易模塊通道, [0輸入通道, 1中間通道, 2輸出通道]
self.simple_channels = [[64, 64, 128],
[128, 128, 256],
[256, 256, 512],
[512, 512, 512]]
# 正常模塊通道, [0輸入通道, 1中間通道, 2輸出通道]
self.base_channels = [[64, 64, 256],
[256, 128, 512],
[512, 256, 1024],
[1024, 512, 2048]]
# 輸入模塊
self.in_block = nn.Sequential(
nn.Conv2D(in_channels=3, out_channels=64,
kernel_size=7, stride=2, padding=3),
nn.BatchNorm(num_channels=64),
nn.ReLU(),
nn.MaxPool2D(kernel_size=3, stride=2, padding=1)
)
# 處理模塊
self.block = self.make_blocks(blocks)
# 輸出模塊
self.avg_pool = nn.AvgPool2D(kernel_size=7, stride=1)
self.features = 512 if is_simple else 2048
self.fc = nn.Linear(self.features, num_classes)
def forward(self, x):
x = self.in_block(x)
x = self.block(x)
x = self.avg_pool(x)
# flatten 根據給定的 start_axis 和 stop_axis 將連續的維度展平
x = paddle.flatten(x, start_axis=1, stop_axis=-1)
x = self.fc(x)
return x
def make_blocks(self, blocks):
"""
生成所有模塊
Args:
blocks (list|tuple): 每模塊數量
Returns:
paddle.nn.Sequential : 所有模塊順序連接
"""
seq = []
is_in_block = True
for block_index in range(len(blocks)):
is_first_block = True
for i in range(blocks[block_index]):
seq.append(self.make_one_block(block_index=block_index,
is_in_block=is_in_block, is_first_block=is_first_block))
is_first_block = False
is_in_block = False
return nn.Sequential(*seq)
def make_one_block(self, block_index: int, is_in_block: bool, is_first_block: bool):
"""
生成一個模塊
Args:
block_index (int): 模塊索引
is_in_block (bool): 是否殘差輸入模塊
is_first_block (bool): 是否第一模塊
Returns:
ResNetBlock: 殘差模塊
"""
net = None
stride = 1
sample_stride = 2
if is_in_block:
stride = 1 if is_first_block else 1
sample_stride = 1 if is_first_block else 2
else:
stride = 2 if is_first_block else 1
sample_stride = 2
channels1 = self.simple_channels[block_index] if self.is_simple else self.base_channels[block_index]
if is_first_block:
net = ResNetBlock(channels=channels1, stride=stride, sample_stride=sample_stride,
is_sample=is_first_block, is_simple=self.is_simple)
else:
channels2 = [channels1[2], channels1[1], channels1[2]]
net = ResNetBlock(channels=channels2, stride=stride, sample_stride=sample_stride,
is_sample=is_first_block, is_simple=self.is_simple)
return net
def get_resnet(num_classes: int, resnet=50):
"""
獲取 ResNet 網路模型
Args:
num_classes (int, optional): 分類數量
resnet (int, optional): ResNet模型選項, 默認 50, 可選 18, 34, 50, 101, 152
Returns:
ResNet: ResNet 網路模型
"""
if resnet not in [18, 34, 50, 101, 152]:
raise Exception(
"resnet 可選 18, 34, 50, 101, 152, 實際: {}".format(resnet))
net = None
if resnet == 18:
net = ResNet([2, 2, 2, 2], num_classes, is_simple=True)
elif resnet == 34:
net = ResNet([3, 4, 6, 3], num_classes, is_simple=True)
elif resnet == 50:
net = ResNet([3, 4, 6, 3], num_classes, is_simple=False)
elif resnet == 101:
net = ResNet([3, 4, 23, 3], num_classes, is_simple=False)
elif resnet == 152:
net = ResNet([3, 8, 36, 3], num_classes, is_simple=False)
return net
資料集決議
資料集決議,主要是決議 影像路徑和標簽的文本 ,然后根據影像路徑讀取影像和標簽,
import paddle
import os
import random
import numpy as np
from PIL import Image
import paddle.vision as ppvs
class ImageClass(paddle.io.Dataset):
"""
ImageClass 影像分類資料集決議, 繼承 paddle.io.Dataset 類
"""
def __init__(self,
dataset_path: str,
images_labels_txt_path: str,
transform=None,
shuffle=True
):
"""
建構式,定義資料集
Args:
dataset_path (str): 資料集路徑
images_labels_txt_path (str): 影像和標簽的文本路徑
transform (Compose, optional): 轉換資料的操作組合, 默認 None
shuffle (bool, True): 隨機打亂資料, 默認 True
"""
super(ImageClass, self).__init__()
self.dataset_path = dataset_path
self.images_labels_txt_path = images_labels_txt_path
self._check_path(dataset_path, "資料集路徑錯誤")
self._check_path(images_labels_txt_path, "影像和標簽的文本路徑錯誤")
self.transform = transform
self.image_paths, self.labels = self.parse_dataset(
dataset_path, images_labels_txt_path, shuffle)
def __getitem__(self, idx):
"""
獲取單個資料和標簽
Args:
idx (Any): 索引
Returns:
image (float32): 影像
label (int): 標簽
"""
image_path, label = self.image_paths[idx], self.labels[idx]
return self.get_item(image_path, label, self.transform)
@staticmethod
def get_item(image_path: str, label: int, transform=None):
"""
獲取單個資料和標簽
Args:
image_path (str): 影像路徑
label (int): 標簽
transform (Compose, optional): 轉換資料的操作組合, 默認 None
Returns:
image (float32): 影像
label (int): 標簽
"""
if not os.path.exists(image_path):
raise Exception("{}: {}".format("影像路徑錯誤", image_path))
ppvs.set_image_backend("pil")
# 統一轉為 3 通道, png 是 4通道
image = Image.open(image_path).convert("RGB")
if transform is not None:
image = transform(image)
# 轉換影像 HWC 轉為 CHW
# image = np.transpose(image, (2, 0, 1))
return image.astype("float32"), label
def __len__(self):
"""
資料數量
Returns:
int: 資料數量
"""
return len(self.labels)
def _check_path(self, path: str, msg: str):
"""
檢查路徑是否存在
Args:
path (str): 路徑
msg (str, optional): 例外訊息
Raises:
Exception: 路徑錯誤, 例外
"""
if not os.path.exists(path):
raise Exception("{}: {}".format(msg, path))
@staticmethod
def parse_dataset(dataset_path: str, images_labels_txt_path: str, shuffle: bool):
"""
資料集決議
Args:
dataset_path (str): 資料集路徑
images_labels_txt_path (str): 影像和標簽的文本路徑
Returns:
image_paths: 影像路徑集
labels: 分類標簽集
"""
lines = []
image_paths = []
labels = []
with open(images_labels_txt_path, "r") as f:
lines = f.readlines()
# 隨機打亂資料
if (shuffle):
random.shuffle(lines)
for i in lines:
data = https://www.cnblogs.com/cnhemiya/archive/2022/05/08/i.split(" ")
if (len(data) < 2):
raise Exception("資料集決議錯誤,資料少于 2")
image_paths.append(os.path.join(dataset_path, data[0]))
labels.append(int(data[1]))
return image_paths, labels
配置模塊
可以查看修改 mod/config.py 檔案,有詳細的說明
開始訓練
運行 train.py 檔案,查看命令列引數加 -h
python3 train.py
--cpu 是否使用 cpu 計算,默認使用 CUDA
--learning-rate 學習率,默認 0.001
--epochs 訓練幾輪,默認 2 輪
--batch-size 一批次數量,默認 2
--num-workers 執行緒數量,默認 2
--no-save 是否保存模型引數,默認保存, 選擇后不保存模型引數
--load-dir 讀取模型引數,讀取 params 目錄下的子檔案夾, 默認不讀取
--log 是否輸出 VisualDL 日志,默認不輸出
--summary 輸出網路模型資訊,默認不輸出,選擇后只輸出資訊,不會開啟訓練
測驗模型
運行 test.py 檔案,查看命令列引數加 -h
python3 test.py
--cpu 是否使用 cpu 計算,默認使用 CUDA
--batch-size 一批次數量,默認 2
--num-workers 執行緒數量,默認 2
--load-dir 讀取模型引數,讀取 params 目錄下的子檔案夾, 默認 best 目錄
測驗模型 GTK 界面
運行 test-gtk.py 檔案,此程式依賴 GTK 庫,只能運行在本地計算機,
python3 test-gtk.py
GTK 庫安裝
python3 -m pip install pygobject
使用手冊
- 1、點擊 選擇模型 按鈕,
- 2、彈出的檔案對話框選擇模型,模型在 params 目錄下的子目錄的 model.pdparams 檔案,
- 3、點擊 隨機測驗 按鈕,就可以看到測驗的影像,預測結果和實際結果,
查看結果報表
運行 report.py 檔案,可以顯示 params 目錄下所有子目錄的 report.json,
加引數 --best 根據 loss 最小的模型引數保存在 best 子目錄下,
python3 report.py
report.json 說明
| 鍵名 | 說明 |
|---|---|
| id | 根據時間生成的字串 ID |
| loss | 本次訓練的 loss 值 |
| acc | 本次訓練的 acc 值 |
| epochs | 本次訓練的 epochs 值 |
| batch_size | 本次訓練的 batch_size 值 |
| learning_rate | 本次訓練的 learning_rate 值 |
VisualDL 可視化分析工具
- 安裝和使用說明參考:VisualDL
- 訓練的時候加上引數 --log
- 如果是 AI Studio 環境訓練的把 log 目錄下載下來,解壓縮后放到本地專案目錄下 log 目錄
- 在專案目錄下運行下面命令
- 然后根據提示的網址,打開瀏覽器訪問提示的網址即可
visualdl --logdir ./log
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/470650.html
標籤:其他
下一篇:java反序列化-URLDNS鏈
