Scikit-Learn自定义变压器:ColumnSelectTransformer

时间:2019-10-07 14:00:00

标签: python pandas dataframe machine-learning scikit-learn

提供来自

的数据
%%bash
mkdir data
wget http://dataincubator-wqu.s3.amazonaws.com/mldata/providers-train.csv -nc -P ./ml-data
wget http://dataincubator-wqu.s3.amazonaws.com/mldata/providers-metadata.csv -nc -P ./ml-data

我受命完成以下代码段。

simple_cols = ['BEDCERT', 'RESTOT', 'INHOSP', 'CCRC_FACIL', 'SFF', 'CHOW_LAST_12MOS', 'SPRINKLER_STATUS', 'EXP_TOTAL', 'ADJ_TOTAL']

class ColumnSelectTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        if not isinstance(X, pd.DataFrame):
            X = pd.DataFrame(X)
        return X[self.columns]

simple_features = Pipeline([
    ('cst', ColumnSelectTransformer(simple_cols)),
])

assert data['RESTOT'].isnull().sum() > 0
assert not np.isnan(simple_features.fit_transform(data)).any()

完成此断言检查

assert data['RESTOT'].isnull().sum() > 0
assert not np.isnan(simple_features.fit_transform(data)).any()

但是我无法通过断言测试。以下是我的尝试:

simple_cols = ['BEDCERT', 'RESTOT', 'INHOSP', 'CCRC_FACIL', 'SFF', 'CHOW_LAST_12MOS', 'SPRINKLER_STATUS', 'EXP_TOTAL', 'ADJ_TOTAL']

class ColumnSelectTransformer(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        if not isinstance(X, pd.DataFrame):
            X = pd.DataFrame(X)
        X.dropna(inplace=True)
        return X[self.columns].values()

simple_features = Pipeline([
    ('cst', ColumnSelectTransformer(simple_cols)),
])

非常感谢我能提供的任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

问题出在

return X[self.columns].values()

正确的return语句应该是

return X[self.columns].values