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


当前回答

这是我的函数(基于此)来清除数据集的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)

其他回答

在我的例子中,问题是许多scikit函数返回numpy数组,这些数组没有pandas索引。因此,当我使用那些numpy数组来构建新的dataframe时,有一个索引不匹配,然后我尝试将它们与原始数据混合。

这是它失败的检查:

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。

在我的例子中,算法要求数据在(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]的范围内。

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

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

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

df = df.reindex(index=my_index)

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