作者 | Karan Bhanot
来源 | Towards Data Science
编辑 | 代码医生团队
如果一直在阅读有关数据科学或机器学习的知识,那么一定遇到与MNIST数据集一起使用的文章和项目。数据集包括一组70,000个图像,其中每个图像是从0到9的手写数字。决定使用相同的数据集来了解如何微调机器学习模型参数可以产生差异。
本文解释了如何GridSearchCV找到该数据集的最佳拟合参数,并使用它们来提高准确性并改善混淆矩阵。可以在下面的GitHub存储库中找到代码:
https://github.com/kb22/Digit-Recognition-with-Parameter-Tuning
导入库和数据集
首先导入必要的库。训练和测试数据.csv在这里。数据集中的每一行由一个标签和784个像素值组成,以表示28x28图像。
https://www.kaggle.com/oddrationale/mnist-in-csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.cm import rainbow
%matplotlib inline
from sklearn.metrics import confusion_matrix, accuracy_score
from sklearn.ensemble import RandomForestClassifier
训练数据包括60,000个图像,而测试数据集包括10,000个图像。
print("Training data:")
print("Shape: {}".format(train_data.shape))
print("Total images: {}".format(train_data.shape[0]))
print("Testing data:")
print("Shape: {}".format(test_data.shape))
print("Total images: {}".format(test_data.shape[0]))
## OUTPUT:
# Training data:
# Shape: (60000, 785)
# Total images: 60000
# Testing data:
# Shape: (10000, 785)
# Total images: 10000
一旦有数据,从它得到的功能和标签并将其存储在train_X,train_y,test_X和test_y。
探索数据集
分析类分布
每个类的数据应该大致相同,以确保正确的模型训练。
train_labels = train_y.value_counts()
plt.figure(figsize = (12, 8))
cmap = rainbow(np.linspace(0, 1, train_labels.shape[0]))
plt.bar(train_labels.index.values, train_labels, color = cmap)
plt.xticks(train_labels.index.values)
plt.xlabel('Digits')
plt.ylabel('Count of images')
plt.title('Count of images for each digit (0 - 9)')
每个数字的图像数量(0-9)
如果看一下情节,每个数字的计数会有一些差异。然而差异并不是太大,模型仍然能够很好地训练数据。因此可以继续进行。
查看训练图像
看看图像实际是怎样的。从训练数据中随机选择10个图像并使用它进行显示plt.imshow()。
np.random.seed(0)
plt.figure(figsize = (20, 8))
for i in range(10):
index = np.random.randint(train_X.shape[0])
image_matrix = train_X.iloc[index].values.reshape(28, 28)
plt.subplot(2, 5, i+1)
plt.imshow(image_matrix, cmap=plt.cm.gray)
10从数据集中随机选择的图像
在10个随机图像中立即看到的是任何一种类型的数字之间的差异。看看上面10张图片中所有数字4的图片。第一个是粗体和直线,第二个是粗体和对角线,而第三个是细体和对角线。如果模型可以从数据中学习并实际检测出所有不同的样式,那将是非常了不起的。
应用机器学习
决定使用随机森林分类器训练数据并预测测试数据。使用了所有参数的默认值。
random_forest_classifier = RandomForestClassifier()
random_forest_classifier.fit(train_X,train_y)
pred_y = random_forest_classifier.predict(test_X)
接下来,使用预测,计算了准确度和混淆矩阵。
print("Accuracy: {}%".format(accuracy_score(test_y, pred_y)*100))
print("Confusion Matrix:")
print("{}".format(confusion_matrix(test_y, pred_y)))
## Output
# Accuracy: 94.42%
# Confusion Matrix:
# [[ 966 0 5 0 2 1 1 2 3 0]
# [ 0 1118 3 3 1 2 3 0 5 0]
# [ 8 4 977 9 5 1 4 14 10 0]
# [ 4 0 25 940 0 21 0 7 10 3]
# [ 3 2 3 2 931 0 9 3 7 22]
# [ 5 3 6 26 1 830 6 3 8 4]
# [ 11 3 3 2 6 8 918 0 7 0]
# [ 3 4 29 4 7 1 0 964 2 14]
# [ 9 0 11 23 16 14 9 6 874 12]
# [ 8 7 7 13 27 7 0 6 10 924]]
该模型的准确率达到94.4%。混淆矩阵表明该模型能够正确预测大量图像。接下来调整模型参数以尝试改进结果。
参数调整
为了确定模型的最佳参数值组合,使用了GridSearchCV。这是一个由sklearn库提供的方法,它允许定义一组希望为给定模型尝试的可能值,并且它训练数据并从参数值的组合中识别最佳估算器。
from sklearn.model_selection import GridSearchCV
param_grid = {
'n_estimators': [100, 200],
'max_depth': [10, 50, 100],
'min_samples_split': [2, 4],
'max_features': ['sqrt', 'log2']
}
grid = GridSearchCV(random_forest_classifier, param_grid = param_grid, cv = 5, verbose = 5, n_jobs = -1)
grid.fit(train_X, train_y)
best_estimator = grid.best_estimator_
在这种特殊情况下,决定为一些参数选择一系列值。估算器的数量可以是100或200,最大深度可以是10,50或100,最小样本分为2或4,最大特征可以基于sqrt或log2。
将可能的参数值传递为param_grid,并将交叉验证设置为5.设置verbose为5将日志输出到控制台,并且njobs为-1使模型使用机器上的所有核心。然后适合这个网格,并用它来找到最好的估算。
最后使用这个最佳模型来预测测试数据。
best_pred_y = best_estimator.predict(test_X)
print("Accuracy: {}%".format(accuracy_score(test_y, best_pred_y)*100))
print("Confusion Matrix:")
print("{}".format(confusion_matrix(test_y, best_pred_y)))
## Output
# Accuracy: 97.08%
# Confusion Matrix:
# [[ 971 0 1 0 0 1 3 1 3 0]
# [ 0 1122 3 3 1 2 2 1 1 0]
# [ 6 0 1000 6 3 0 3 9 5 0]
# [ 0 0 9 979 0 5 0 8 6 3]
# [ 1 0 1 0 955 0 6 0 2 17]
# [ 3 0 1 10 3 859 6 2 5 3]
# [ 8 3 0 0 3 4 937 0 3 0]
# [ 1 4 18 1 0 0 0 990 5 9]
# [ 4 0 5 8 3 8 3 4 931 8]
# [ 7 5 1 10 11 2 1 4 4 964]]
看一下上面的准确性,看到通过改变模型的参数,精度从94.42%提高到97.08%。混淆矩阵还表明更多图像被正确分类。
机器学习不仅仅是读取数据并应用多种算法,直到得到一个好的模型才能使用,但它还涉及对模型进行微调以使它们最适合手头的数据。
确定正确的参数是决定使用哪种算法并根据数据充分利用它的关键步骤之一。
结论
在本文中讨论了一个项目,通过选择最佳的参数值组合来提高随机森林分类器的准确性GridSearchCV。使用MNIST数据集并将准确度从94.42%提高到97.08%。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有