PyTorch的nn.Linear()详解

1. nn.Linear()

  • nn.Linear():用于设置网络中的全连接层,需要注意的是全连接层的输入与输出都是二维张量

  • 一般形状为[batch_size, size],不同于卷积层要求输入输出是四维张量。其用法与形参说明如下:

  • in_features指的是输入的二维张量的大小,即输入的[batch_size, size]中的size。

  • out_features指的是输出的二维张量的大小,即输出的二维张量的形状为[batch_size,output_size],当然,它也代表了该全连接层的神经元个数。

  • 从输入输出的张量的shape角度来理解,相当于一个输入为[batch_size, in_features]的张量变换成了[batch_size, out_features]的输出张量。

用法示例:

import torch as t
from torch import nn
from torch.nn import functional as F

# 假定输入的图像形状为[3,64,64]
x = t.randn(10, 3, 64, 64)      # 10张 3个channel 大小为64x64的图片

x = nn.Conv2d(3, 64, kernel_size=3, stride=3, padding=0)(x)
print(x.shape)


# 之前的特征图尺寸为多少,只要设置为(1,1),那么最终特征图大小都为(1,1) 
# x = F.adaptive_avg_pool2d(x, [1,1])    # [b, 64, h, w] => [b, 64, 1, 1]
# print(x.shape)

# 将四维张量转换为二维张量之后,才能作为全连接层的输入
x = x.view(x.size(0), -1)
print(x.shape)

# in_features由输入张量的形状决定,out_features则决定了输出张量的形状 
connected_layer = nn.Linear(in_features = 64*21*21, out_features = 10)

# 调用全连接层
output = connected_layer(x) 
print(output.shape)
torch.Size([10, 64, 21, 21])
torch.Size([10, 28224])
torch.Size([10, 10])
原文地址:https://www.cnblogs.com/douzujun/p/13366939.html