การจำแนกภาพด้วย ResNet
สร้างโมเดลจาก ResNet18 ที่ผ่านการเทรนมาแล้วเรียบร้อย ถึงเวลาทดสอบกับภาพตัวอย่างกันแล้ว
จะนำ preprocessing transforms มาใช้กับภาพและจำแนกประเภทของภาพ โดยต้องใช้ layer softmax() ตามด้วย argmax() เนื่องจาก ResNet18 ได้รับการเทรนบนชุดข้อมูลแบบ multi-class
ภาพที่เลือกใช้สำหรับทดสอบการพยากรณ์มีดังนี้:

บันทึก preprocessing transform ไว้ในตัวแปร preprocess และโหลดภาพ PIL ไว้ในตัวแปร img
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Deep Learning สำหรับภาพด้วย PyTorch
คำแนะนำการฝึกหัด
- นำ preprocessing transforms มาใช้กับภาพ แล้ว reshape โดยใช้
.unsqueeze(0)เพื่อเพิ่ม batch dimension - ส่งภาพผ่านโมเดล จากนั้น reshape ผลลัพธ์ด้วย
.squeeze(0)เพื่อลบ batch dimension แล้วเพิ่ม layersoftmax() - ใช้
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)