文章目录
torch.nn 接口的了解
torch.nn是专门为神经网络设计的模块化接口。nn构建于autograd之上,可以用来定义和运行神经网络。
nn.Module是nn中十分重要的类,包含网络各层的定义及forward方法。
定义自已的网络:
def init(self):
需要继承nn.Module类,并实现forward方法。super(model,self).init
一般把网络中具有可学习参数的层放在构造函数__init__()中,
不具有可学习参数的层(如ReLU)可放在构造函数中,也可不放在构造函数中(而在forward中使用nn.functional来代替)
只要在nn.Module的子类中定义了forward函数,backward函数就会被自动实现(利用Autograd)。
在forward函数中可以使用任何Variable支持的函数,毕竟在整个pytorch构建的图中,是Variable在流动。还可以使用
if,for,print,log等python语法.
注:Pytorch基于nn.Module构建的模型中,只支持mini-batch的Variable输入方式,
比如,只有一张输入图片,也需要变成 N x C x H x W 的形式:
input_image = torch.FloatTensor(1, 28, 28)
input_image = Variable(input_image)
input_image = input_image.unsqueeze(0) # 1 x 1 x 28 x 28
torch.nn.functional包的内置函数
Convolution 函数
Pooling函数
非线性激活函数
Pytorch内的非线性激活函数多达十九种,主要是 relu,softmax,sigmoid,tanh及其相关变形。
非线性激活函数 | 函数表达式 | 适用场景 |
---|---|---|
threshold(input, threshold, value) | 图像灰度处理 | |
relu(input) | ||
hardtanh(input, min_val=-1.0, max_val=1.0) | ||
relu6(input) | ||
elu(input, alpha=1.0) | ||
leaky_relu(input, negative_slope=0.01) | ||
prelu(input, weight) | ||
rrelu(input, lower=0.125, upper=0.33, training=False) | ||
logsigmoid(input) | ||
hardshrink(input, lambd=0.5) | ||
tanhshrink(input) | ||
softsign(input) | ||
softplus(input, beta=1, threshold=20) | ||
softmin(input) | ||
softmax(input) | ||
softshrink(input, lambd=0.5) | ||
tanh(input) | ||
sigmoid(input) |
这里绘制出sigmoid,tanh,softmax,relu的函数图像
Normalization函数
线性函数
Dropout函数
距离函数
损失函数
vision functions
torch.nn包的内置函数
loss function
- torch.nn.BCEWithLogitsLoss()
封装好的对数似然损失函数