手写数字识别python
时间: 2023-09-13 16:13:43 浏览: 70
以下是一个用Python实现手写数字识别的简单例子:
1. 导入所需库
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.neighbors import KNeighborsClassifier
```
2. 加载数据集
```python
digits = load_digits()
```
3. 数据集分割
```python
X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.2, random_state=0)
```
4. KNN模型训练
```python
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
```
5. 预测并输出分类报告
```python
y_pred = knn.predict(X_test)
print(classification_report(y_test, y_pred))
```
6. 可视化展示
```python
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(8, 8))
for ax, image, prediction in zip(axes.flatten(), X_test, y_pred):
ax.set_axis_off()
image = image.reshape(8, 8)
ax.imshow(image, cmap=plt.cm.gray_r)
ax.set_title(f'Prediction: {prediction}')
plt.show()
```
这是一个简单的示例,实际上手写数字识别涉及到的技术和算法还有很多,可以根据具体需求和实际情况进行相应的选择和调整。
阅读全文