OneVsRestClassifier を使用して、一連のコメントに対してマルチラベル分類を実行しようとしています。私の目的は、各コメントを可能なトピックのリストにタグ付けすることです。私のカスタム分類子は、手作業で精選された単語とそれに対応する csv 内のタグのリストを使用して、各コメントにタグを付けます。Bag of Words 手法から得られた結果と、VotingClassifier を使用してカスタム分類子を組み合わせようとしています。これが私の既存のコードの一部です:
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.ensemble import VotingClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.grid_search import GridSearchCV
from sklearn.linear_model import SGDClassifier
from sklearn.multiclass import OneVsRestClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MultiLabelBinarizer
class CustomClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, word_to_tag):
self.word_to_tag = word_to_tag
def fit(self, X, y=None):
return self
def predict_proba(self, X):
prob = np.zeros(shape=(len(self.word_to_tag), 2))
for index, comment in np.ndenumerate(X):
prob[index] = [0.5, 0.5]
for word, label in self.word_to_tag.iteritems():
if (label == self.class_label) and (comment.find(word) >= 0):
prob[index] = [0, 1]
break
return prob
def _get_label(self, ...):
# Need to have a way of knowing which label being classified
# by OneVsRestClassifier (self.class_label)
bow_clf = Pipeline([('vect', CountVectorizer(stop_words='english', min_df=1, max_df=0.9)),
('tfidf', TfidfTransformer(use_idf=False)),
('clf', SGDClassifier(loss='log', penalty='l2', alpha=1e-3, n_iter=5)),
])
custom_clf = CustomClassifier(word_to_tag_dict)
ovr_clf = OneVsRestClassifier(VotingClassifier(estimators=[('bow', bow_clf), ('custom', custom_clf)],
voting='soft'))
params = { 'estimator_weights': ([1, 1], [1, 2], [2, 1]) }
gs_clf = GridSearchCV(ovr_clf, params, n_jobs=-1, verbose=1, scoring='precision_samples')
binarizer = MultiLabelBinarizer()
gs_clf.fit(X, binarizer.fit_transform(y))
私の意図は、いくつかのヒューリスティックによって得られたこの手動でキュレーションされた単語のリストを使用して、bag of words のみを適用して得られた結果を改善することです。現在、OneVsRestClassifier を使用してラベルごとに CustomClassifier のコピーが作成されるため、予測中にどのラベルが分類されているかを知る方法を見つけるのに苦労しています。