我正在尝试使用一个vs其余分类器包装器创建一个多标签分类器。
我将管道用于TFIDF和分类器。
在拟合管道时,我必须按类别循环遍历数据,然后每次都对管道进行拟合以对每个类别进行预测。
现在,我要导出此图像,就像通常使用pickle或joblib导出拟合模型一样。
示例:
pickle.dump(clf,'clf.pickle')
如何使用管道执行此操作?即使我腌制管线,但每次我要预测新关键字时,是否仍需要调整管线?
示例:
pickle.dump(pipeline,'pipeline.pickle')
pipeline = pickle.load('pipeline.pickle')
for category in categories:
pipeline.fit(X_train, y_train[category])
pipeline.predict(['kiwi'])
print (predict)
如果在加载管道后跳过pipeline.fit(X_train, y_train[category])
,则只会在预测中获得单个值数组。如果适合管道,我将得到一个三值数组。
此外,如何将网格搜索合并到导出管道中?
原始数据
keyword class1 class2 class3
"orange apple" 1 0 1
"lime lemon" 1 0 0
"banana" 0 1 0
categories = ['class1','class2','class3']
管道
SVC_pipeline = Pipeline([
('tfidf', TfidfVectorizer(stop_words=stop_words)),
('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
])
Gridsearch(不知道如何将其整合到管道中)
parameters = {'tfidf__ngram_range': [(1, 1), (1, 2)],
'tfidf__use_idf': (True, False),
'tfidf__max_df': [0.25, 0.5, 0.75, 1.0],
'tfidf__max_features': [10, 50, 100, 250, 500, 1000, None],
'tfidf__stop_words': ('english', None),
'tfidf__smooth_idf': (True, False),
'tfidf__norm': ('l1', 'l2', None),
}
grid = GridSearchCV(SVC_pipeline, parameters, cv=2, verbose=1)
grid.fit(X_train, y_train)
拟合管道
for category in categories:
print('... Processing {}'.format(category))
SVC_pipeline.fit(X_train, y_train[category])
# compute the testing accuracy
prediction = SVC_pipeline.predict(X_test)
print('Test accuracy is {}'.format(accuracy_score(y_test[category], prediction)))
答案 0 :(得分:0)
OneVsRestClassifier在内部适合每个类一个分类器。因此,您不应该像在
中那样为每个类调整管道for category in categories:
pipeline.fit(X_train, y_train[category])
pipeline.predict(['kiwi'])
print (predict)
您应该做这样的事情
SVC_pipeline = Pipeline([
('tfidf', TfidfVectorizer()), #add your stop_words
('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)),
])
SVC_pipeline.fit(["apple","boy","cat"],np.array([[0,1,1],[1,1,0],[1,1,1]]))
您现在可以使用
保存模型pickle.dump(SVC_pipeline,open('pipeline.pickle', 'wb'))
稍后您可以使用以下方法加载模型并进行预测
obj = pickle.load(open('pipeline.pickle', 'rb'))
obj.predict(["apple","boy","cat"])
您可以先使用MultiLabelBinarizer对多类标签进行二值化处理,然后再将它们传递给合适的方法
示例:
from sklearn.preprocessing import MultiLabelBinarizer
y = [['c1','c2'],['c3'],['c1'],['c1','c3'],['c1','c2','c3']]
mb = MultiLabelBinarizer()
y_encoded = mb.fit_transform(y)
SVC_pipeline.fit(["apple","boy","cat", "dog", "rat"], y_encoded)
grid = GridSearchCV(SVC_pipeline, {'tfidf__use_idf': (True, False)}, cv=2, verbose=1)
grid.fit(["apple","boy","cat", "dog", "rat"], y_encoded)
# Save the pipeline
pickle.dump(grid,open('grid.pickle', 'wb'))
# Later load it back and make predictions
grid_obj = pickle.load(open('grid.pickle', 'rb'))
grid_obj.predict(["apple","boy","cat", "dog", "rat"])