有没有一种方便的机制来锁定科学工具包学习管道中的步骤,以防止它们在pipeline.fit()上重新部署?例如:
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所示),它的拟合方法什么也不做,它的变换方法是预拟合变换器的变换。这是唯一的办法吗?
发布于 2017-06-23 03:50:24
纵观整个代码,在管道对象中似乎没有任何东西具有这样的功能:在管道上调用.fit()会导致在每个阶段上使用.fit()。
我能想到的最好的快速解决方案是用猴子来修补舞台的装配功能:
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)发布于 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)
https://stackoverflow.com/questions/42139319
复制相似问题