PyTorch:如何将张量的形状作为 int 列表 [英] PyTorch: How to get the shape of a Tensor as a list of int
本文介绍了PyTorch:如何将张量的形状作为 int 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 numpy 中,V.shape
给出了 V 维的整数元组.
在 tensorflow 中 V.get_shape().as_list()
给出了 V 维度的整数列表.
在 pytorch 中,V.size()
给出了一个大小对象,但我如何将其转换为整数?
解决方案
对于 PyTorch v1.0 及可能更高版本:
<预><代码>>>>进口火炬>>>var = torch.tensor([[1,0], [0,1]])# 使用 .size 函数,返回一个 torch.Size 对象.>>>变量大小()torch.Size([2, 2])>>>类型(var.size())<class 'torch.Size'># 同样,使用 .shape>>>变量形状torch.Size([2, 2])>>>类型(var.shape)<class 'torch.Size'>您可以将任何 torch.Size 对象转换为原生 Python 列表:
<预><代码>>>>列表(var.size())[2, 2]>>>类型(列表(var.size()))<类'列表'><小时>
在 PyTorch v0.3 和 0.4 中:
简单的list(var.size())
,例如:
In numpy, V.shape
gives a tuple of ints of dimensions of V.
In tensorflow V.get_shape().as_list()
gives a list of integers of the dimensions of V.
In pytorch, V.size()
gives a size object, but how do I convert it to ints?
解决方案
For PyTorch v1.0 and possibly above:
>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])
# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>
# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>
You can cast any torch.Size object to a native Python list:
>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>
In PyTorch v0.3 and 0.4:
Simply list(var.size())
, e.g.:
>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))
>>> var
Variable containing:
1 0
0 1
[torch.IntTensor of size 2x2]
>>> var.size()
torch.Size([2, 2])
>>> list(var.size())
[2, 2]
这篇关于PyTorch:如何将张量的形状作为 int 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文