如何建立sklearn管道来执行以下操作?
我所拥有的:
A, B = getAB(X_train)
X_train = transform(X_train)
model(A, B, X_train)
我想要什么:
pipe = Pipeline([
(‘ab’, getAB),
(‘tranf’, transform),
(‘net’, net)
]
pipe.fit(X_train, y_train)
请帮助!
答案 0 :(得分:1)
是的,可以通过编写具有拟合/转换功能的自定义转换器来实现。这可以是您的课程:
from sklearn.base import BaseEstimator, TransformerMixin
def getABTransformer(BaseEstimator, TransformerMixin):
def __init__(self): # no *args or **kargs
pass
def fit(self, X, y=None):
return self # nothing else to do
def transform(self, X, y=None):
return getAB(X)
然后,您可以按照以下步骤创建ColumnTransformer
:
from sklearn.compose import ColumnTransformer
clm_pipe = ColumnTransformer([
(‘ab’, getABTransformer, np.arange(0, len(X_train)), # list of columns indices
(‘tranf’, transform, np.arange(0, len(X_train))), # list of columns indices
]
以及该模型的最终管道:
pipe = Pipeline([
(‘clm_pipe’, clm_pipe),
(‘net’, net)
]
您可以阅读有关ColumnTransformer
的更多信息