← 研究筆記
用一行程式呼叫影像分類模型:執行 timm

用一行程式呼叫影像分類模型:執行 timm

記錄在沒有網路連線的情況下執行 timm 的過程。timm 提供統一的方式使用預訓練影像分類模型。一個具有 2.5 百萬個參數的輕量模型完成了對合成影像的推論。

本文介紹的儲存庫

huggingface/pytorch-image-models

The largest collection of PyTorch image encoders / backbones. Including train, eval, inference, export scripts, and pretrained weights -- ResNet, ResNeXT, EfficientNet, NFNet, Vision Transformer (ViT), MobileNetV4, MobileNet-V3 & V2, RegNet, DPN, CSPNet, Swin Transformer, MaxViT, CoAtNet, ConvNeXt, and more

37k Python Apache License 2.0

測試影像分類模型時,如果每種架構都使用不同的實作方式和權重載入方法,還沒開始比較就得先花時間處理這些差異。timm 是一個程式庫,讓您能透過共用的 API 建立及使用數百個影像分類模型。我安裝了 timm,並測試預訓練模型能否在沒有網路連線的情況下執行推論。

timm 讓您透過共用的 create_model 介面使用多種影像分類架構,包括 ResNet、MobileNet 和 Vision Transformer。此專案以 Apache 2.0 授權條款發布原始碼 (*1)。

1. 安裝 timm 並下載模型

在建置時啟用網路存取,下載輕量模型 mobilenetv3_small_100 的預訓練權重。

FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'torch==2.13.0' 'torchvision==0.28.0' --index-url https://download.pytorch.org/whl/cpu
RUN pip install --no-cache-dir --quiet 'timm==1.0.28'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
podman build -t timm-sandbox .

2. 對合成影像執行推論

我使用了一張簡單的合成影像進行測試。我在同一次執行中產生影像,並在沒有網路連線的情況下將它傳給模型。

import torch
from PIL import Image, ImageDraw
import timm

model = timm.create_model("mobilenetv3_small_100", pretrained=True)
model.eval()

config = timm.data.resolve_data_config({}, model=model)
transform = timm.data.create_transform(**config)

img = Image.new("RGB", (224, 224), color=(90, 160, 230))
draw = ImageDraw.Draw(img)
draw.rectangle((0, 160, 224, 224), fill=(60, 140, 60))
draw.ellipse((150, 20, 200, 70), fill=(250, 210, 60))

input_tensor = transform(img).unsqueeze(0)
with torch.no_grad():
    output = model(input_tensor)
    probs = torch.nn.functional.softmax(output[0], dim=0)

top5_prob, top5_idx = torch.topk(probs, 5)
for prob, idx in zip(top5_prob.tolist(), top5_idx.tolist()):
    print(f"class {idx:4d}  {prob*100:.2f}%")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
  -v "$(pwd)":/work -w /work timm-sandbox \
  python classify_demo.py

-v 選項讓容器能夠讀取及寫入指定的目錄。請在專供實驗使用的空目錄中執行此指令。

執行後得到以下輸出。

parameters: 2,542,856
top-5 ImageNet class indices and probabilities:
  class  722  33.15%
  class  852  9.72%
  class  417  2.36%
  class  714  1.64%
  class  107  1.49%

這個輕量模型約有 2.54 百萬個參數。透過一行程式呼叫共用 API 的 create_model 即可調用模型,而模型在沒有網路存取的情況下完成了推論。輸出包含 ImageNet 的 1,000 個類別的索引編號。您可以使用已發布的對照表,將編號對應到類別名稱。這次實驗將簡單的合成圖形傳給模型,因此並未評估排名靠前的類別在語意上是否合理。

對不同模型使用相同的呼叫慣例

當每種架構都需要各自的載入方法和前處理時,比較模型就需要更多工作。timm 這類共用介面讓您透過相同的 API 處理多個模型。您可以將模型選擇與執行分開。

來源

*1 timm (pytorch-image-models, GitHub), https://github.com/huggingface/pytorch-image-models, Apache 2.0 License