失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 【Pytorch神经网络实战案例】03 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-测试方法

【Pytorch神经网络实战案例】03 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-测试方法

时间:2022-01-03 00:37:03

相关推荐

【Pytorch神经网络实战案例】03 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-测试方法

import torchimport torchvisionfrom PIL import Imagefrom torch import nnimage_path="./test_img/dog.png"image=Image.open(image_path)print(image) #size=406x479 所以需要转换# png格式是四个通道,除了RGB三通道外,还有一个透明度通道。# 所以,我们调用image=image.convert(RGB)保留其颜色通道。# 当然,如果图片本来就是三个颜色通道,经过此操作,不变。# 加上这一步后可以适应png、jpg各种格式的图片。image=image.convert('RGB')transform=pose([torchvision.transforms.Resize((32,32)),torchvision.transforms.ToTensor()])image=transform(image)image=image.cuda()print(image.shape)# 搭建神经网络class Tudui(nn.Module):def __init__(self):super(Tudui, self).__init__()self.model = nn.Sequential(# Conv2d中##in_channels:输入的通道数目 【必选】##out_channels: 输出的通道数目 【必选】##kernel_size:卷积核的大小,类型为int 或者元组,当卷积是方形的时候,只需要一个整数边长即可,卷积不是方形,要输入一个元组表示 高和宽。【必选】##stride: 卷积每次滑动的步长为多少,默认是 1 【可选】##padding(手动计算):设置在所有边界增加值为0的边距的大小(也就是在feature map 外围增加几圈 0 ),## 例如当 padding =1 的时候,如果原来大小为 3 × 3 ,那么之后的大小为 5 × 5 。即在外围加了一圈 0 。【可选】##dilation:控制卷积核之间的间距【可选】nn.Conv2d(3, 32, 5, 1, 2),# MaxPool2d中:# #kernel_size(int or tuple) - max pooling的窗口大小,# # stride(int or tuple, optional) - max pooling的窗口移动的步长。默认值是kernel_size# # padding(int or tuple, optional) - 输入的每一条边补充0的层数# # dilation(int or tuple, optional) – 一个控制窗口中元素步幅的参数# # return_indices - 如果等于True,会返回输出最大值的序号,对于上采样操作会有帮助# # ceil_mode - 如果等于True,计算输出信号大小的时候,会使用向上取整,代替默认的向下取整的操作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()是用于设置网络中的全连接层的,在二维图像处理的任务中,全连接层的输入与输出一般都设置为二维张量,形状通常为[batch_size, size]# 相当于一个输入为[batch_size, in_features]的张量变换成了[batch_size, out_features]的输出张量。nn.Linear(64*4*4, 64),nn.Linear(64, 10))def forward(self, x):x = self.model(x)return x# 加载网络模型model=torch.load("tudui_0.pth", map_location=torch.device("cuda"))# model=torch.load("tudui_0.pth", map_location=torch.device("cpu"))# Expected 4-dimensional input for 4-dimensional weight [32, 3, 5, 5],# but got 3-dimensional input of size [3, 32, 32] insteadimage=torch.reshape(image,(1,3,32,32))model.eval()with torch.no_grad():#提升性能output=model(image)print(output)print(output.argmax(1))

如果觉得《【Pytorch神经网络实战案例】03 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-测试方法》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。