Programming

sklearn 오류 ValueError : 입력에 NaN, 무한대 또는 dtype ( 'float64')에 비해 너무 큰 값이 있습니다.

procodes 2020. 8. 28. 08:17
반응형

sklearn 오류 ValueError : 입력에 NaN, 무한대 또는 dtype ( 'float64')에 비해 너무 큰 값이 있습니다.


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

무한한 값을 제거했지만 이것도 작동하지 않았습니다. 선호도 전파 알고리즘을 사용할 수 있도록 매트릭스에서 무한 값을 제거하려면 어떻게해야합니까?

아나콘다와 파이썬 2.7.9를 사용하고 있습니다.


이것은 scikit 내부에서 발생할 수 있으며 수행하는 작업에 따라 다릅니다. 사용중인 기능에 대한 문서를 읽는 것이 좋습니다. 예를 들어 행렬이 양의 값이고 해당 기준을 충족하지 못하는 것에 의존하는 것을 사용할 수 있습니다.

편집 : 나는 그것을 어떻게 놓칠 수 있습니까?

np.isnan(mat.any()) #and gets False
np.isfinite(mat.all()) #and gets True

분명히 잘못되었습니다. 오른쪽은 다음과 같습니다.

np.any(np.isnan(mat))

np.all(np.isfinite(mat))

any함수 의 반환 값이 숫자 인지 아닌지 요소가 NaN인지 확인하고 싶습니다 .


pandas 와 함께 sklearn사용할 때 동일한 오류 메시지가 나타납니다 . 내 솔루션은 sklearn 코드를 실행하기 전에 데이터 프레임의 인덱스를 재설정하는 것입니다 .df

df = df.reset_index()

df에서 다음과 같은 일부 항목을 제거 할 때이 문제가 여러 번 발생 했습니다.

df = df[df.label=='desired_one']

내 입력 csv에 빈 공간이 있기 때문에 입력 배열의 차원이 왜곡되었습니다.


이것이 실패한 검사입니다.

어느 말

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이 아닌 값이 있는지 확인하십시오. 그리고 그 모든 값은 실제로 float 값입니다. 어떤 값도 Inf가 아니어야합니다.


이것은 (에 따라 내 함수 )의 데이터 집합을 청소 nan, Inf및 (왜곡 된 데이터 세트에 대한) 세포 누락 :

import pandas as pd

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(1)
    return df[indices_to_keep].astype(np.float64)

이 버전의 python 3 :

/opt/anaconda3/bin/python --version
Python 3.6.0 :: Anaconda 4.3.0 (64-bit)

오류의 세부 사항을 살펴보면 오류를 일으키는 코드 줄을 찾았습니다.

/opt/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py in _assert_all_finite(X)
     56             and not np.isfinite(X).all()):
     57         raise ValueError("Input contains NaN, infinity"
---> 58                          " or a value too large for %r." % X.dtype)
     59 
     60 

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

이로부터 오류 메시지가 제공하는 동일한 테스트를 사용하여 내 데이터로 진행중인 작업을 테스트하는 올바른 방법을 추출 할 수있었습니다. np.isfinite(X)

그런 다음 빠르고 더러운 루프를 통해 내 데이터에 실제로 다음이 포함되어 있음을 알 수있었습니다 nans.

print(p[:,0].shape)
index = 0
for i in p[:,0]:
    if not np.isfinite(i):
        print(index, i)
    index +=1

(367340,)
4454 nan
6940 nan
10868 nan
12753 nan
14855 nan
15678 nan
24954 nan
30251 nan
31108 nan
51455 nan
59055 nan
...

이제해야 할 일은 이러한 인덱스에서 값을 제거하는 것입니다.


행의 하위 집합을 선택하려고 시도한 후 오류가 발생했습니다.

df = df.reindex(index=my_index)

my_index포함되지 않은 값 포함 된 것으로 밝혀 df.index졌으므로 재색 인 기능이 새 행을 삽입하고 nan.


I had the same error, and in my case X and y were dataframes so I had to convert them to matrices first:

X = X.as_matrix().astype(np.float)
y = y.as_matrix().astype(np.float)

i got the same error. it worked with df.fillna(-99999, inplace=True) before doing any replacement, substitution etc


In my case the problem was that many scikit functions return numpy arrays, which are devoid of pandas index. So there was an index mismatch when I used those numpy arrays to build new DataFrames and then I tried to mix them with the original data.


try

mat.sum()

If the sum of your data is infinity (greater that the max float value which is 3.402823e+38) you will get that error.

see the _assert_all_finite function in validation.py from the scikit source code:

if is_float and np.isfinite(X.sum()):
    pass
elif is_float:
    msg_err = "Input contains {} or a value too large for {!r}."
    if (allow_nan and np.isinf(X).any() or
            not allow_nan and not np.isfinite(X).all()):
        type_err = 'infinity' if allow_nan else 'NaN, infinity'
        # print(X.sum())
        raise ValueError(msg_err.format(type_err, X.dtype))

참고URL : https://stackoverflow.com/questions/31323499/sklearn-error-valueerror-input-contains-nan-infinity-or-a-value-too-large-for

반응형