神经网络工具箱nn的使用

it2026-10-03  1

数据包

from PIL import Image from torchvision.transforms import ToTensor,ToPILImage import matplotlib.pyplot as plt import torch as t from torch import nn from torch.autograd import Variable as V

全连接层

'''全连接层''' class Linear(nn.Module): #继承nn.Module '''构造函数''' def __init__(self,in_features,out_features): nn.Module.__init__(self) self.w=nn.Parameter(t.randn(in_features,out_features)) self.b=nn.Parameter(t.randn(out_features)) '''前向传播''' def forward(self,x): x=x.mm(self.w) return x+self.b.expand_as(x)

图像的卷积锐化

'''打开图像''' to_tensor=ToTensor() to_pil=ToPILImage() img=Image.open('D:/杨狗/test.jpg') '''绘制图像''' #plt.imshow(img) '''这是为了操作方便,将整个图像增加一个维度,图像本来是三维的(长宽与通道),现在成了四维了''' input=to_tensor(img).unsqueeze(0) #print(input.shape) #锐化卷积核,大小3*3,且有3通道, kernel=t.ones(3,3,3)/-9. kernel[0][1][1]=1 kernel[1][1][1]=1 kernel[2][1][1]=1 conv=nn.Conv2d(1,1,(3,3),1,bias=False) #参数:输入通道数(因为新增了一个维度,所以是1),输出通道数(同理),卷积核大小,步长,是否有偏移量 conv.weight.data=kernel.view(1,3,3,3) #与图像对应,本来是3*3*3的卷积核,由于增加了维度,调整为1*3*3*3 out=conv(V(input)) '''去掉增加的维度''' img_out=to_pil(out.data.squeeze(0)) '''绘制图像''' plt.imshow(img_out)

池化层

pool=nn.AvgPool2d(10,10) out=pool(V(input)) img_out=to_pil(out.data.squeeze(0)) plt.imshow(img_out)

 

最新回复(0)