【发布时间】:2015-03-04 20:09:28
【问题描述】:
下面是我的管道,我似乎无法通过使用 ModelTransformer 类将参数传递给我的模型,我从链接 (http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html) 获取它
错误消息对我来说很有意义,但我不知道如何解决这个问题。知道如何解决这个问题吗?谢谢。
# define a pipeline
pipeline = Pipeline([
('vect', DictVectorizer(sparse=False)),
('scale', preprocessing.MinMaxScaler()),
('ess', FeatureUnion(n_jobs=-1,
transformer_list=[
('rfc', ModelTransformer(RandomForestClassifier(n_jobs=-1, random_state=1, n_estimators=100))),
('svc', ModelTransformer(SVC(random_state=1))),],
transformer_weights=None)),
('es', EnsembleClassifier1()),
])
# define the parameters for the pipeline
parameters = {
'ess__rfc__n_estimators': (100, 200),
}
# ModelTransformer class. It takes it from the link
(http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html)
class ModelTransformer(TransformerMixin):
def __init__(self, model):
self.model = model
def fit(self, *args, **kwargs):
self.model.fit(*args, **kwargs)
return self
def transform(self, X, **transform_params):
return DataFrame(self.model.predict(X))
grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1, refit=True)
错误信息: ValueError:估计器 ModelTransformer 的参数 n_estimators 无效。
【问题讨论】:
-
感谢您的提问——我也有同样的问题。让我再问你一件事。你知道为什么 self.model.fit(*args, **kwargs) 有效吗?我的意思是你通常不会在调用 fit 方法时传递像 n_estimators 这样的超参数,但是在定义类实例时,例如 rfc=RandomForestClassifier(n_estimators=100), rfc.fit(X,y)
-
@drake,当你创建一个 ModelTransformer 实例时,你需要传入一个带有参数的模型。例如,ModelTransformer(RandomForestClassifier(n_jobs=-1, random_state=1, n_estimators=100)))。而这里 self.model.fit(*args, **kwargs) 主要是指 self.model.fit(X, y)。
-
谢谢,@nkhuyu。我知道它是这样工作的。我在问为什么。由于 self.model = 模型,self.model=RandomForestClassifier(n_jobs=-1, random_state=1, n_estimators=100)。我知道 *args 正在解包 (X, y),但我不明白为什么 self.model 已经知道超参数时在 fit 方法中需要 **kwargs。
标签: python-2.7 machine-learning parameter-passing scikit-learn cross-validation