SVM支持向量机和美丽的画图方法

线性可分的数据初探

生成一点线性可分的数据看看

  • 利用sklearn中make_blobs函数,其参数为
    1. n_samples: int, optional (default=100) The total number of points equally divided among clusters. 待生成的样本的总数。
    2. **n_features: **int, optional (default=2) The number of features for each sample. 每个样本的特征数。
    3. centers: int or array of shape [n_centers, n_features], optional (default=3) The number of centers to generate, or the fixed center locations. 要生成的样本中心(类别)数,或者是确定的中心点。 要生成的样本中心(类别)数,或者是确定的中心点。
    4. cluster_std: float or sequence of floats, optional (default=1.0) The standard deviation of the clusters. 每个类别的方差,例如我们希望生成2类数据,其中一类比另一类具有更大的方差,可以将cluster_std设置为[1.0,3.0]。
    5. center_box: pair of floats (min, max), optional (default=(-10.0, 10.0))
      The bounding box for each cluster center when centers are generated at random.
    6. shuffle: boolean, optional (default=True) Shuffle the samples.
    7. random_state: int, RandomState instance or None, optional (default=None)
      If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
      简而言之,选择生成样本的个数,特征数,类别数,类方差就足够用了
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_blobs   #类数据的生成  
X, y = make_blobs(n_samples=50,n_features=2,centers = 2,
                  random_state=0, cluster_std=0.60)
print(X.shape)	#完全是自己想看一看X的格式
plt.scatter(X[:, 0], X[:, 1], c=y, s=50,marker='o',cmap='summer')

生成数据的散点图

什么样的直线可以分开这些点呢

plt.figure(figsize = (10,6))
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plt.plot([0.6], [2.1], 'x', color='blue', markeredgewidth=3, markersize=10)

for m, b in [(1.1, 0.65), (0.5, 1.6), (-0.2, 2.9)]:
    plt.plot(xfit, m * xfit + b,)

plt.xlim(-1, 3.5)

选取了三条直线,均可以将这两类点分离。直观上,X点归属于哪一类,线就应该相应的变化。
在这里插入图片描述

SVM的独特思想:最小间隔最大化

直观理解

plt.figure(figsize = (8,5))
xfit = np.linspace(-1, 3.5)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')

for m, b, d in [(1, 0.65, 0.33), (0.5, 1.6, 0.55), (-0.2, 2.9, 0.2)]:
    yfit = m * xfit + b
    plt.plot(xfit, yfit, )
    plt.fill_between(xfit, yfit - d, yfit + d, edgecolor='blue',
                     color='#AAAAAA', alpha=0.5)

plt.xlim(-1, 3.5);

在这里插入图片描述

本质上就是阴影部分的区域最大化,分类边界到最近的点的距离最大化。

训练

from sklearn.svm import SVC    # "Support vector classifier"
model = SVC(kernel='linear')   #kernel选择线性的
model.fit(X, y)

进行绘图

#绘图函数
def plot_svc_decision_function(model, ax=None, plot_support=True):
    """Plot the decision function for a 2D SVC"""
    if ax is None:
        ax = plt.gca()
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    
    # create grid to evaluate model
    x = np.linspace(xlim[0], xlim[1], 30)
    y = np.linspace(ylim[0], ylim[1], 30)
    Y, X = np.meshgrid(y, x)  
    xy = np.vstack([X.ravel(), Y.ravel()]).T
    P = model.decision_function(xy).reshape(X.shape)
    
    # plot decision boundary and margins
    ax.contour(X, Y, P, colors='k',
               levels=[-1, 0, 1], alpha=0.5,
               linestyles=['--', '-', '--'])
    
    # plot support vectors
    if plot_support:
        ax.scatter(model.support_vectors_[:, 0],
                   model.support_vectors_[:, 1],
                   s=300, linewidth=1, facecolors='black');
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
plt.figure(figsize = (10,8))
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='autumn')
plot_svc_decision_function(model)

在这里插入图片描述

  • 这条线就是我们希望得到的决策边界啦

  • 观察发现有3个黑色的点点,它们恰好都是边界上的点就是我们的support vectors(支持向量)

  • 在Scikit-Learn中, 它们存储在这个位置 support_vectors_(一个属性)

model.support_vectors_

在这里插入图片描述

只要支持向量不变,数据点增加无所谓。

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用支持向量机SVM)进行二分类时,可以通过绘制决策边界来可视化分类结果。下面是一个简单的示例代码,用于绘制线性可分离的二分类数据集的SVM决策边界: ```python import numpy as np import matplotlib.pyplot as plt from sklearn import svm # 创建线性可分离的二分类数据集 X = np.array([[1, 2], [2, 1], [2, 3], [3, 2]]) y = np.array([0, 0, 1, 1]) # 创建SVM分类器对象 clf = svm.SVC(kernel='linear') # 训练模型 clf.fit(X, y) # 绘制决策边界 # 确定坐标轴的范围 x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # 生成网格点坐标 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) # 预测网格点的标签 Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # 绘制决策边界和训练样本点 plt.contourf(xx, yy, Z, cmap=plt.cm.Paired, alpha=0.8) plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) # 设置坐标轴标签和标题 plt.xlabel('X1') plt.ylabel('X2') plt.title('SVM Classification') # 显示图形 plt.show() ``` 上述代码中,首先创建了一个线性可分离的二分类数据集(X和y)。然后,使用`svm.SVC`创建了一个SVM分类器对象,并使用`fit`方法对模型进行训练。接下来,通过生成网格点坐标和预测网格点的标签,绘制了决策边界和训练样本点。最后,通过调用`show`方法显示图形。 请注意,以上示例代码仅适用于线性可分离的数据集。对于非线性可分离的数据集,可以使用不同的SVM核函数(例如多项式核函数或高斯核函数)来绘制决策边界。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值