Obtain torch.tensor from string of floats

Viewed 2160

We can convert 1 dimensional array of floats, stored as a space separated numbers in text file, in to a numpy array or a torch tensor as follows.

line = "1 5 3 7 4"
np_array = np.fromstring(line, dtype='int', sep=" ")

np_array
>> array([1, 5, 3, 7, 4])

And to convert above numpy array to a torch tensor, we can do following :

torch_tensor = torch.tensor(np_array)
torch_tensor
>>tensor([1, 5, 3, 7, 4])

How can I convert a string of numbers separated by space in to a torch.Tensor directly without converting them to a numpy array? We can also do this by fist splitting the string at a space, mapping them to int or float, and then feeding it to torch.tensor. But like numpy's fromstring, is there any such method in pytorch?

2 Answers

What about

x = torch.tensor(list(map(float, line.split(' '))), dtype=torch.float32)

PyTorch currently has no analogous function to numpy's fromstring. You can either use the numpy function itself, or by splitting and mapping as you say.

Related