使用 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 进行图像深度学习