2

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 2

4

What about

x = torch.tensor(list(map(float, line.split(' '))), dtype=torch.float32)
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this is definitely a solution, but, I wanted to know if there is any builtin function in pytorch, like in numpy there is fromstring.
@MikePatel AFAIK the closest function in pytorch you have is from_numpy()
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.