# 导入必要的库 from sklearn import datasets from sklearn.model_selection import train_test_split, cross_validate from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score import numpy as np# (1)加载数据集并划分数据集为训练集和测试集 iris = datasets.load_iris() # 加载 iris 数据集 X = iris.data # 特征值 y = iris.target # 目标值# 使用train_test_split函数进行数据集分割,留出1/3的样本作为测试集 # stratify=y 参数确保训练集和测试集中各类别的比例相同(同分布取样) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3.0, random_state=42, stratify=y)# (2)初始化朴素贝叶斯分类器并训练 gnb = GaussianNB() # 创建高斯朴素贝叶斯分类器实例 gnb.fit(X_train, y_train) # 使用训练集训练分类器# (3)使用五折交叉验证评估模型性能 # scoring参数指定要计算的评分指标 cv_results = cross_validate(gnb, X_train, y_train, cv=5, scoring=['accuracy', 'precision_macro', 'recall_macro', 'f1_macro'])# 输出交叉验证结果的平均值 print(f"交叉验证准确度均值: {np.mean(cv_results['test_accuracy'])}") print(f"交叉验证精度均值: {np.mean(cv_results['test_precision_macro'])}") print(f"交叉验证召回率均值: {np.mean(cv_results['test_recall_macro'])}") print(f"交叉验证F1值均值: {np.mean(cv_results['test_f1_macro'])}")# (4)使用测试集评估模型性能 y_pred = gnb.predict(X_test) # 使用测试集预测 # 计算并打印测试集上的各项性能指标 print(f"测试集准确度: {accuracy_score(y_test, y_pred)}") print(f"测试集精度: {precision_score(y_test, y_pred, average='macro')}") print(f"测试集召回率: {recall_score(y_test, y_pred, average='macro')}") print(f"测试集F1值: {f1_score(y_test, y_pred, average='macro')}")# 提交作业时需要打包源代码,命名为:学号姓名-任务6.zip