我使用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。


当前回答

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

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

其他回答

这可能发生在scikit内部,这取决于您正在做什么。我建议阅读您正在使用的函数的文档。你可能会使用一个,例如,你的矩阵是正定的,不满足那个条件。

编辑:我怎么能错过呢?

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

显然是错误的。正确的是:

np.any(np.isnan(mat))

and

np.all(np.isfinite(mat))

您想要检查是否有任何元素是NaN,而不是任何函数的返回值是否为数字…

如果您碰巧使用“kc_house_data.csv”数据集(一些评论者和许多数据科学新手似乎使用这个数据集,因为它出现在许多流行的课程材料中),则该数据是错误的,并且是错误的真正来源。

为了解决这个问题,从2022年开始:

删除csv文件中的最后一行(空) 有两行包含一个空数据值"x,x,,x,x" -要修复它,不要删除逗号,而是添加一个随机整数值,如2000,因此它看起来像"x,x,2000,x,x"

不要忘记在项目中保存和重新加载。

所有其他答案都是有帮助和正确的,但在这种情况下不是:

如果你使用kc_house_data.csv,你需要修复文件中的数据,没有其他帮助,空数据字段将随机转移其他数据,并产生难以追踪到源的奇怪错误!

使用isneginf可能会有所帮助。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.isneginf.html#numpy.isneginf

x[numpy.isneginf(x)] = 0 #0 is the value you want to replace with

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

我的输入数组的维度是倾斜的,因为我的输入csv有空格。