如何将其中包含 None 的列表转换为 torch.tensor()?

How convert a list with None in it to torch.tensor()?

例如我有一个变量z = [1, 3, None, 5, 6]

我想做:torch.tensor(z)

并得到如下内容:

torch.tensor([1,3, None, 5,6], dtype=torch.float)

但是,这种尝试会引发错误

TypeError: must be real number, not NoneType

有没有办法将此类列表转换为 torch.tensor

我不想将这个 None 值归咎于其他东西。 Numpy 数组能够转换此类列表 np.array([1, 3, None, 5, 6]),但我也不希望来回转换变量。

I have a feeling that the tensor construction from data source doesn't allow the same kind of leniency that Numpy has with allowing None types. Please see also 用于其他人询问张量中 None 类型的讨论。

看来您将不得不考虑如何通过插补或其他形式的数据清理来处理丢失的数据。

或者也许 tensorshape 就是您所需要的。

这取决于你做什么。可能最好的方法是将 None 转换为 0.

将事物转换为 numpy 数组,然后再转换为 Torch 张量是一个很好的途径,因为它将 None 转换为 np.nan。然后你可以创建 Torch 张量甚至保持 np.nan.

import torch
import numpy as np

a = [1,3, None, 5,6]
b = np.array(a,dtype=float) # you will have np.nan from None
print(b) #[ 1.  3. nan  5.  6.]
np.nan_to_num(b, copy=False)
print(b) #[1. 3. 0. 5. 6.]
torch.tensor(b, dtype=torch.float) #tensor([1., 3., 0., 5., 6.])

也尝试在 np.nan_to_num 中使用 copy=True,您将在张量中得到 nan 而不是 0。