KNN手写数字识别案例
本章会介绍如何使用knn模型进行手写数字识别,该案例的学习重点是放在如何数据处理,并非该模型的应用
介绍:每张图片都是28*28像素组成的,即:我们的csv文件中每一行都有784个像素点,表示图片(每个像素)的颜色,最终构成图像
加载相应的库
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import joblib
from collections import Counter #Counter 是 Python 内置的计数器工具,用来快速统计一个序列里每个元素出现的次数,返回一个类似字典的统计结果
from sklearn.metrics import accuracy_score
# 扩展:忽略警告
import warnings
warnings.filterwarnings('ignore',module='sklearn')
# 参1:忽略警告;参2:忽略的模块
一、定义函数,接收用户传入的索引,显示该索引对应的图片
def show_digit(idx):
# 1.读取数据集,获取到源数据
df = pd.read_csv('手写数字识别.csv')
#print(df) #(42000行 * 785 列)
# 2. 判断传入的索引是否越界
if idx < 0 or idx >=len(df) - 1:
print('索引越界!')
return
# 3. 走这里,说明没有越界,就正常获取数据
x = df.iloc[:,1:]
y = df.iloc[:,0]
# 4. 查看用户传入的索引对应的图片
print(f'该图片对应的数字是:{y.iloc[idx]}')
print(f'查看所有标签的分布情况:{Counter(y)}')
# 5. 查看下 x 的形状
print(x.iloc[idx].shape) # (784,) 想办法把(784,)转换成(28,28)
print(x.iloc[idx].values)
# 6. 把(784,),转换成(28,28)
x = x.iloc[idx].values.reshape(28,28)
print(x.shape)
# 7.具体的绘制灰度图的动作
plt.imshow(x,cmap='gray') # 灰度图
# imshow = image show,专门用来把二维数字矩阵渲染成图片显示出来。
#第一个参数 x 就是你的图片二维数组 (28,28),代表每个位置像素亮度。
#cmap='gray'
#cmap:colormap 颜色映射
#'gray':用灰度色系渲染
#数值越小 → 越黑
#数值越大 → 越白
plt.axis('off') # 不显示坐标轴
二、定义函数,训练模型,并保存训练好的模型
def train_model():
# 1. 加载数据集
df = pd.read_csv('手写数字识别.csv')
# 2. 数据的预处理
# 2.1 拆分出特征列
x = df.iloc[:,1:]
# 2.2 拆分出标签列
y = df.iloc[:,0]
# 2.3 打印出特征和标签的形状
print(f'x的形状:{x.shape}')
print(f'y的形状:{y.shape}')
# 2.4 对特征列(拆分前)进行归一化.
x = x / 255
# 2.5. 拆分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=23,stratify=y)
# 3.模型训练
# 3.1 创建模型对象
estimator = KNeighborsClassifier(n_neighbors=3)
# 3.2 训练模型
estimator.fit(x_train,y_train)
# 4.模型评估
print(f'准确率:{estimator.score(x_test,y_test)}')
print(f'准确率:{accuracy_score(y_test,estimator.predict(x_test))}')
# 5. 保存模型
# 参1:模型对象;参2:模型保存的路径;# pkl:pandas独有的文件类型
joblib.dump(estimator, '手写数字识别.pkl')
print('模型保存成功!')
三、定义函数,测试模型
def use_model():
# 1.加载图片
x = plt.imread('demo.png') #28*28 像素;plt.imread() 是 matplotlib 提供的图片读取函数
# 2.绘制图片
plt.imshow(x, cmap='gray')
plt.axis('off')
plt.show()
# 3.加载模型
estimator = joblib.load('手写数字识别.pkl')
# 4. 模型预测
# 4.1 查看数据集转换
print(x.shape)
print(x.reshape(1,-1).shape) # 转成1行n列
# 4.2 具体的转换动作,记得归一化
x = x.reshape(1,-1)
# 4.3 模型预测
y_pre = estimator.predict(x)
# 5. 打印预测结果
print(f'预测值为:{y_pre}')
四、运行函数
show_digit(9)
train_model()
use_model()

浙公网安备 33010602011771号