開始使用免費開始

使用 ResNet 進行影像分類

你已經從預訓練的 ResNet18 建立了模型。現在,該用一張範例影像來測試它了。

你將對影像套用前處理轉換,並進行分類。由於 ResNet18 是在多類別資料集上訓練的,你需要在 softmax() 之後接上 argmax()

你選擇以下影像作為預測測試: A cup of espresso

前處理轉換已儲存為 preprocess。PIL 影像已上傳為 img

本練習屬於課程

使用 PyTorch 進行影像深度學習

檢視課程

練習說明

  • 對影像套用前處理轉換,並使用 .unsqueeze(0) 重新塑形以加入批次維度。
  • 將影像餵入模型,使用 .squeeze(0) 對輸出重新塑形以移除批次維度,並加上 softmax()
  • 使用 argmax() 選出機率最高的類別。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Apply preprocessing transforms
batch = ____.____

# Apply model with softmax layer
prediction = ____.____.____

# Apply argmax
class_id = prediction.____.item()
score = prediction[class_id].item()
category_name = weights.meta["categories"][class_id]
print(category_name)
編輯並執行程式碼