如何从sklearn的OneVsRest/OneVsOneClassifier中提取支持向量?
提取OneVsRestClassifier/OneVsOneClassifier中的支持向量
OneVsRestClassifier和OneVsOneClassifier属于元分类器,它们会为多分类任务训练多个二分类SVC子模型,因此本身没有support_vectors_属性。要获取支持向量,需要访问它们内部训练好的子分类器集合——estimators_属性。
针对OneVsRestClassifier的解决方案
训练完成后,estimators_会返回一个列表,每个元素对应一个二分类SVC模型(对应某一类与其他类的分类),直接访问每个子模型的support_vectors_即可:
model_linear = svm.SVC(kernel="linear") or_linear = OneVsRestClassifier(model_linear) or_linear.fit(X_train, y_train) # 遍历所有子分类器,提取支持向量 for idx, estimator in enumerate(or_linear.estimators_): print(f"第{idx+1}个子分类器的支持向量:") print(estimator.support_vectors_)
针对OneVsOneClassifier的解决方案
OneVsOneClassifier会为每一对类别训练一个二分类SVC模型,同样通过estimators_访问子模型:
oo_linear = OneVsOneClassifier(model_linear) oo_linear.fit(X_train, y_train) # 遍历所有子分类器,提取支持向量 for idx, estimator in enumerate(oo_linear.estimators_): print(f"第{idx+1}个子分类器的支持向量:") print(estimator.support_vectors_)
如果需要将所有子模型的支持向量合并,可以用numpy的concatenate方法:
import numpy as np all_support_vectors = np.concatenate([est.support_vectors_ for est in or_linear.estimators_]) print("所有支持向量合并结果:") print(all_support_vectors)
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

