介绍
手写数字分类就是机器学习中的Hello world。下面我用纯python代码实现手写数字分类。主要用的到知识有逻辑回归、梯度下降、sigmoid损失函数,前面的博客我都写过了。代码注释比较详细,具体看注释↓
代码
# coding=utf-8
import math
import numpy as np
import matplotlib.pyplot as plt
# 一个下载mnist数据的脚本,在我github上有
import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# 加载mnist手写数字训练集
x, y = mnist.train.next_batch(55000)
print(x.shape)
# 学习率
lr = 0.1
w = np.zeros((10, 784))
for j in range(10):
for i in range(len(x)):
# 梯度下降更新权值
w_grads = x[i] * np.atleast_2d(1 / (1 + math.e ** (-np.matmul(w, x[i]))) - y[i]).T / len(x[i])
w += -lr * w_grads
# 加载mnist手写数字测试集
x_test, y_test = mnist.test.next_batch(10000)
total, correct = 0, 0
# 测试模型正确率
for i in range(0, len(x_test)):
total += 1
a = np.matmul(w, x[i])
if y[i].argmax() == a.argmax():
correct += 1
print('正确率:', correct / total)
# 画图,直观看到执行结果
x_test, y_test = mnist.test.next_batch(25)
result = np.array([np.matmul(w, x) for x in x_test]).argmax(1)
for i in range(len(x_test)):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.imshow(np.reshape(x_test[i], (28, 28)))
plt.savefig('1.png')
plt.show()
print('识别结果:', result)
print('正确答案:', y_test.argmax(1))
执行结果
测试结果正确率只有88%,后面用到更高级算法,可以将正确率提高到99%
PS
我的github上有我的全部学习笔记,欢迎一起学习。github地址:https://github.com/js1219/ML-Learning-Notes.git