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


当前回答

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

其他回答

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

问题似乎发生在DecisionTreeClassifier输入检查,尝试

X_train = X_train.replace((np.inf, -np.inf, np.nan), 0).reset_index(drop=True)

这是它失败的检查:

https://github.com/scikit-learn/scikit-learn/blob/0.17.X/sklearn/utils/validation.py#L51

def _assert_all_finite(X):
    """Like assert_all_finite, but only for ndarray."""
    X = np.asanyarray(X)
    # First try an O(n) time, O(1) space solution for the common case that
    # everything is finite; fall back to O(n) space np.isfinite to prevent
    # false positives from overflow in sum method.
    if (X.dtype.char in np.typecodes['AllFloat'] and not np.isfinite(X.sum())
            and not np.isfinite(X).all()):
        raise ValueError("Input contains NaN, infinity"
                         " or a value too large for %r." % X.dtype)

所以确保你的输入中有非NaN值。所有这些值实际上都是浮点值。这些值也不应该是Inf。

这是我的函数(基于此)来清除数据集的nan, Inf和缺失的单元格(用于倾斜的数据集):

import pandas as pd
import numpy as np

def clean_dataset(df):
    assert isinstance(df, pd.DataFrame), "df needs to be a pd.DataFrame"
    df.dropna(inplace=True)
    indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(axis=1)
    return df[indices_to_keep].astype(np.float64)

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

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

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