对应文件资源
此文章记录如何对一个他人已经训练好的神经网络进行测试或使用
该项目包含一些表现优异的关于计算机视觉的神经网络架构
from torchvision import models
dir(models)
首字母大写的是许多流行模型的python类
首字母小写的是便捷函数
创建一个AlexNet实例(不过暂时还不需要用这个实例因为这个实例没有训练,我们需要的是一个训练好的网络,如下文的resnet101)
from torchvision import models
alexnet=models.AlexNet()
from torchvision import models
from torchvision import transforms
from PIL import Image
import torch
alexnet=models.AlexNet()
# 导入alexnet实例
resnet=models.resnet101(pretrained=True)
# 实例化一个具有101层的卷积神经网络,指示函数下载训练好的权重
preprocess=transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485,0.456,0.406],
std=[0.229,0.224,0.225]
)])
# 定义一个预处理函数,缩放到256*256个像素,围绕中心裁剪为224*224个像素
# 并将其转化成一个张量,对其RGB分量进行归一化处理
img=Image.open("img/bobby.jpg")
# 加载图片
#img.show()
img_t=preprocess(img)
# 运用定义好的预处理函数对图像进行预处理
batch_t=torch.unsqueeze(img_t,0)
# 将img_t增加一个维度并设置维数为1
resnet.eval()
# 将网络设置为eval模式
out=resnet(batch_t)
with open("files/imagenet_classes.txt") as f:
labels=[line.strip() for line in f.readlines()]
# 加载标签文件
_,index=torch.max(out,1)
# 获取最大值的索引
percentage=torch.nn.functional.softmax(out,dim=1)[0]*100
# 将out归一化到[0,1]之间再到化成百分制
_,indices=torch.sort(out,descending=True)
# 降序排列并提供原始数组的索引值
print([(labels[idx],percentage[idx].item()) for idx in indices[0][:5]])
# 输出分数最高的前5个答案
这个程序展示利用对抗神经网络(GAN)将一个马转换成斑马的过程,当然参数都是训练好的
from distutils.errors import PreprocessError
import torch
import torch.nn as nn
class ResNetBlock(nn.Module): # <1>
def __init__(self, dim):
super(ResNetBlock, self).__init__()
self.conv_block = self.build_conv_block(dim)
def build_conv_block(self, dim):
conv_block = []
conv_block += [nn.ReflectionPad2d(1)]
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=0, bias=True),
nn.InstanceNorm2d(dim),
nn.ReLU(True)]
conv_block += [nn.ReflectionPad2d(1)]
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=0, bias=True),
nn.InstanceNorm2d(dim)]
return nn.Sequential(*conv_block)
def forward(self, x):
out = x + self.conv_block(x) # <2>
return out
class ResNetGenerator(nn.Module):
def __init__(self, input_nc=3, output_nc=3, ngf=64, n_blocks=9): # <3>
assert(n_blocks >= 0)
super(ResNetGenerator, self).__init__()
self.input_nc = input_nc
self.output_nc = output_nc
self.ngf = ngf
model = [nn.ReflectionPad2d(3),
nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=True),
nn.InstanceNorm2d(ngf),
nn.ReLU(True)]
n_downsampling = 2
for i in range(n_downsampling):
mult = 2**i
model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,
stride=2, padding=1, bias=True),
nn.InstanceNorm2d(ngf * mult * 2),
nn.ReLU(True)]
mult = 2**n_downsampling
for i in range(n_blocks):
model += [ResNetBlock(ngf * mult)]
for i in range(n_downsampling):
mult = 2**(n_downsampling - i)
model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
kernel_size=3, stride=2,
padding=1, output_padding=1,
bias=True),
nn.InstanceNorm2d(int(ngf * mult / 2)),
nn.ReLU(True)]
model += [nn.ReflectionPad2d(3)]
model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]
model += [nn.Tanh()]
self.model = nn.Sequential(*model)
def forward(self, input): # <3>
return self.model(input)
# 以上代码为创建一个神经网络,现在暂时不设计具体实现
netG=ResNetGenerator()
# 创建一个神经网络实例
model_path="files/horse2zebra_0.4.0.pth"
model_data=torch.load(model_path)
netG.load_state_dict(model_data)
# 将训练好的权重导入到模型当中
netG.eval()
# 将网络置于eval模式
from PIL import Image
from torchvision import transforms
preprocess=transforms.Compose([transforms.Resize(256),
transforms.ToTensor()])
img=Image.open("img/horse.jpg")
img_t=preprocess(img)
batch_t=torch.unsqueeze(img_t,0)
batch_out=netG(batch_t)
# 以上操作均类似于第一个例子里的操作
out_t=(batch_out.data.squeeze()+1.0)/2.0
out_img=transforms.ToPILImage()(out_t)
out_img.show()
# 将生成好的图片转化成一个可以展现的照片