我正在尝试在scikit-learn包中实现的不同分类器,以执行一些NLP任务。我用来执行分类的代码如下
def train_classifier(self, argcands):
# Extract the necessary features from the argument candidates
train_argcands_feats = []
train_argcands_target = []
for argcand in argcands:
train_argcands_feats.append(self.extract_features(argcand))
train_argcands_target.append(argcand["info"]["label"])
# Transform the features to the format required by the classifier
self.feat_vectorizer = DictVectorizer()
train_argcands_feats = self.feat_vectorizer.fit_transform(train_argcands_feats)
# Transform the target labels to the format required by the classifier
self.target_names = list(set(train_argcands_target))
train_argcands_target = [self.target_names.index(target) for target in train_argcands_target]
# Train the appropriate supervised model
self.classifier = LinearSVC()
#self.classifier = SVC(kernel="poly", degree=2)
self.classifier.fit(train_argcands_feats,train_argcands_target)
return
def execute(self, argcands_test):
# Extract features
test_argcands_feats = [self.extract_features(argcand) for argcand in argcands_test]
# Transform the features to the format required by the classifier
test_argcands_feats = self.feat_vectorizer.transform(test_argcands_feats)
# Classify the candidate arguments
test_argcands_targets = self.classifier.predict(test_argcands_feats)
# Get the correct label names
test_argcands_labels = [self.target_names[int(label_index)] for label_index in test_argcands_targets]
return zip(argcands_test, test_argcands_labels)
从代码中可以看出,我正在测试支持向量机分类器的两个实现:LinearSVC和带有多项式内核的SVC。 现在,为我的“问题”。使用LinearSVC时,我得到一个没有问题的分类:测试实例标有一些标签。但是,如果我使用多项式SVC,则所有测试实例都使用SAME标签进行标记。 我知道一个可能的解释是,简单地说,多项式SVC不是用于我的任务的适当分类器,这很好。我只想确保我正确使用多项式SVC。
感谢您提供的所有帮助/建议。
更新 根据答案中给出的建议,我已经更改了训练分类器的代码,以执行以下操作:
# Train the appropriate supervised model
parameters = [{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['poly'], 'degree': [2]}]
self.classifier = GridSearchCV(SVC(C=1), parameters, score_func = f1_score)
现在我收到以下消息:
ValueError: The least populated class in y has only 1 members, which is too few. The minimum number of labels for any class cannot be less than k=3.
这与我的训练数据中类别实例的不均匀分布有关,对吧?或者我是否错误地调用了该程序?
答案 0 :(得分:4)
在这两种情况下,您都应该使用grid search调整正则化参数C的值。你无法比较结果,否则一个好的C值可能会为另一个模型产生糟糕的结果。
对于多项式内核,您还可以网格搜索度数的最佳值(例如2或3或更多):在这种情况下,您应该同时网格搜索C和度。
修改强>:
这与我的训练数据中类别实例的不均匀分布有关,对吧?或者我是否错误地调用了该程序?
检查每个类至少有3个样本,以便能够StratifiedKFold
进行k == 3
交叉验证(我认为这是GridSearchCV
用于分类的默认CV)。如果你有更少,不要指望模型能够预测任何有用的东西。我建议每班至少100个样本(作为一个有点任意的经验法则,除非你处理少于10个特征的玩具问题,并且在类之间的决策边界有很多规律性。)