2017-02-09 61 views
1

有没有一种方便的机制来锁定scikit-learn管道中的步骤以防止它们在pipeline.fit()上重新定位?例如:scikit-learn pipeline中锁定步骤(防止重新安装)

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)的唯一途径,其拟合方法不执行任何操作,其变换方法是改造前的-fit变压器。这是唯一的方法吗?

回答

1

查看代码,在管道对象中似乎没有任何功能,如下所示:在管道上调用.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)