【发布时间】:2020-09-12 12:09:42
【问题描述】:
我想使用FunctionTransformer,同时提供一个简单的API并隐藏额外的细节。具体来说,我希望能够提供一个Custom_Trans 类,如下所示。因此,用户应该能够使用目前失败的trans2,而不是正常工作的trans2:
from sklearn import preprocessing
from sklearn.pipeline import Pipeline
from sklearn import model_selection
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
import numpy as np
X, y = make_regression(n_samples=100, n_features=1, noise=0.1)
def func(X, a, b):
return X[:,a:b]
class Custom_Trans(preprocessing.FunctionTransformer):
def __init__(self, ind0, ind1):
super().__init__(
func=func,
kw_args={
"a": ind0,
"b": ind1
}
)
trans1 = preprocessing.FunctionTransformer(
func=func,
kw_args={
"a": 0,
"b": 50
}
)
trans2 = Custom_Trans(0,50)
pipe1 = Pipeline(
steps=[
('custom', trans1),
('linear', LinearRegression())
]
)
pipe2 = Pipeline(
steps=[
('custom', trans2),
('linear', LinearRegression())
]
)
print(model_selection.cross_val_score(
pipe1, X, y, cv=3,)
)
print(model_selection.cross_val_score(
pipe2, X, y, cv=3,)
)
这是我得到的:
[0.99999331 0.99999671 0.99999772]
...sklearn/base.py:209: FutureWarning: From version 0.24, get_params will raise an
AttributeError if a parameter cannot be retrieved as an instance attribute.
Previously it would return None.
warnings.warn('From version 0.24, get_params will raise an '
...
[0.99999331 0.99999671 0.99999772]
我知道这与估算器克隆有关,但我不知道如何解决。例如this post 这么说
估计器中不应该有逻辑,甚至没有输入验证 初始化。逻辑应该放在使用参数的地方,这通常是合适的
但在这种情况下,我需要将参数传递给超类。没有办法将逻辑放在fit() 中。
我能做什么?
【问题讨论】:
-
刚刚在
BaseEstimator中看到了这个注释所有的估算器都应该在它们的init 中指定所有可以在类级别设置的参数作为显式关键字参数(没有 *args 或 **kwargs)。
标签: python inheritance scikit-learn