python - 从支持向量机返回最佳支持向量
问题描述
我正在使用来自 sklearn(在 Python 中)的支持向量分类器来找到一组“0”和“1”标记数据之间的最佳边界。
见:https ://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html
但是,我想在围绕边界线旋转数据后执行一些分析,因此我需要返回允许我定义线开始的属性。
我执行 SVC 如下:
相关进口:
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
我将分类器定义为:
clf = svm.SVC(kernel='linear',C = 1e-3 ,class_weight='balanced')
然后适合训练数据:
clf.fit(f_train, labels_train)
因此可以使用以下方法查看线性类边界:
plt.figure()
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = clf.decision_function(xy).reshape(XX.shape)
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
linestyles=['--', '-', '--'])
如中所示:https ://scikit-learn.org/stable/auto_examples/svm/plot_separating_hyperplane.html
但是打电话的时候:
clf.support_vectors_.shape
如果尝试将线性边界描述为输出具有形状,我不确定如何将输出解释为相关 (4485, 2)
任何有关返回允许我定义边界线的东西的帮助将不胜感激!
解决方案
基于Plotting 3D Decision Boundary From Linear SVMclf.intercept_
您可以使用和clf.coef_
属性获得边界线:
def decision_hyperplane(clf, x, y=None, dimension=2):
"""
Return a decision line (dimension 2, return y based on x) or a
decision plane (dimension 3, return z based on x and y).
Decision plane equation is wx + b = 0, so in 2d case:
w.dot(x) + b = w_x * x + w_y * y + b = 0
y = (-w_x * x - b) / w_y
In 3d:
w_x * x + w_y * y + w_z * z + b = 0
z = (-w_x * x - w_y * y - b) / w_z
"""
if dimension == 2:
return (-clf.intercept_[0] - clf.coef_[0][0] * x) / clf.coef_[0][1]
elif dimension == 3:
return (-clf.intercept_[0] - clf.coef_[0][0] * x - clf.coef_[0][1] * y) / clf.coef_[0][2]
如果您将它与这样的代码一起使用
ax.plot(xx, decision_hyperplane(clf, xx), color='red')
推荐阅读
- c# - 在 C# 中从 Azure Data Lake 读取数据
- java - Spring PostMethod 从 UTC 返回日期
- java - 二叉搜索树中序迭代器下一个方法
- ios - 如何在 iOS 上的视频聊天中添加音乐背景?
- python - 为什么请求返回的 HTML 与真实页面的 HTML 不同?
- python - Python 将列表转换为 numpy 数组进行处理?
- arduino - 如何使用 FreeRTOS 上的队列从一个任务到另一个任务发送和接收字符?
- python - 如何在我的 Discord Bot 中修复我的 datetime 命令?
- kubernetes - Istio -- 删除 istio-control-plane 进程被冻结
- android - 如何使用 Android Accessibility Services 获得点击的 View Elements?