Pytorch多维 输入

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Pytorch多维 输入

又是花落时   2022-09-29 我要评论

问题: 由于 在输入lstm 层 每个batch 做了根据输入序列最大长度做了padding,导致每个 batch 的 length 不同。 导致输出 长度不同 。如:(batch, length, output_dim): (12,128,10),(12,111,10). 但是输入 linear 层的时候没有出现问题。

网站解释:

官网 pytorch linear:

  • Input:(*, H_{in})(∗,Hin​)where*∗means any number of dimensions including none andH_{in} = \text{in\_features}Hin​=in_features. 任意维度 number 理解有歧义 (a)number. k可以理解三维,四维。。。 (b) 可以理解 为某一维度的数 。
  • Output:(*, H_{out})(∗,Hout​)where all but the last dimension are the same shape as the input andH_{out} = \text{out\_features}Hout​=out_features.

代码解释:

分别 用三维 和二维输入数组,查看他们参数数目是否一样。

import torch
 
x = torch.randn(128, 20)  # 输入的维度是(128,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)
print('m.weight.shape:\n ', m.weight.shape)
print('m.bias.shape:\n', m.bias.shape)
print('output.shape:\n', output.shape)
 
# ans = torch.mm(input,torch.t(m.weight))+m.bias 等价于下面的
ans = torch.mm(x, m.weight.t()) + m.bias   
print('ans.shape:\n', ans.shape)
 
print(torch.equal(ans, output))

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
x = torch.randn(128, 30,20)  # 输入的维度是(128,30,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)
print('m.weight.shape:\n ', m.weight.shape)
print('m.bias.shape:\n', m.bias.shape)
print('output.shape:\n', output.shape)
ouput:
m.weight.shape:
  torch.Size([30, 20])
m.bias.shape:
 torch.Size([30])
output.shape:
 torch.Size([128, 30, 30])

结果:

(128,30,20),和 (128,20) 分别是如 nn.linear(30,20) 层。

weight.shape 均为: (30,20)

linear() 参数数目只和 input_dim ,output_dim 有关。

weight 在源码的定义, 没找到如何计算多维input的代码。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们