【问题标题】:How to calculate (N,*, input) matrix class (output, input) matrix(the result is (N,*,output)) by pytorch?如何通过pytorch计算(N,*,输入)矩阵类(输出,输入)矩阵(结果为(N,*,输出))?
【发布时间】:2021-09-14 02:48:57
【问题描述】:

我想重写 nn.Linear 所做的事情。问题是输入大小是(N,*,in_feature),权重大小是(out_feature,in_feature)。如果我希望结果是 (N,*,out_feature) 使用 python,我应该如何编写代码?

input @ weight.T 

不正确,很遗憾。

【问题讨论】:

  • 哦,matmul,我明白了!

标签: python machine-learning deep-learning pytorch


【解决方案1】:

大小需要匹配才能应用@ __matmul__:输入x 的形状为(N, *, in_feature),权重张量w 的形状为(out_feature, in_feature) .

x = torch.rand(2, 4, 4, 10)
w = torch.rand(5, 10)

w 进行转置将得到(in_feature, out_feature) 的形状。在xw.T 之间应用__matmul__ 将缩小为(N, *, out_feature) 的形状:

>>> z = x@w.T
>>> z.shape
torch.Size([2, 4, 4, 5])

或者等效地使用torch.matmul:

>>> z = torch.matmul(x, w.T)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    相关资源
    最近更新 更多