5-11、高斯核函数RBF
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from matplotlib.colors import ListedColormap
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x, y = datasets.make_moons(n_samples=1000, noise=0.25, random_state=2020) # 生成1000个数据样本
plt.figure()
plt.scatter(x[y == 0, 0], x[y == 0, 1], color="r")
plt.scatter(x[y == 1, 0], x[y == 1, 1], color="g")
plt.title('散点图')
plt.show()
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=2020)
# 绘制边界曲线
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1),
np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1)
)
x_new = np.c_[x0.ravel(), x1.ravel()]
y_pre = model.predict(x_new)
zz = y_pre.reshape(x0.shape)
# 设置颜色
cus = ListedColormap(["#BA55D3", "#FF69B4", "#FFE4C4"])
plt.contourf(x0, x1, zz, cmap=cus)
def RBFkernelSVC(gamma):#高斯核函数RBF
return Pipeline([
("std", StandardScaler()),
("svc", SVC(kernel="rbf", gamma=gamma))
])
sv = RBFkernelSVC(gamma=1)
sv.fit(x_train, y_train)
plot_decision_boundary(sv, axis=([-1.8, 2.5, -1.4, 1.8]))
plt.scatter(x[y == 0, 0], x[y == 0, 1], color="r")
plt.scatter(x[y == 1, 0], x[y == 1, 1], color="g")
plt.title('高斯核函数RBF')
plt.show()
# 打印出分数
print(sv.score(x_test, y_test))
d = datasets.load_iris()
x = d.data
y = d.target
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=2020)
sv = RBFkernelSVC(gamma=10)
sv.fit(x_train, y_train)
# 打印出分数
print(sv.score(x_test, y_test))