nn.Linear()
PyTorch的 nn.Linear() 是用於設置網絡中的全連接層的,需要注意在二維圖像處理的任務中,全連接層的輸入與輸出一般都設置為二維張量,形狀通常為[batch_size, size],不同於卷積層要求輸入輸出是四維張量。其用法與形參說明如下:
torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
即 $y=x A^{T}+b$
Parameters
-
- in_features – size of each input sample
- out_features – size of each output sample
- bias – If set to False, the layer will not learn an additive bias. Default: True
in_features 指的是輸入的二維張量的大小,即輸入的 [batch_size, size] 中的 size 。
out_features 指的是輸出的二維張量的大小,即輸出的二維張量的形狀為 [ batch_size,output_size],當然,它也代表了該全連接層的神經元個數。
從輸入輸出的張量的 shape 角度來理解,相當於一個輸入為 [batch_size, in_features] 的張量變換成了 [batch_size, out_features] 的輸出張量。
Variables
-
- weight :weight.shape = (out_features,in_features)
- bias : bias.shape = (out_features)
Example
x = torch.arange(6).view(-1,2).type(torch.float32) print(x) m = nn.Linear(2,3) print(m) print(m.weight.shape) print(m.bias.shape) print(m(x))
tensor([[0., 1.], [2., 3.], [4., 5.]]) Linear(in_features=2, out_features=3, bias=True) torch.Size([3, 2]) torch.Size([3]) tensor([[-0.0630, 0.8754, 1.0031], [ 1.3898, 2.9152, 1.2959], [ 2.8425, 4.9551, 1.5887]], grad_fn=<AddmmBackward0>)
Example
model = nn.Sequential( nn.Linear(2,3) ) print(model) for param in model.state_dict(): print(param) print(model.state_dict()[param])
Sequential( (0): Linear(in_features=2, out_features=3, bias=True) ) 0.weight tensor([[ 0.1144, 0.2086], [-0.6700, -0.3607], [-0.1835, 0.4866]]) 0.bias tensor([ 0.4158, -0.5482, 0.2358])