【Pytorch神经网络实战案例】03 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-测试方法
生活随笔
收集整理的這篇文章主要介紹了
【Pytorch神经网络实战案例】03 CIFAR-10数据集:Pytorch使用GPU训练CNN模版-测试方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import torch
import torchvision
from PIL import Image
from 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=torchvision.transforms.Compose([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] instead
image=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模版-测试方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机视觉概述:视觉任务+场景领域+发展
- 下一篇: pandas处理日期的几种常用方法