【问题标题】:raise ValueError("Input contains NaN") ValueError: Input contains NaN when trying to build machine learning modelraise ValueError("Input contains NaN") ValueError: Input contains NaN 在尝试构建机器学习模型时
【发布时间】:2021-03-25 09:06:36
【问题描述】:

我正在尝试构建一个预测模型,但目前不断收到错误消息:raise ValueError("Input contains NaN") ValueError: Input contains NaN。我尝试使用np.any(np.isnan(dataframe))np.any(np.isnan(dataframe)),但我不断收到新的错误。例如,TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

这是目前为止的代码:

import pandas as pd
from sklearn.preprocessing import LabelEncoder
import numpy as np

dataframe = pd.read_csv('file.csv', delimiter=',')

le = LabelEncoder()
dfle = dataframe

dfle2 = dfle.apply(lambda col: le.fit_transform(col.astype(str)), axis=0, result_type='expand')

newdf = dfle2[['column1', 'column2', 'column3', 'column4', 'column5', 'column6', 'column7']]

X = dataframe[['column1', 'column2', 'column4', 'column5', 'column6', 'column7']].values

y = dfle.column3

from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ohe = OneHotEncoder()

ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')
# np.all(np.isfinite(dfle))
# np.any(np.isnan(dfle))
X = ohe.fit_transform(X).toarray()

【问题讨论】:

    标签: python pandas scikit-learn one-hot-encoding label-encoding


    【解决方案1】:

    你可以做很多事情来处理这个错误 首先,您可以将 Nan 值填充为 0 dataframe = pd.read_csv('file.csv', delimiter=',').fillna(0)

    或者您可以使用sklearn 插补技术来填充 Nan 值。

    https://scikit-learn.org/stable/modules/classes.html#module-sklearn.impute

    可以使用多种插补技术,但您应该使用KNNImputer

    【讨论】:

    • df.dropna() 也可以,不过我觉得用处不大。
    【解决方案2】:

    错误

    TypeError: ufunc 'isfinite' not supported for the input types,
    and the inputs could not be safely coerced to any supported types
    according to the casting rule ''safe''
    

    可能是因为您在执行col.astype(str) 时转换为str。请改用astype(float) 之类的东西。

    至于NaN 错误,您需要确定是否可以通过将其替换为零 (fillna(0)) 来解决,或者是否需要使用更复杂的东西,例如卡尔曼滤波器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多