我使用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()

其他回答

如果您正在运行一个估计器,可能是您的学习率太高了。我意外地将错误的数组传递给了网格搜索,最终训练的学习率为500,我可以看到这导致了训练过程中的问题。

基本上,不仅你的输入必须全部有效,中间数据也必须有效。

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

这对我很有效

这是它失败的检查:

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。

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

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

在大多数情况下,消除无限和空值可以解决这个问题。

去掉无穷值。

df.replace([np.inf, -np.inf], np.nan, inplace=True)

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

df.fillna(999, inplace=True)