SVM 分类器的分类超平面的绘制

这里写图片描述

0.库的导入

# Load libraries
from sklearn.svm import LinearSVC
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
import numpy as np
from matplotlib import pyplot as plt

1.加载IrisFlower 数据集

# Iris flower 数据集有三个类别,四个特征
# 这里只导入两个类别和两个特征的数据
iris = datasets.load_iris()
X = iris.data[:100,:2]
y = iris.target[:100]

2.特征标准化

# Standarize features
scaler = StandardScaler()
X_std = scaler.fit_transform(X)

3.训练支持向量分类器

# Create support vector classifier
svc = LinearSVC(C=1.0)

# Train model
model = svc.fit(X_std, y)

4.绘制决策边界超平面

所有类别 0 为黑色,类别1 为浅灰色

超平面是决定新的观察值分类结果的决策边界

这条线上的划分为类别0,这条线下的划分为类别1

# 绘制数据点,不同类别不同颜色
color = ['black' if c == 0 else 'lightgrey' for c in y]
plt.scatter(X_std[:,0], X_std[:,1], c=color)

# 创建超平面(根据SVC的参数,求出直线的斜率与截距)
w = svc.coef_[0]
a = - w[0]/w[1]
xx = np.linspace(-2.5, 2.5)
yy = a * xx - (svc.intercept_[0])/w[1]

# Plot the hyperplane
plt.plot(xx, yy)
plt.axis("off"), plt.show();

output

5.说明

翻译自ChrisAlbon的博客
原文地址

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值