您的位置:首页 > 房产 > 家装 > 网络模型应用实例

网络模型应用实例

2024/10/5 20:26:36 来源:https://blog.csdn.net/qq_58739767/article/details/142032022  浏览:    关键词:网络模型应用实例

import torch
import torchvision
from PIL import Image
from torch import nn

image_path = "D:/test pytorch/images/dog.png"
# 读取图片
image = Image.open(image_path)
image = image.convert('RGB')
# png格式的图片是4通道类型,RGB只有三通道,所以调用image = image.convert('RGB')保留其颜色通道。若本来就是三通道,加上这一步也可以。均适用
print(image)

# 网络要求32*32,但是图片显示201*176,对其resize
transform = torchvision.transforms.Compose([torchvision.transforms.Resize((32,32)),
                                            torchvision.transforms.ToTensor()])
image = transform(image)
print(image.shape)

 # 加载网络模型
class SUN(nn.Module):
    def __init__(self):
        super(SUN, self).__init__()
        self.model = 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(1024, 64),
            nn.Linear(64, 10)
        )

    def forward(self, x):
        x =self.model(x)
        return x
model = torch.load("sun_0.path")

# 实验结果可看,预测结果不准确,实验结果预测是第二个,但实际在模型中,是第五个类别才是狗,原因是,训练次数的不足
# model = torch.load("sun_29.path")
# 报错显示,在GPU上运行的,使用在CPU上,需要加语句;
# model = torch.load("sun_29.path",map_location = torch.device('cpu'))
print(model)

# 报错:Given groups=1, weight of size [32, 3, 5, 5], expected input[1, 4, 32, 32] to have 3 channels, but got 4 channels instead
image = torch.reshape(image,(1,3,32,32))
# 当模型出现dropout或者batchnormal下述2条就需要下述两条语句
model.eval()
with torch.no_grad():
    output = model(image)
output = model(image)
print(output)
print(output.argmax(1))

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com