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


当前回答

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

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

其他回答

当我使用sklearn与熊猫时,我得到了同样的错误消息。我的解决方案是在运行任何sklearn代码之前重置我的dataframe df的索引:

df = df.reset_index()

在删除df中的一些条目时,我多次遇到这个问题,例如

df = df[df.label=='desired_one']
dataset = dataset.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

这对我很有效

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

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

这是它失败的检查:

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。

这里没有一个答案对我有用。这是有效的。

Test_y = np.nan_to_num(Test_y)

它将无穷大值替换为高有限值,将nan值替换为数字