해결 방법: 입력에 nan, 무한대 또는 dtype에 비해 너무 큰 값('float64')이 포함되어 있습니다.
Python을 사용할 때 발생할 수 있는 일반적인 오류는 다음과 같습니다.
ValueError: Input contains infinity or a value too large for dtype('float64').
이 오류는 일반적으로 scikit-learn 모듈의 함수를 사용하려고 할 때 발생하지만 입력으로 사용하는 DataFrame이나 행렬에 NaN 값 또는 무한 값이 있습니다.
다음 예에서는 실제로 이 오류를 해결하는 방법을 보여줍니다.
오류를 재현하는 방법
다음과 같은 팬더 DataFrame이 있다고 가정합니다.
import pandas as pd import numpy as np #createDataFrame df = pd. DataFrame ({' x1 ': [1, 2, 2, 4, 2, 1, 5, 4, 2, 4, 4], ' x2 ': [1, 3, 3, 5, 2, 2, 1, np.inf, 0, 3, 4], ' y ': [np.nan, 78, 85, 88, 72, 69, 94, 94, 88, 92, 90]}) #view DataFrame print (df) x1 x2 y 0 1 1.0 NaN 1 2 3.0 78.0 2 2 3.0 85.0 3 4 5.0 88.0 4 2 2.0 72.0 5 1 2.0 69.0 6 5 1.0 94.0 7 4 lower 94.0 8 2 0.0 88.0 9 4 3.0 92.0 10 4 4.0 90.0
이제 scikit-learn 함수를 사용하여 다중 선형 회귀 모델을 맞추려고 한다고 가정합니다.
from sklearn. linear_model import LinearRegression
#initiate linear regression model
model = LinearRegression()
#define predictor and response variables
x, y = df[[' x1 ', ' x2 ']], df. y
#fit regression model
model. fit (x,y)
#print model intercept and coefficients
print (model. intercept_ , model. coef_ )
ValueError: Input contains infinity or a value too large for dtype('float64').
우리가 사용하고 있는 DataFrame에 무한 값과 NaN 값이 모두 있기 때문에 오류가 발생합니다.
오류를 수정하는 방법
이 오류를 해결하는 방법은 먼저 무한 또는 NaN 값을 포함하는 DataFrame에서 모든 행을 제거하는 것입니다.
#remove rows with any values that are not finite
df_new = df[np. isfinite (df). all ( 1 )]
#view updated DataFrame
print (df_new)
x1 x2 y
1 2 3.0 78.0
2 2 3.0 85.0
3 4 5.0 88.0
4 2 2.0 72.0
5 1 2.0 69.0
6 5 1.0 94.0
8 2 0.0 88.0
9 4 3.0 92.0
10 4 4.0 90.0
무한 또는 NaN 값이 있는 두 줄이 제거되었습니다.
이제 선형 회귀 모델을 적합화할 수 있습니다.
from sklearn. linear_model import LinearRegression
#initiate linear regression model
model = LinearRegression()
#define predictor and response variables
x, y = df_new[[' x1 ', ' x2 ']], df_new. y
#fit regression model
model. fit (x,y)
#print model intercept and coefficients
print (model. intercept_ , model. coef_ )
69.85144124168515 [5.72727273 -0.93791574]
DataFrame에서 무한 또는 NaN 값이 있는 행을 먼저 제거했기 때문에 이번에는 오류가 발생하지 않습니다.
추가 리소스
다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.
Python에서 수정하는 방법: ‘numpy.ndarray’ 개체를 호출할 수 없습니다.
수정 방법: TypeError: ‘numpy.float64’ 개체를 호출할 수 없습니다.
수정 방법: 유형 오류: 예상 문자열 또는 바이트 개체