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