gpt4 book ai didi

python - PyTorch:如何将张量的形状作为 int 列表

转载 作者:太空狗 更新时间:2023-10-29 19:33:32 25 4
gpt4 key购买 nike

在 numpy 中,V.shape 给出了 V 维度的整数元组。

在 tensorflow V.get_shape().as_list() 中给出了 V 维度的整数列表。

在pytorch中,V.size()给出了一个size对象,但是如何将它转换为ints呢?

最佳答案

对于 PyTorch v1.0 及可能更高版本:

>>> 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'>

您可以将任何 torch.Size 对象转换为原生 Python 列表:

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

在 PyTorch v0.3 和 0.4 中:

简单地 list(var.size()),例如:

>>> 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]

关于python - PyTorch:如何将张量的形状作为 int 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46826218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com