Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyTorch: How to get the shape of a Tensor as a list of int

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?

like image 387
patapouf_ai Avatar asked Oct 19 '17 08:10

patapouf_ai


People also ask

How do you get the shape of a tensor in PyTorch?

To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch.

How do you find the shape of a tensor?

Tensor. get_shape method: this shape is inferred from the operations that were used to create the tensor, and may be partially complete. If the static shape is not fully defined, the dynamic shape of a Tensor t can be determined by evaluating tf. shape(t) .

How do you make a tensor list?

To convert a Python list to a tensor, we are going to use the tf. convert_to_tensor() function and this function will help the user to convert the given object into a tensor. In this example, the object can be a Python list and by using the function will return a tensor.

What is Item () PyTorch?

item() moves the data to CPU. It converts the value into a plain python number. And plain python number can only live on the CPU. So, basically loss is one-element PyTorch tensor in your case, and . item() converts its value to a standard Python number.


1 Answers

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] 
like image 114
alvas Avatar answered Nov 08 '22 20:11

alvas