iis服务器助手广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Pytorch linear 多维输入的参数问题
  • 257
分享到

Pytorch linear 多维输入的参数问题

2024-04-02 19:04:59 257人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

问题: 由于 在输入lstm 层 每个batch 做了根据输入序列最大长度做了padding,导致每个 batch 的 length 不同。 导致输出 长度不同 。如:(batch,

问题: 由于 在输入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的代码。

到此这篇关于Pytorch linear 多维 输入的参数的文章就介绍到这了,更多相关Pytorch多维 输入内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Pytorch linear 多维输入的参数问题

本文链接: https://www.lsjlt.com/news/120137.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作