【问题标题】:ValueError: Input contains NaN, even when Using SimpleImputerValueError:输入包含 NaN,即使使用 SimpleImputer
【发布时间】:2021-04-19 08:03:24
【问题描述】:

我正在尝试使用 Titanic 数据集作为我的第一个 Kaggle 项目,但遇到了这个错误。我一直在 Stack 上寻找解决方案,但我仍然无法弄清楚。

我做了两个 Pipelines 来预处理数字和分类特征:

num_pipeline = Pipeline([
            ('imputer', SimpleImputer( strategy='median')), 
            ('scaler', StandardScaler())])
    
cat_pipeline = Pipeline([
        ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
        ('onehot', OneHotEncoder()) ])

然后我将它们加入到 ColumnTransformer 中

preprocessor = ColumnTransformer(
        transformers = [
            ('num', num_pipeline, numeric_features),
            ('cat', cat_pipeline, categorical_features) ])

numeric_features 和 categorical_features 是数值和分类特征的列表:

numeric_features = ['Age', 'SibSp', 'Parch', 'Fare']
categorical_features = ['Pclass', 'Sex',  'Embarked']

最后,在我的最终管道中,我添加了一个分类器:

knn = Pipeline([
    ('Preprocessor' , preprocessor),
    ('Classifier', KNeighborsClassifier())
])
knn.fit(X_train, y_train)

这是我得到“ValueError:输入包含 NaN”的时候

【问题讨论】:

    标签: python scikit-learn pipeline


    【解决方案1】:
    train = pd.read_csv('train.csv')
    train.isna().sum()
    

    输出:

    PassengerId      0
    Survived         0
    Pclass           0
    Name             0
    Sex              0
    Age            177
    SibSp            0
    Parch            0
    Ticket           0
    Fare             0
    Cabin          687
    Embarked         2
    dtype: int64
    

    AgeCabinEmbarked 列包含 NaN 值。但是,您没有在numeric_featurescategorical_features 中包含Cabin 列,因此它的值不会被估算。这就是您收到错误的原因。

    【讨论】:

    • 感谢您的回答。我尝试将 'Cabin' 添加到 categorical_features 中,但它仍然不起作用。
    • @MedCh 你能做preprocessor.fit_transform(X_train),然后在结果上运行df.isna().sum()吗?这将显示哪些特征仍然具有 NaN 值
    • preprocessor.fit_transform(X_train) 返回一个数组,因此计算空值返回 0:count=0 for i in range(len(df)): for j in df[i]: if np.isnan(i): count+=1 i+=1 count
    • 我刚刚注意到:您的管道称为knn,但您调用rf.fit()rf 是什么?
    • 对不起,应该是knn.fit()。我从 Jupyter 复制时出错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2021-04-29
    • 2021-03-14
    相关资源
    最近更新 更多