图像相关层
import torch as t
from torch import nn
from PIL import Image
from torch.autograd import Variable as V
from torchvision.transforms import ToTensor, ToPILImage
to_tensor=ToTensor() #img->tensor
to_pil=ToPILImage()
lena=Image.open('lena.jpg')
#lena.show()
#输入是一个batch,batch_size=1
input=to_tensor(lena).unsqueeze(0)
#锐化卷积核
kernel=t.ones(3,3)/-9
kernel[1][1]=1
conv=nn.Conv2d(1,1,(3,3),1,bias=False)
conv.weight.data=kernel.view(1,1,3,3)
out=conv(V(input))
#to_pil(out.data.squeeze(0)).show()
#池化层:特殊的卷积层
pool=nn.AvgPool2d(2,2)
out=pool(V(input))
#to_pil(out.data.squeeze(0)).show()
#输入batch_size=2,维度3
input=V(t.randn(2,3))
linear=nn.Linear(3,4)
h=linear(input)
print(h)
#4 channel,初始化标准差为4,均值为0
bn=nn.BatchNorm1d(4)
bn.weight.data=t.zeros(4)
bn_out=bn(h)
#注意输出的均值和方差
#方差是标准差的平方,计算无偏方差分母会减1
#使用unbiased=False,分母不减1
print(bn_out.mean(0),bn_out.var(0,unbiased=False))
#每个元素以0.5的概率合并
dropout=nn.Dropout(0.5)
o=dropout(bn_out)
print(o) #有一半左右的数变为0
#激活函数:ReLU(x)=max(0