使用sklearn的鸢尾花数据集进行支持向量机分类
使用sklearn的鸢尾花数据集进行支持向量机分类
本示例使用sklearn的鸢尾花数据集,选择前两列特征进行支持向量机分类。
步骤:
- 导入必要的库
- 加载鸢尾花数据集
- 选择前两列特征作为输入,类别标签作为输出
- 使用
train_test_split将数据集分割为训练集和测试集,比例由用户输入,并设置random_state=1保证结果可重复 - 使用
SVC创建支持向量机模型,设置kernel='rbf',gamma=20,decision_function_shape='ovo' - 使用训练集拟合模型
- 使用
score()方法分别计算训练集和测试集的精度,并保留两位小数
代码如下:
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# 加载鸢尾花数据集
iris = datasets.load_iris()
# 选择前两列特征和类别标签
X = iris.data[:, :2]
y = iris.target
# 用户输入训练集分割比例
train_size = float(input('请输入训练集分割比例:'))
# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=train_size, random_state=1)
# 创建支持向量机模型
model = SVC(kernel='rbf', gamma=20, decision_function_shape='ovo')
# 使用训练集拟合模型
model.fit(X_train, y_train)
# 计算训练集和测试集的精度
train_accu = model.score(X_train, y_train)
test_accu = model.score(X_test, y_test)
# 打印结果
print(f'accu of model for train set is {train_accu:.2f}')
print(f'accu of model for test set is {test_accu:.2f}')
输入样例:
请输入训练集分割比例:0.6
输出样例:
accu of model for train set is 0.87
accu of model for test set is 0.65
原文地址: https://www.cveoy.top/t/topic/mMcH 著作权归作者所有。请勿转载和采集!