import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split, learning_curve from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score # 1. 加载 digits 数据集 digits = load_digits() X, y = digits.data, digits.target # 打印数据形状 print(f"输入特征维度: {X.shape}") print(f"目标变量维度: {y.shape}") # 2. 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) print("\n--- 数据划分情况 ---") print(f"训练集大小: {X_train.shape 0 } 条记录") print(f"测试集大小: {X_test.shape 0 } 条记录") # 3. 定义函数用于绘制学习曲线 def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None): """ 绘制学习曲线 :param estimator: 模型实例 :param title: 图形标题 :param X: 特征矩阵 :param y: 标签数组 :param ylim: 设置 y 轴范围 (可选) :param cv: 交叉验证折数 """ plt.figure(figsize=(8, 6)) plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training Examples") plt.ylabel("Score") # 获取不同样本规模下的训练误差和验证误差 train_sizes, train_scores, val_scores = learning_curve( estimator, X, y, cv=cv, scoring='accuracy', n_jobs=-1, train_sizes=np.linspace(0.1, 1.0, 10), shuffle=True, random_state=42) # 平均每组的结果 train_scores_mean = np.mean(train_scores, axis=1) val_scores_mean = np.mean(val_scores, axis=1) # 绘图 plt.grid() plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training Accuracy") plt.plot(train_sizes, val_scores_mean, 'o-', color="g", label="Cross-validation Accuracy") plt.legend(loc="best") return plt # 4. 初始化高斯朴素贝叶斯模型并绘制学习曲线 model = GaussianNB() # 创建模型实例 plot_learning_curve(model, "Learning Curve of Gaussian Naive Bayes on Digits Dataset", X_train, y_train, cv=5) # 显示图形 plt.show() # 5. 测试模型性能(额外部分) model.fit(X_train, y_train) # 在训练集上拟合模型 y_pred = model.predict(X_test) # 对测试集进行预测 test_accuracy = accuracy_score(y_test, y_pred) # 计算准确率 print(f"\n测试集上的准确率: {test_accuracy:.4f}") 检查有无错误
时间: 2025-03-18 22:03:58 浏览: 50
你的代码整体结构清晰,并涵盖了从加载数据、划分训练集和测试集到绘制学习曲线及评估模型性能的主要步骤。不过,存在一些小问题需要修正:
---
### **发现的问题**
1. **打印信息拼接错误**
在 `train_test_split` 后面的两行中:
```python
print(f"训练集大小: {X_train.shape 0 } 条记录")
print(f"测试集大小: {X_test.shape 0 } 条记录")
```
这里的 `{X_train.shape 0}` 和 `{X_test.shape 0}` 写法有问题。正确的应该是通过索引来访问 shape 的第一个元素(即样本数),例如 `{X_train.shape[0]}`。
修改后的版本应为:
```python
print(f"训练集大小: {X_train.shape[0]} 条记录")
print(f"测试集大小: {X_test.shape[0]} 条记录")
```
2. **学习曲线函数中的默认值说明不够明确**
函数 `plot_learning_curve` 中的部分参数如 `cv` 默认值未提供,建议在注释中标明该参数的作用以及推荐设置。
3. **随机性控制是否充分?**
尽管你在许多地方设置了 `random_state=42` 等固定种子值,但在某些位置仍可以进一步增强一致性(如 `learning_curve` 参数中的 `shuffle=True` 已经包含一定的随机化操作)。如果希望完全一致,可以在脚本开头显式地加入全局随机种子设定:
```python
import numpy as np
np.random.seed(42)
```
---
### **改进版完整代码**
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split, learning_curve
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
# 全局随机种子初始化
np.random.seed(42)
# 1. 加载 digits 数据集
digits = load_digits()
X, y = digits.data, digits.target
# 打印数据形状
print(f"输入特征维度: {X.shape}")
print(f"目标变量维度: {y.shape}")
# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
print("\n--- 数据划分情况 ---")
print(f"训练集大小: {X_train.shape[0]} 条记录") # 正确格式化字符串
print(f"测试集大小: {X_test.shape[0]} 条记录")
# 3. 定义函数用于绘制学习曲线
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=5): # 添加 cv 默认值
"""
绘制学习曲线
:param estimator: 模型实例
:param title: 图形标题
:param X: 特征矩阵
:param y: 标签数组
:param ylim: 设置 y 轴范围 (可选)
:param cv: 交叉验证折数,默认为5
"""
plt.figure(figsize=(8, 6))
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training Examples")
plt.ylabel("Score")
# 获取不同样本规模下的训练误差和验证误差
train_sizes, train_scores, val_scores = learning_curve(
estimator, X, y, cv=cv, scoring='accuracy', n_jobs=-1,
train_sizes=np.linspace(0.1, 1.0, 10), shuffle=True, random_state=42)
# 平均每组的结果
train_scores_mean = np.mean(train_scores, axis=1)
val_scores_mean = np.mean(val_scores, axis=1)
# 绘图
plt.grid()
plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training Accuracy")
plt.plot(train_sizes, val_scores_mean, 'o-', color="g", label="Cross-validation Accuracy")
plt.legend(loc="best")
return plt
# 4. 初始化高斯朴素贝叶斯模型并绘制学习曲线
model = GaussianNB() # 创建模型实例
plot_learning_curve(model, "Learning Curve of Gaussian Naive Bayes on Digits Dataset", X_train, y_train, cv=5)
# 显示图形
plt.show()
# 5. 测试模型性能(额外部分)
model.fit(X_train, y_train) # 在训练集上拟合模型
y_pred = model.predict(X_test) # 对测试集进行预测
test_accuracy = accuracy_score(y_test, y_pred) # 计算准确率
print(f"\n测试集上的准确率: {test_accuracy:.4f}")
```
---
### § 改进点总结 §
1. 固定了打印语句中的语法错误。
2. 增加了全局随机种子以提高实验结果的一致性和复现性。
3. 注解更加详细,便于初学者理解每个模块的功能与意义。
---
###
阅读全文
相关推荐














