我使用sklearn和有一个问题的亲和传播。我已经建立了一个输入矩阵,我一直得到以下错误。

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

我已经跑了

np.isnan(mat.any()) #and gets False
np.isfinite(mat.all()) #and gets True

我试着用

mat[np.isfinite(mat) == True] = 0

去除掉无限值,但这也没用。 我要怎么做才能去掉矩阵中的无穷大值,这样我就可以使用亲和传播算法了?

我使用anaconda和python 2.7.9。


当前回答

我有错误后,试图选择一个子集的行:

df = df.reindex(index=my_index)

结果是my_index包含df中不包含的值。索引,所以reindex函数插入一些新行,并用nan填充它们。

其他回答

dataset = dataset.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

这对我很有效

我想为numpy提出一个适合我的解决方案。这条线

from numpy import inf
inputArray[inputArray == inf] = np.finfo(np.float64).max

将numpy数组的所有无限值替换为最大的float64数。

我发现在一个新列上调用pct_change后,nan存在于一行中。我用下面的代码删除nan行

df = df.replace([np.inf, -np.inf], np.nan)
df = df.dropna()
df = df.reset_index()

try

mat.sum()

如果你的数据和是无穷大(大于最大浮点值3.402823e+38),你会得到这个错误。

请参阅scikit源代码中的validation.py中的_assert_all_finite函数:

if is_float and np.isfinite(X.sum()):
    pass
elif is_float:
    msg_err = "Input contains {} or a value too large for {!r}."
    if (allow_nan and np.isinf(X).any() or
            not allow_nan and not np.isfinite(X).all()):
        type_err = 'infinity' if allow_nan else 'NaN, infinity'
        # print(X.sum())
        raise ValueError(msg_err.format(type_err, X.dtype))

如果您正在运行一个估计器,可能是您的学习率太高了。我意外地将错误的数组传递给了网格搜索,最终训练的学习率为500,我可以看到这导致了训练过程中的问题。

基本上,不仅你的输入必须全部有效,中间数据也必须有效。