from sklearn.datasets import make_circles
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import numpy as np, matplotlib.pyplot as mp
# 创建随机样本、数据标准化
X, y = make_circles(noise=.1, factor=.4)
X = StandardScaler().fit_transform(X)
# 建模、训练
for e, kernel in enumerate(['linear', 'rbf'], 1):
clf = SVC(kernel=kernel)
clf.fit(X, y)
# 可视化
mp.subplot(1, 2, e) # 散点图
mp.scatter(X[:, 0], X[:, 1], s=40, c=y)
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, .01), np.arange(y_min, y_max, .01))
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
mp.contourf(xx, yy, Z, 0, alpha=.2) # 等高线图
mp.show()
相关文章: