我正在尝试使用 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.
这与我的训练数据中类实例分布不均有关,对吗?还是我错误地调用了过程?
最佳答案
在这两种情况下,您都应该使用 grid search 调整正则化参数 C 的值.否则您无法比较结果,因为一个模型的良好 C 值可能会对另一个模型产生糟糕的结果。
对于多项式内核,您还可以网格搜索度数的最佳值(例如 2 或 3 或更多):在这种情况下,您应该同时网格搜索 C 和度数。
编辑:
This has something to do with the uneven distribution of class' instances in my training data, right? Or am I calling the procedure incorrectly?
检查每个类至少有 3 个样本,以便能够使用 k == 3
进行 StratifiedKFold
交叉验证(我认为这是使用的默认 CV GridSearchCV
用于分类)。如果你有更少的东西,不要指望模型能够预测任何有用的东西。我会建议每个类至少 100 个样本(作为一个有点武断的最小界限经验法则,除非你处理的玩具问题少于 10 个特征并且在类之间的决策边界中有很多规律性)。
顺便说一句,请始终将完整的回溯粘贴到问题/错误报告中。否则,可能没有必要的信息来诊断正确的原因。
关于python - 在 scikit-learn 中使用具有多项式内核的支持向量分类器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12163362/