纯Python通过逻辑回归实现手写数字分类

介绍

手写数字分类就是机器学习中的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

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值