[转载]Pytorch中nn.Linear module的理解

[转载]Pytorch中nn.Linear module的理解

本文转载并援引全文纯粹是为了构建和分类自己的知识,方便自己未来的查找,没啥其他意思。

这个模块要实现的公式是:y=xAT+*b

来源:https://blog.csdn.net/u012936765/article/details/52671156

Linear 是module的子类,是参数化module的一种,与其名称一样,表示着一种线性变换。

创建

这里写图片描述

parent 的init函数

这里写图片描述

Linear的创建需要两个参数,inputSize 和 outputSize
inputSize:输入节点数
outputSize:输出节点数
所以Linear 有7个字段:

weight : Tensor , outputSize ×× inputSize
bias: Tensor ,outputSize
gradWeight: Tensor , outputSize ×× inputSize
gradBias: Tensor ,outputSize
gradInput: Tensor
output: Tensor
_type: output:type()
例子
module = nn.Linear(10, 5)
1
Forward Pass

这里写图片描述

————————————————
版权声明:本文为CSDN博主「bubbleoooooo」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u012936765/article/details/52671156

这篇文章有一个很好的例子:

import torch

x = torch.randn(128, 20)  # 输入的维度是(128,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)
print('m.weight.shape:
 ', m.weight.shape)
print('m.bias.shape:
', m.bias.shape)
print('output.shape:
', output.shape)

# ans = torch.mm(input,torch.t(m.weight))+m.bias 等价于下面的
ans = torch.mm(x, m.weight.t()) + m.bias   
print('ans.shape:
', ans.shape)

print(torch.equal(ans, output))

输出是:

m.weight.shape:
  torch.Size([30, 20])
m.bias.shape:
 torch.Size([30])
output.shape:
 torch.Size([128, 30])
ans.shape:
 torch.Size([128, 30])
True

注意它输入的是一个128*20的二维tensor,经过一个线性变换后变成了128*30的.如果输入换成了:

x = torch.randn(20, 128)  # 输入的维度是(20,128)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)

就会报错了。因为公式是y=xAT+b。由上面的输出我们可以看到,A的维度是3020,转置之后是20*30,所以应该和X的列数对应。一般的:linear的输入和输出值的都是列数,把输入换成:

x = torch.randn(20, 20)  # 输入的维度是(20,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)

输出之后就会发现,改变的依然是列数。

原文地址:https://www.cnblogs.com/jiading/p/11945346.html