相关文章
Pytorch学习笔记(一):torch.cat()模块的详解
Pytorch学习笔记(二):nn.Conv2d()函数详解
Pytorch学习笔记(三):nn.BatchNorm2d()函数详解
Pytorch学习笔记(四):nn.MaxPool2d()函数详解
Pytorch学习笔记(五):nn.AdaptiveAvgPool2d()函数详解
Pytorch学习笔记(六):view()和nn.Linear()函数详解
Pytorch学习笔记(七):F.softmax()和F.log_softmax函数详解
1.函数语法格式和作用
(view)作用:
目的是将多维的的数据如(none,36,2,2)平铺为一维如(none,144)。作用类似于keras中的Flatten函数。只不过keras中是和卷积一起写的,而pytorch是在forward中才声明的。 相当于reshape
(view)函数语言格式:
view(out.size(0), -1)-------(none,36,2,2)平铺为一维如(none,144)
或者
view(-1, 1, 28, 28)-------torch.Size([96, 784])变为torch.Size([96, 1, 28, 28])
(nn.Linear)作用:
作为全连接层(fc),可固定输出通道数。
(nn.Linear)函数语言格式:
nn.Linear(in_features, out_features, bias=True)
2.参数解释
-
in_features指的是输入的二维张量的大小,即输入的[batch_size, size]中的size。
-
out_features指的是输出的二维张量的大小,即输出的二维张量的形状为[batch_size,output_size],当然,它也代表了该全连接层的神经元个数。
-
bias默认为True,可以学到额外的偏置
-
从输入输出的张量的shape角度来理解,相当于一个输入为[batch_size, in_features]的张量变换成了[batch_size, out_features]的输出张量。
3.具体代码
import torch
m = torch.nn.Linear(2, 3)
input = torch.randn(4, 2)
out = m(input)
print(m.weight.shape)
print(m.bias.shape)
print(out.size())
结果如下: