神经网络工具箱nn的使用

数据包

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值