SVM支持向量机python
线性可分的数据初探
生成一点线性可分的数据看看
- 利用sklearn中make_blobs函数,其参数为
- n_samples: int, optional (default=100) The total number of points equally divided among clusters. 待生成的样本的总数。
- **n_features: **int, optional (default=2) The number of features for each sample. 每个样本的特征数。
- centers: int or array of shape [n_centers, n_features], optional (default=3) The number of centers to generate, or the fixed center locations. 要生成的样本中心(类别)数,或者是确定的中心点。 要生成的样本中心(类别)数,或者是确定的中心点。
- cluster_std: float or sequence of floats, optional (default=1.0) The standard deviation of the clusters. 每个类别的方差,例如我们希望生成2类数据,其中一类比另一类具有更大的方差,可以将cluster_std设置为[1.0,3.0]。
- 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. - shuffle: boolean, optional (default=True) Shuffle the samples.
- 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_
只要支持向量不变,数据点增加无所谓。