美文网首页
处理缺失数据

处理缺失数据

作者: 1nvad3r | 来源:发表于2020-09-23 17:10 被阅读0次

    方法一:
    直接丢弃含缺失数据的列。

    # Get names of columns with missing values
    cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
    
    # Drop columns in training and validation data
    reduced_X_train = X_train.drop(cols_with_missing, axis=1)
    reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)
    
    print("MAE from Approach 1 (Drop columns with missing values):")
    print(score_dataset(reduced_X_train, reduced_X_valid, y_train, y_valid))
    

    方法二:
    对缺失值进行填充,SimpleImputer()默认按均值填充。

    from sklearn.impute import SimpleImputer
    
    # Imputation
    my_imputer = SimpleImputer()
    imputed_X_train = pd.DataFrame(my_imputer.fit_transform(X_train))
    imputed_X_valid = pd.DataFrame(my_imputer.transform(X_valid))
    
    # Imputation removed column names; put them back
    imputed_X_train.columns = X_train.columns
    imputed_X_valid.columns = X_valid.columns
    
    print("MAE from Approach 2 (Imputation):")
    print(score_dataset(imputed_X_train, imputed_X_valid, y_train, y_valid))
    

    方法三:
    填充的扩展,在原数据上加几列,列中的值是boolean类型,如果该数据丢失则为1,如果没丢失则为0。

    # Get names of columns with missing values
    cols_with_missing = [col for col in X_train.columns if X_train[col].isnull().any()]
    
    # Make copy to avoid changing original data (when imputing)
    X_train_plus = X_train.copy()
    X_valid_plus = X_valid.copy()
    
    # Make new columns indicating what will be imputed
    for col in cols_with_missing:
        X_train_plus[col + '_was_missing'] = X_train_plus[col].isnull()
        X_valid_plus[col + '_was_missing'] = X_valid_plus[col].isnull()
    
    # Imputation
    my_imputer = SimpleImputer()
    imputed_X_train_plus = pd.DataFrame(my_imputer.fit_transform(X_train_plus))
    imputed_X_valid_plus = pd.DataFrame(my_imputer.transform(X_valid_plus))
    
    from sklearn.impute import SimpleImputer
    
    # Imputation removed column names; put them back
    imputed_X_train_plus.columns = X_train_plus.columns
    imputed_X_valid_plus.columns = X_valid_plus.columns
    
    print("MAE from Approach 3 (An Extension to Imputation):")
    print(score_dataset(imputed_X_train_plus, imputed_X_valid_plus, y_train, y_valid))
    
    

    相关文章

      网友评论

          本文标题:处理缺失数据

          本文链接:https://www.haomeiwen.com/subject/sxyoyktx.html