首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在scikit-learn管道中锁定步骤(防止重新设置)

在scikit-learn管道中锁定步骤(防止重新设置)
EN

Stack Overflow用户
提问于 2017-02-09 22:29:38
回答 2查看 1.1K关注 0票数 7

有没有一种方便的机制来锁定科学工具包学习管道中的步骤,以防止它们在pipeline.fit()上重新部署?例如:

代码语言:javascript
复制
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.pipeline import Pipeline
from sklearn.datasets import fetch_20newsgroups

data = fetch_20newsgroups(subset='train')
firsttwoclasses = data.target<=1
y = data.target[firsttwoclasses]
X = np.array(data.data)[firsttwoclasses]

pipeline = Pipeline([
    ("vectorizer", CountVectorizer()),
    ("estimator", LinearSVC())
])

# fit intial step on subset of data, perhaps an entirely different subset
# this particular example would not be very useful in practice
pipeline.named_steps["vectorizer"].fit(X[:400])
X2 = pipeline.named_steps["vectorizer"].transform(X)

# fit estimator on all data without refitting vectorizer
pipeline.named_steps["estimator"].fit(X2, y)
print(len(pipeline.named_steps["vectorizer"].vocabulary_))

# fitting entire pipeline refits vectorizer
# is there a convenient way to lock the vectorizer without doing the above?
pipeline.fit(X, y)
print(len(pipeline.named_steps["vectorizer"].vocabulary_))

我能想到的唯一不需要中间转换的方法就是定义一个自定义的估计器类(如here所示),它的拟合方法什么也不做,它的变换方法是预拟合变换器的变换。这是唯一的办法吗?

EN

回答 2

Stack Overflow用户

发布于 2017-06-23 03:50:24

纵观整个代码,在管道对象中似乎没有任何东西具有这样的功能:在管道上调用.fit()会导致在每个阶段上使用.fit()。

我能想到的最好的快速解决方案是用猴子来修补舞台的装配功能:

代码语言:javascript
复制
pipeline.named_steps["vectorizer"].fit(X[:400])
# disable .fit() on the vectorizer step
pipeline.named_steps["vectorizer"].fit = lambda self, X, y=None: self
pipeline.named_steps["vectorizer"].fit_transform = model.named_steps["vectorizer"].transform

pipeline.fit(X, y)
票数 3
EN

Stack Overflow用户

发布于 2019-01-22 18:11:34

您可以使用管道的一个子集,如

preprocess_pipeline =Pipeline(Pipeline.Best_estimator_.step:-1)#排除最后一步

然后

tmp = preprocess_pipeline.fit(x_train) normalized_x = tmp.fit_transform(x_train)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42139319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档