使用 PyTorch 進行影像深度學習
Michal Oleszak
Machine Learning Engineer
從零開始訓練模型:
預訓練模型-已在某任務上訓練好的模型
善用預訓練模型的步驟:
torchvision 模型torch.save().pt 或 .pth.state_dict() 儲存權重torch.save(model.state_dict(), "BinaryCNN.pth")
建立新模型實例
new_model = BinaryCNN()
載入已儲存的參數
new_model.load_state_dict(torch.load('BinaryCNN.pth'))
from torchvision.models import ( resnet18, ResNet18_Weights )weights = ResNet18_Weights.DEFAULTmodel = resnet18(weights=weights)transforms = weights.transforms()
resnet 架構與權重from PIL import Image image = Image.open("cat013.jpg")image_tensor = transform(image)image_reshaped = image_tensors.unsqueeze(0)

model.eval()with torch.no_grad():pred = model(image_reshaped).squeeze(0)pred_cls = pred.softmax(0)cls_id = pred_cls.argmax().item()cls_name = weights.meta["categories"][cls_id]print(cls_name)
Egyptian cat
使用 PyTorch 進行影像深度學習