<jupyter_start><jupyter_text>Day 14 Random Forest for Classifying Hand-written Digits 前面简单介绍过手写数字数据集,再一次使用这些数据，使用随机森林分类器解决这个问题:<jupyter_code>%matplotlib inline
%config InlineBackend.figure_format = 'svg'

import warnings

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()


# warnings.filterwarnings(action='ignore')
from sklearn.datasets import load_digits
digits = load_digits()
digits.keys()
# 设置图形对象
fig = plt.figure(figsize=(6, 6)) #英寸
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

# 画数字:每个数字是8像素×8像素
for i in range(64):
    ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
    ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest')
    
    # 用target值给图像作标注
    ax.text(0, 7, str(digits.target[i]))<jupyter_output><empty_output><jupyter_text>用随机森林快速对数字进行分类<jupyter_code>from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

Xtrain, Xtest, ytrain, ytest = train_test_split(digits.data, digits.target, random_state=0)
model = RandomForestClassifier(n_estimators=1000)
model.fit(Xtrain, ytrain)
ypred = model.predict(Xtest)<jupyter_output><empty_output><jupyter_text>看看分类器的分类结果报告:<jupyter_code>from sklearn import metrics
print(metrics.classification_report(ypred, ytest))<jupyter_output>precision    recall  f1-score   support

          0       1.00      0.97      0.99        38
          1       1.00      0.98      0.99        44
          2       0.95      1.00      0.98        42
          3       0.98      0.96      0.97        46
          4       0.97      1.00      0.99        37
          5       0.98      0.98      0.98        48
          6       1.00      1.00      1.00        52
          7       1.00      0.96      0.98        50
          8       0.94      0.98      0.96        46
          9       0.98      0.98      0.98        47

avg / total       0.98      0.98      0.98       450<jupyter_text>!!!准确率这么高!?  画出混淆矩阵:<jupyter_code>from sklearn.metrics import confusion_matrix
mat = confusion_matrix(ytest, ypred)
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False)
plt.xlabel('true label')
plt.ylabel('predicted label');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10437859354268023, 'fraction_numerical': 0.07120743034055728, 'mean_word_length': 2.5510204081632653, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '588676', 'license': 'MIT', 'n_tokens_mistral': 951, 'n_tokens_neox': 910, 'n_words': 170, 'path': 'Code/Day 14 Random Forest for Classifying Hand-written Digits.ipynb', 'repo_name': 'xuhaer/ML', 'size': '2261'}