【机器学习】基础入门(3)SVM支持向量机及代码实现

1 支持向量机SVM

一篇非常好的SVM理论讲解(点这里)

1.1 支持向量机介绍

STEP 1:构建数据集

import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_blobs

# 散点图可视化
X, y = make_blobs(n_samples=60, centers=2, random_state=0, cluster_std=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap=plt.cm.Paired)

在这里插入图片描述

make_blobs模块构造数据集
sklearn.datasets.make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, center_box=(-10.0, 10.0), shuffle=True, random_state=None)

  • n_samples: int, optional (default=100),待生成的样本的总数
  • n_features: int, optional (default=2),每个样本的特征数
  • centers: int or array of shape [n_centers, n_features], optional (default=3),要生成的样本中心(类别)数,或者是确定的中心点
  • cluster_std: float or sequence of floats, optional (default=1.0),每个类别的方差,例如我们希望生成2类数据,其中一类比另一类具有更大的方差,可以将cluster_std设置为[1.0,3.0]

STEP 2:线性分类器

# 画散点图
X, y = make_blobs(n_samples=60, centers=2, random_state=0, cluster_std=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap=plt.cm.Paired)
x_fit = np.linspace(0, 3) #将(0,3)等距离分为50份

# 画函数(可能会有多种分法)
y_1 = 1 * x_fit + 0.8
plt.plot(x_fit, y_1, '-c')

y_2 = -0.3 * x_fit + 3
plt.plot(x_fit, y_2, '-k')

plt.show()

在这里插入图片描述

np.linspace:主要用来创建等差数列
numpy.linspace(start, stop, num, endpoint=True, retstep=False, dtype=None, axis=0)
在start和stop之间返回均匀间隔的数据

  • start:返回样本数据开始点
  • stop:返回样本数据结束点
  • num:生成的样本数据量,默认为50
  • endpoint:True则包含stop;False则不包含stop
  • retstep:如果为True则结果会给出数据间隔
    dtype:输出数组类型
  • dtype:输出数组类型

STEP 3:测试新数据分类情况

# 画散点图
X, y = make_blobs(n_samples=60, centers=2, random_state=0, cluster_std=0.4)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap=plt.cm.Paired)
# 在散点图上标记新加入的红色节点(3,2.8)为<
plt.scatter([3], [2.8], c='#cccc00', marker='<', s=100, cmap=plt.cm.Paired)
x_fit = np.linspace(0, 3) #将(0,3)等距离分为50份

# 画函数
y_1 = 1 * x_fit + 0.8
plt.plot(x_fit, y_1, '-c')

y_2 = -0.3 * x_fit + 3
plt.plot(x_fit, y_2, '-k')

plt.show()

在这里插入图片描述
可以看到,此时黑色的线会把这个新的数据集分错,蓝色直线分类正确。
However上面这个例子的给出带有主观性,如何客观地评判两种分类方式的健壮性呢?

STEP 4:分类器优劣判断——最大间隔

# 画散点图
X, y = make_blobs(n_samples=60, centers=2, random_state=0, cluster_std=0.4)
plt.scatter
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值