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


当前回答

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

这对我很有效

其他回答

在处理这个问题很长一段时间后,我意识到这是因为在训练集和测试集的分割中,所有数据行的数据列都是相同的。然后在某些算法中进行一些计算可能会导致无穷大的结果。如果您正在使用的数据的关闭行更可能是相似的,那么重新排列数据会有所帮助。这是scikit的一个漏洞。我使用的是0.23.2版本。

在我的例子中,算法要求数据在(0,1)之间不包含。我非常残酷的解决方案是在所有期望值中添加一个小随机数:

y_train = pd.DataFrame(y_train).applymap(lambda x: x + np.random.rand()/100000.0)["col_name"]
y_train[y_train >= 1] = 0.999999

而y_train在[0,1]的范围内。

这当然不适合所有的情况,因为你会弄乱你的输入数据,但如果你有稀疏的数据,只需要一个快速的预测,这是一个解决方案

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

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

df = df.reindex(index=my_index)

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

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

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

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