算法伪代码
BEGIN
// (1) 加载Iris数据集并留出1/3样本作为测试集
加载 iris 数据集
设置 X = iris 特征
设置 y = iris 标签
使用 留出法 拆分 (X, y) 进入 (X_train, y_train) 和 (X_test, y_test),测试集占1/3,随机种子设为 42,按 y 进行分层
// (2) 使用训练集训练支持向量机模型
初始化 svm_model 为 SVC
拟合 svm_model 在 (X_train, y_train)
// (3) 使用五折交叉验证评估模型性能
初始化 skf 为 StratifiedKFold,n_splits = 5,洗牌 = True,随机种子设为 42
scores = 使用交叉验证计算 (svm_model, X_train, y_train, skf, 评分标准 = '准确率')
precision = 使用交叉验证计算 (svm_model, X_train, y_train, skf, 评分标准 = '精确率_宏')
recall = 使用交叉验证计算 (svm_model, X_train, y_train, skf, 评分标准 = '召回率_宏')
f1 = 使用交叉验证计算 (svm_model, X_train, y_train, skf, 评分标准 = 'F1_宏')
// 打印交叉验证结果
打印 "训练集准确度: " + 平均值(scores)
打印 "训练集精确度: " + 平均值(precision)
打印 "训练集召回率: " + 平均值(recall)
打印 "训练集F1值: " + 平均值(f1)
// (4) 使用测试集测试模型性能
y_pred = 预测(svm_model, X_test)
accuracy = 计算准确率(y_test, y_pred)
precision = 计算精确率(y_test, y_pred, 平均值 = '宏')
recall = 计算召回率(y_test, y_pred, 平均值 = '宏')
f1 = 计算F1值(y_test, y_pred, 平均值 = '宏')
// 打印测试结果
打印 "测试集准确度: " + accuracy
打印 "测试集精确度: " + precision
打印 "测试集召回率: " + recall
打印 "测试集F1值: " + f1
END
2. 算法主要代码
完整源代码\调用库方法(函数参数说明)
from sklearn import datasets
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import numpy as np
# (1)加载iris数据集,并留出1/3作为测试集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 使用留出法留出1/3的样本作为测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=42, stratify=y)
# (2)使用训练集训练支持向量机—SMO分类算法
svm_model = SVC()
svm_model.fit(X_train, y_train)
# (3)使用五折交叉验证对模型性能进行评估
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(svm_model, X_train, y_train, cv=skf, scoring='accuracy')
precision = cross_val_score(svm_model, X_train, y_train, cv=skf, scoring='precision_macro')
recall = cross_val_score(svm_model, X_train, y_train, cv=skf, scoring='recall_macro')
f1 = cross_val_score(svm_model, X_train, y_train, cv=skf, scoring='f1_macro')
# 打印交叉验证结果
print("训练集准确度: {:.3f}".format(np.mean(scores)))
print("训练集精确度: {:.3f}".format(np.mean(precision)))
print("训练集召回率: {:.3f}".format(np.mean(recall)))
print("训练集F1值: {:.3f}".format(np.mean(f1)))
# (4)使用测试集测试模型性能
y_pred = svm_model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='macro')
recall = recall_score(y_test, y_pred, average='macro')
f1 = f1_score(y_test, y_pred, average='macro')
# 打印测试结果
print("测试集准确度: {:.3f}".format(accuracy))
print("测试集精确度: {:.3f}".format(precision))
print("测试集召回率: {:.3f}".format(recall))
print("测试集F1值: {:.3f}".format(f1))
3. 训练结果截图(包括:准确率、精度(查准率)、召回率(查全率)、F1)
四、实验结果分析
1. 测试结果截图(包括:准确率、精度(查准率)、召回率(查全率)、F1)
2. 对比分析
训练集与测试集一致性:
训练集的各项性能指标(准确度、精确度、召回率和F1值)都很高,这表明模型在训练数据上拟合良好。
测试集的各项指标更是完美(1.00),说明模型能够很好地泛化到未见过的数据上。
过拟合与泛化能力:
由于测试集的表现优于训练集(尤其是高达1.00),这表示在本实验中,模型没有出现过拟合的迹象,而是成功学习到了数据的特征(虽然在真实应用中,完全的1.00很少见,且可能是数据集小或简单问题所导致的)。
浙公网安备 33010602011771号