编程基础很弱,需要机器学习,学习记录,按自己理解写的,希望以后能学懂吧,要是有大神看到还请赐教。
完整的模型验证套路
完整的模型验证(测试,demo)套路-利用已经训练好的模型,然后给它提供输入。
import torch
import torchvision.transforms
from PIL import Image
from torch import nn
img_path = "./test/dog.png"
# 读取图片
img = Image.open(img_path)
print(img)
# png图片格式四通道
img = img.convert('RGB')
transform = torchvision.transforms.Compose([
torchvision.transforms.Resize((32, 32)),
torchvision.transforms.ToTensor()
])
img = transform(img)
print(img.shape)
# img= img.reshape(())
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model1 = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 32, 5, 1, 2),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 5, 1, 2),
nn.MaxPool2d(2),
nn.Flatten(),
nn.Linear(64 * 4 * 4, 64),
nn.Linear(64, 10)
)
def forward(self, x):
x = self.model1(x)
return x
model = torch.load("tudui_50.pth")
print(model)
img = torch.reshape(img, (1, 3, 32, 32))
# 将img输入到模型当中
#良好习惯
model.eval()
with torch.no_grad():
output = model(img)
print(output)
print(output.argmax(1))
会发现报错,报错内容如下:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor
原因:
模型是在GPU中训练的,然后这里的代码读取的tensor需要将其放入GPU中进行计算。
解决方法:
将读取的图片放入GPU中,在代码中添加如下:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
img=img.to(device)
最后一P看不懂我裂开了