实验要求:
1.提取Iris数据集前两个属性,和0,1两个类别,形成新的实验数据
2.分别使用line、poly、 rbf三 种不同核函数对提取数据集进行分类,
比较三种不同核函数的分类精度,并编辑分类边界线
实验实现
# 导包
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
from sklearn.svm import SVC
iris = load_iris()
# 提取前两个属性
x = iris.data[:, :2]
# 提取0,1两个类别
y = iris.target
new_x = x[y < 2]
new_y = y[y < 2]
# 形成新数据集
new_iris = (new_x, new_y)
# 定义三种不同的核函数
kernels = ['linear', 'poly', 'rbf']
# 绘制子图布局
fig, sub = plt.subplots(1, 3, figsize=(12, 4))
# 遍历每种核函数
for i, kernel in enumerate(kernels):
# 创建SVC模型并指定核函数
clf = SVC(kernel=kernel)
# 训练模型
clf.fit(new_x, new_y)
# 获取分类精度
score = clf.score(new_x