直接调用torch.nn 定义含有参数的自定义层
class MyDense(nn.Module):
def __init__(self,**kwargs):
super(MyDense,self).__init__(**kwargs)
self.params = nn.ParameterList([nn.Parameter(torch.randn(4,4)) for i in range(3)])
self.params.append(nn.Parameter(torch.randn(4,1)))
def forward(self,x):
for i in range(len(self.params)):
x = torch.mm(x,self.params[i])
return x
net = MyDense()
print(net)
上面的方法使用ParameterList函数,还能使用ParameterDict函数
class MyDictDense(nn.Module):
def __init__(self,**kwargs):
super(MyDictDense,self).__init__(**kwargs)
self.params = nn.ParameterDict({
'linear1':nn.Parameter(torch.randn(4,4)),
'linear2':nn.Parameter(torch.randn(4,2)),
'linear3':nn.Parameter(torch.randn(4,1))
})
def forward(self,x,choice ='linear1'):
return torch.mm(x,self.params[choice])
net = MyDictDense()
print(net)
上面的函数可以用来检测每一层的输出
net(x,choice='linear2')
tensor([[-0.2905, -1.0128],
[-0.6450, 0.2643],
[ 1.7937, 0.4945],
[-0.0725, -0.2533]], grad_fn=<MmBackward>)
平滑层
class FlattenLayer(nn.Module): #平滑层
def __init__(self):
super(FlattenLayer, self).__init__()
def forward(self, x): # x shape: (batch, *, *, ...)
return x.view(x.shape[0], -1)
线性层
class LinearNet(nn.Module): ##继承nn.module类
def __init__(self, n_feature):
super(LinearNet, self).__init__()
self.linear = nn.Linear(n_feature, 1)
def forward(self, x):
y = self.linear(x)
return y
net = LinearNet(num_inputs)
print(net) # 使用print可以打印出网络的结构
2019年11月15日更
卷积层
import torch
from torch import nn
def corr2d(X, K): # 用于二维卷积函数
h, w = K.shape
Y = torch.zeros((X.shape[0] - h + 1, X.shape[1] - w + 1))
for i in range(Y.shape[0]):
for j in range(Y.shape[1]):
Y[i, j] = (X[i: i + h, j: j + w] * K).sum()
return Y
class Conv2D(nn.Module):
def __init__(self, kernel_size):
super(Conv2D, self).__init__()
self.weight = nn.Parameter(torch.randn(kernel_size))
self.bias = nn.Parameter(torch.randn(1))
def forward(self, x):
return corr2d(x, self.weight) + self.bias


https://cuijiahua.com/blog/2018/01/dl_3.html
这篇文章详细讲解了LetNet-5
关于通道数量
以RGB图像为例。
一个12*12的像素图,对其进行5*5的卷积,最后得到一个8*8的像素图。
RGB图像有3个通道(12123),所以卷积核也要有3个通道(553),对像素图进行卷积后得到的结果是881而不是883的图像。最后像素图的深度(输出图像的信道数)取决于卷积核的个数。

如果要得到8*8*256的结果,应该这样做:用256个5*5*3的卷积核来卷12*12*3的像素图。最后得到的结果进行堆叠就是8*8*256的图像。(256个5*5*3的卷积核可以想象成它的输入信道数为3,而输出信道数为256,表示为5×5×3×256两者互不影响。)
网友评论