简体   繁体   English

如何将其中没有任何内容的列表转换为torch.tensor()?

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

For example I have a variable z = [1, 3, None, 5, 6] 例如,我有一个变量z = [1, 3, None, 5, 6]

I would like to do: torch.tensor(z) 我想做: torch.tensor(z)

and get something like the following: 并得到如下内容:

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

Howhever, such attempt raises an error 但是,这样的尝试会引发错误

TypeError: must be real number, not NoneType TypeError:必须为实数,而不是NoneType

Is there a way to convert such list to a torch.tensor ? 有没有办法将此类列表转换为torch.tensor

I don't want to impute this None value with something else. 我不想用其他东西来推论这个None值。 Numpy arrays are capable of converting such lists np.array([1, 3, None, 5, 6]) , but I'd prefer not to convert back and forth variable either. Numpy数组能够转换这样的列表np.array([1, 3, None, 5, 6]) ,但是我也不希望来回转换变量。

It depends on what you do. 这取决于您的工作。 Probable the best is to convert None to 0 . 最好的办法是将None转换为0

Converting things to numpy arrays and then to Torch tensors is a very good path since it will convert None to np.nan . 将事物转换为numpy数组然后转换为Torch张量是一个很好的方法,因为它将将None转换为np.nan Then you can create the Torch tensor even holding np.nan . 然后,即使持有np.nan您也可以创建Torch张量。

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.])

Try also copy=True inside np.nan_to_num and you will get nan inside your tensor instead of 0. 也尝试在np.nan_to_numnp.nan_to_num copy=True ,您将在张量内得到nan而不是0。

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 . 我感觉数据源的张量构造不允许Numpy具有允许None类型的宽大处理 Please see also here for a discussion where others have asked about None types in tensors. 另请参阅此处的讨论,其中其他人询问了张量中的None类型。

Looks like you're going to have to think about how to handle your missing data, either through imputation or another form of data cleaning. 看起来您将不得不考虑如何通过归因或其他形式的数据清除来处理丢失的数据。

Or perhaps a tensorshape is what you need. 或者您可能需要张量形状

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

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