建立一个定制的ScikitLearn Impu

2024-09-18 23:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个自定义Scikit学习转换器。具体来说,我的目标是填充应用于用户指定阈值的特征列,即非Nan类型的实例的部分。例如,如果将阈值设置为90%,并且特征1由50%的NaN类型组成,而特征2由95%的NaN类型组成,则该算法将丢弃第一个特征并填充第二个特征。在

我已经生成了一个工作结构,但是由于我不熟悉编程,所以我想就以下问题提供一些建议:我是否需要在每个方法中定义imputer=imputer(…),还是有更无缝的方法来实现这一点?目前,如果我在一个实例上调用fit_transform,我的代码可以工作;但是,如果我调用transform,它将失败,我应该如何集成fit和transform来解决这个问题?有没有更容易的方法来获取填充者的统计特性而不是为其创建一个方法?在

注意,转换代码实际上还没有完全实现我想要的功能,但是我现在更关心的是类结构,应该能够自己修复功能。在

import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import Imputer

class CustomImputer(BaseEstimator, TransformerMixin):
    """Custom imputation transformer for completing missing values provided
    they meet the user specified threshold.
    """
    def __init__(self, threshold, strat):
        self.threshold = threshold
        self.strat = strat
    def fit(self, X, y=None):
        """Fit the imputer on X.
        """
        imputer = Imputer(strategy=self.strat)
        return imputer.fit(X)
    def statistics_(self):
        """Documentation...
        """
        imputer = Imputer(strategy=self.strat)
        self.statistics_ = imputer.fit(X).statistics_
        return self.statistics_
    def transform(self, X):
        """Impute all missing values in X that meet the user specified threshold.
        """
        imputer = Imputer(strategy=self.strat)
        nulls = X.isnull().sum()
        size = X.shape[0]
        for i in range(X.shape[1]):
            if (1 - nulls[i] / size) < self.threshold:
                X.drop(X.columns[i], axis=1) # drop features that don't meet criteria? other options?
        return imputer.transform(X)


df = pd.read_csv("fact_sage_data.csv")
X = df.drop(["cmpd", "H_eVatom"], axis=1)
plz_impute = CustomImputer(0.99, "median")
X_imputed = plz_impute.fit_transform(X) # in this specific case it dropped 75 features

Tags: the方法importself类型thresholddeftransform