LoginSignup
9
8

More than 3 years have passed since last update.

機械学習でInput contains NaN, infinity or a value too large for dtype('float64').というエラーが出たときの対処法

Posted at

機械学習で「Input contains NaN, infinity or a value too large for dtype('float64').」というエラーが出たときの対処法

エラーの原因

上のエラーに書いてある通りデータにNaNかinfかfloat64でないタイプのものが混じっている。文字列を含む列をpandasで以下のように書き、Naも埋めたのにエラーが出た。

df=df.drop(columns=df.select_dtypes(include='object').columns)

これでは列の中に一部含まれるfloat以外の値を変換することができないみたいだ。
そこでnumpyで使えるようにndarrayに変換した後、float以外の値になるやつをfloat型に変換させ、float型に変更不可能なものをNaとし、その後欠損値を変換した。

X = df.iloc[:, 1:].values
y = df.iloc[:, 0].values
for i in range(X.shape[1]):
    X[:,i]= pd.to_numeric(X[:,i], errors='coerce')
X1=np.nan_to_num(X)

これが正しい処理なのかはよくわからないが、とりあえずモデルを学習させるときのエラーはなくなった。
なにかいいやり方があったらコメントお願いします。

9
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8