我使用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.replace([np.inf, -np.inf], np.nan, inplace=True)

以您喜欢的方式摆脱空值,特定的值,如999,平均值,或创建自己的函数来输入缺失的值

df.fillna(999, inplace=True)

其他回答

这可能发生在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,而不是任何函数的返回值是否为数字…

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

这对我很有效

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

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

df = df.reindex(index=my_index)

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

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