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?
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.
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) .
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With