简体   繁体   English

从浮点数字符串中获取torch.tensor

[英]Obtain torch.tensor from string of floats

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.我们可以将一维浮点数数组(以空格分隔的数字存储在文本文件中)转换为 numpy 数组或 Torch 张量,如下所示。

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:要将上述 numpy 数组转换为火炬张量,我们可以执行以下操作:

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?如何将一串由空格分隔的数字直接转换为torch.Tensor而不将它们转换为numpy数组? 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 .我们也可以通过在空格处拆分字符串,将它们映射到 int 或 float,然后将其提供给torch.tensor来做到这一点。 But like numpy 's fromstring , is there any such method in pytorch?但是像numpy的 fromstring 一样, fromstring有没有这样的方法?

What about关于什么

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

PyTorch currently has no analogous function to numpy's fromstring . PyTorch 目前没有与 numpy 的 fromstring 类似的fromstring You can either use the numpy function itself, or by splitting and mapping as you say.您可以使用 numpy function 本身,也可以按照您所说的拆分和映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM