帮我改进一下 from sklearn.neighbors import KNeighborsClassifier from sklearn.datasets import load_digits from sklearn import svm, metrics from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.metrics import plot_confusion_matrix from sklearn.naive_bayes import GaussianNB #使绘图支持中文字符 from matplotlib import rcParams rcParams['font.family'] = 'SimHei' plt.rcParams['axes.unicode_minus'] = False # In[2]: digits = load_digits() data = digits.data print(data[0]) print(digits.images[0]) print(digits.target[0]) plt.imshow(digits.images[0]) plt.show() # In[3]: train_x, test_x, train_y, test_y = train_test_split(data, digits.target, test_size=0.3, random_state=82) print(train_x) gnb = GaussianNB() gnb.fit(train_x, train_y) print("训练集得分: %.4lf" % gnb.score(train_x, train_y)) print("测试集得分: %.4lf" % gnb.score(test_x, test_y)) print(gnb.predict(data)) plot_confusion_matrix(gnb, test_x, test_y) plt.show() # In[5]: ################################################################# fig = plt.figure(figsize=(6,13)) for i in range(40): y_pred = gnb.fit(train_x, train_y).predict([data[i]]) plt.subplot(8,5,i+1) plt.imshow(digits.images[i], interpolation='none') plt.title("%d---->%d"%(digits.target[i],y_pred)) plt.show()
时间: 2024-04-15 17:24:51 浏览: 132
以下是改进后的代码:
```python
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import plot_confusion_matrix
from sklearn.naive_bayes import GaussianNB
import matplotlib.pyplot as plt
import numpy as np
# 使绘图支持中文字符
from matplotlib import rcParams
rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
# 加载手写数字数据集
digits = load_digits()
data = digits.data
print(data[0])
print(digits.images[0])
print(digits.target[0])
plt.imshow(digits.images[0])
plt.show()
# 划分训练集和测试集
train_x, test_x, train_y, test_y = train_test_split(data, digits.target, test_size=0.3, random_state=82)
print(train_x)
# 使用高斯朴素贝叶斯进行训练和预测
gnb = GaussianNB()
gnb.fit(train_x, train_y)
train_score = gnb.score(train_x, train_y)
test_score = gnb.score(test_x, test_y)
print("训练集得分: %.4lf" % train_score)
print("测试集得分: %.4lf" % test_score)
print(gnb.predict(data))
plot_confusion_matrix(gnb, test_x, test_y, display_labels=digits.target_names)
plt.title("混淆矩阵")
plt.colorbar(label="样本数量")
plt.show()
# 绘制数字和预测结果的子图
fig, axes = plt.subplots(8, 5, figsize=(6, 13))
for i, ax in enumerate(axes.flat):
y_pred = gnb.predict([data[i]])
ax.imshow(digits.images[i], interpolation='none')
ax.set_title("%d---->%d" % (digits.target[i], y_pred))
ax.axis('off')
plt.tight_layout()
plt.show()
```
这里使用了高斯朴素贝叶斯分类器(`GaussianNB`),并计算了训练集得分和测试集得分。在绘制混淆矩阵时,使用了手写数字的类别标签作为显示标签。同时,在绘制数字和预测结果的子图时,添加了轴标签以提高可读性。
希望对你有所帮助!
阅读全文