Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting python list to pytorch tensor

Tags:

python

pytorch

I have a problem converting a python list of numbers to pytorch Tensor : this is my code :

caption_feat = [int(x)  if x < 11660  else 3 for x in caption_feat]

printing caption_feat gives : [1, 9903, 7876, 9971, 2770, 2435, 10441, 9370, 2]
I do the converting like this : tmp2 = torch.Tensor(caption_feat) now printing tmp2 gives : tensor([1.0000e+00, 9.9030e+03, 7.8760e+03, 9.9710e+03, 2.7700e+03, 2.4350e+03, 1.0441e+04, 9.3700e+03, 2.0000e+00])
However I expected to get : tensor([1. , 9903, , 9971. ......]) Any Idea?

like image 999
Ameen Ali Avatar asked Feb 06 '20 07:02

Ameen Ali


People also ask

How do I turn a list into a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Is PyTorch tensor faster than numpy?

Tensors in CPU and GPU It is nearly 15 times faster than Numpy for simple matrix multiplication!

How do you convert a list to an array in Python?

To convert a list to array in Python, use the np. array() method. The np. array() is a numpy library function that takes a list as an argument and returns an array containing all the list elements.

How do you make a torch tensor?

There are a few main ways to create a tensor, depending on your use case. To create a tensor with pre-existing data, use torch.tensor() . To create a tensor with specific size, use torch.* tensor creation ops (see Creation Ops).


2 Answers

You can directly convert python list to a pytorch Tensor by defining the dtype. For example,

import torch

a_list = [3,23,53,32,53] 
a_tensor = torch.Tensor(a_list)
print(a_tensor.int())

>>> tensor([3,23,53,32,53])
like image 154
Devanshi Avatar answered Oct 23 '22 07:10

Devanshi


If all elements are integer you can make integer torch tensor by defining dtype

>>> a_list = [1, 9903, 7876, 9971, 2770, 2435, 10441, 9370, 2]
>>> tmp2 = torch.tensor(a_list, dtype=torch.int)
>>> tmp2
tensor([    1,  9903,  7876,  9971,  2770,  2435, 10441,  9370,     2],
       dtype=torch.int32)

While torch.Tensor returns torch.float32 which made it to print number in scientific notation

>>> tmp2 = torch.Tensor(a_list)
>>> tmp2
tensor([1.0000e+00, 9.9030e+03, 7.8760e+03, 9.9710e+03, 2.7700e+03, 2.4350e+03,
        1.0441e+04, 9.3700e+03, 2.0000e+00])
>>> tmp2.dtype
torch.float32
like image 29
Dishin H Goyani Avatar answered Oct 23 '22 08:10

Dishin H Goyani