数据集

数据集下载MNIST

首先读取数据集, 并打印相关信息

包括

  • 图像的数量, 形状
  • 像素的最大, 最小值
  • 以及看一下第一张图片
path = 'MNIST/mnist.npz'
with np.load(path, allow_pickle=True) as f:
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test'] print(f'dataset info: shape: {x_train.shape}, {y_train.shape}')
print(f'dataset info: max: {x_train.max()}')
print(f'dataset info: min: {x_train.min()}') print("A sample:")
print("y_train: ", y_train[0])
# print("x_train: \n", x_train[0])
show_pic = x_train[0].copy()
show_pic = cv2.resize(show_pic, (28 * 10, 28 * 10))
cv2.imshow("A image sample", show_pic)
key = cv2.waitKey(0)
# 按 q 退出
if key == ord('q'):
cv2.destroyAllWindows()
print("show demo over")

转换为tf 数据集的格式, 并进行归一化

# convert to tf tensor
x_train = tf.convert_to_tensor(x_train, dtype=tf.float32) // 255.
x_test = tf.convert_to_tensor(x_test, dtype=tf.float32) // 255.
dataset_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset_train = dataset_train.batch(batch_size).repeat(class_num)

定义网络

在这里定义一个简单的全连接网络

def build_simple_net():
net = Sequential([
layers.Dense(256, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(class_num)
])
net.build(input_shape=(None, 28 * 28))
# net.summary()
return net

训练

使用 SGD 优化器进行训练

def train(print_info_step=250):
net = build_simple_net()
# 优化器
optimizer = optimizers.SGD(lr=0.01)
# 计算准确率
acc = metrics.Accuracy() for step, (x, y) in enumerate(dataset_train):
with tf.GradientTape() as tape:
# [b, 28, 28] => [b, 784]
x = tf.reshape(x, (-1, 28 * 28))
# [b, 784] => [b, 10]
out = net(x)
# [b] => [b, 10]
y_onehot = tf.one_hot(y, depth=class_num)
# [b, 10]
loss = tf.square(out - y_onehot)
# [b]
loss = tf.reduce_sum(loss) / batch_size # 反向传播
acc.update_state(tf.argmax(out, axis=1), y)
grads = tape.gradient(loss, net.trainable_variables)
optimizer.apply_gradients(zip(grads, net.trainable_variables)) if acc.result() >= 0.90:
net.save_weights(save_path)
print(f'final acc: {acc.result()}, total step: {step}')
break if step % print_info_step == 0:
print(f'step: {step}, loss: {loss}, acc: {acc.result().numpy()}')
acc.reset_states() if step % 500 == 0 and step != 0:
print('save model')
net.save_weights(save_path)

验证

验证在测试集的模型效果, 这里仅取出第一张进行验证

def test_dataset():
net = build_simple_net()
# 加载模型
net.load_weights(save_path)
# 拿到测试集第一张图片
pred_image = x_test[0]
pred_image = tf.reshape(pred_image, (-1, 28 * 28))
pred = net.predict(pred_image)
# print(pred)
print(f'pred: {tf.argmax(pred, axis=1).numpy()}, label: {y_test[0]}')

应用

分割手写数字, 并进行逐一识别

  • 先将图像二值化
  • 找到轮廓
  • 得到数字的坐标
  • 转为模型的需要的输入格式, 并进行识别
  • 显示
def split_number(img):
result = []
net = build_simple_net()
# 加载模型
net.load_weights(save_path) image = cv2.cvtColor(img.copy(), cv2.COLOR_RGB2GRAY)
ret, thresh = cv2.threshold(image, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 1, 2)
for cnt in contours[:-1]:
x, y, w, h = cv2.boundingRect(cnt) image = img[y:y+h, x:x+w]
image = cv2.resize(image, (28, 28)) pred_image = tf.convert_to_tensor(image, dtype=tf.float32) / 255.
pred_image = tf.reshape(pred_image, (-1, 28 * 28))
pred = net.predict(pred_image)
out = tf.argmax(pred, axis=1).numpy()
result = [out[0]] + result
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("demo", img)
print(result)
k = cv2.waitKey(0)
# 按 q 退出
if k == ord('q'):
pass
cv2.destroyAllWindows()

效果

单数字



多数字



附录

所有代码, 文件 tf2_mnist.py

import os
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, Sequential, optimizers, metrics # 屏蔽通知信息和警告信息
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 每批几张图片
batch_size = 2
# 类别数
class_num = 10
# 保存模型的路径
save_path = "./models/mnist.ckpt"
# 展示样例
show_demo = False
# 验证测试集
evaluate_dataset = False
# 是否训练
run_train = False
# 图片路径, 仅用于 detect_image(), 当为False时不识别
image_path = 'images/36.png' path = 'MNIST/mnist.npz'
with np.load(path, allow_pickle=True) as f:
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test'] if show_demo:
print(f'dataset info: shape: {x_train.shape}, {y_train.shape}')
print(f'dataset info: max: {x_train.max()}')
print(f'dataset info: min: {x_train.min()}') print("A sample:")
print("y_train: ", y_train[0])
# print("x_train: \n", x_train[0])
show_pic = x_train[0].copy()
show_pic = cv2.resize(show_pic, (28 * 10, 28 * 10))
cv2.imshow("A image sample", show_pic)
key = cv2.waitKey(0)
if key == ord('q'):
cv2.destroyAllWindows()
print("show demo over") # convert to tf tensor
x_train = tf.convert_to_tensor(x_train, dtype=tf.float32) // 255.
x_test = tf.convert_to_tensor(x_test, dtype=tf.float32) // 255.
dataset_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset_train = dataset_train.batch(batch_size).repeat(class_num) def build_simple_net():
net = Sequential([
layers.Dense(256, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(256, activation='relu'),
layers.Dense(class_num)
])
net.build(input_shape=(None, 28 * 28))
# net.summary()
return net def train(print_info_step=250):
net = build_simple_net()
# 优化器
optimizer = optimizers.SGD(lr=0.01)
# 计算准确率
acc = metrics.Accuracy() for step, (x, y) in enumerate(dataset_train):
with tf.GradientTape() as tape:
# [b, 28, 28] => [b, 784]
x = tf.reshape(x, (-1, 28 * 28))
# [b, 784] => [b, 10]
out = net(x)
# [b] => [b, 10]
y_onehot = tf.one_hot(y, depth=class_num)
# [b, 10]
loss = tf.square(out - y_onehot)
# [b]
loss = tf.reduce_sum(loss) / batch_size # 反向传播
acc.update_state(tf.argmax(out, axis=1), y)
grads = tape.gradient(loss, net.trainable_variables)
optimizer.apply_gradients(zip(grads, net.trainable_variables)) if acc.result() >= 0.90:
net.save_weights(save_path)
print(f'final acc: {acc.result()}, total step: {step}')
break if step % print_info_step == 0:
print(f'step: {step}, loss: {loss}, acc: {acc.result().numpy()}')
acc.reset_states() if step % 500 == 0 and step != 0:
print('save model')
net.save_weights(save_path) def test_dataset():
net = build_simple_net()
# 加载模型
net.load_weights(save_path)
# 拿到测试集第一张图片
pred_image = x_test[0]
pred_image = tf.reshape(pred_image, (-1, 28 * 28))
pred = net.predict(pred_image)
# print(pred)
print(f'pred: {tf.argmax(pred, axis=1).numpy()}, label: {y_test[0]}') def split_number(img):
result = []
net = build_simple_net()
# 加载模型
net.load_weights(save_path) image = cv2.cvtColor(img.copy(), cv2.COLOR_RGB2GRAY)
ret, thresh = cv2.threshold(image, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 1, 2)
for cnt in contours[:-1]:
x, y, w, h = cv2.boundingRect(cnt) image = img[y:y+h, x:x+w]
image = cv2.resize(image, (28, 28)) pred_image = tf.convert_to_tensor(image, dtype=tf.float32) / 255.
pred_image = tf.reshape(pred_image, (-1, 28 * 28))
pred = net.predict(pred_image)
out = tf.argmax(pred, axis=1).numpy()
result = [out[0]] + result
img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.imshow("demo", img)
print(result)
k = cv2.waitKey(0)
if k == ord('q'):
pass
cv2.destroyAllWindows() if __name__ == '__main__':
if run_train:
train()
elif evaluate_dataset:
test_dataset()
elif image_path:
image = cv2.imread(image_path)
# detect_image(image)
split_number(image)

linux-基于tensorflow2.x的手写数字识别-基于MNIST数据集的更多相关文章

  1. 基于Numpy的神经网络+手写数字识别

    基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...

  2. 手写数字识别——基于LeNet-5卷积网络模型

    在<手写数字识别——利用Keras高层API快速搭建并优化网络模型>一文中,我们搭建了全连接层网络,准确率达到0.98,但是这种网络的参数量达到了近24万个.本文将搭建LeNet-5网络, ...

  3. 【TensorFlow-windows】(四) CNN(卷积神经网络)进行手写数字识别(mnist)

    主要内容: 1.基于CNN的mnist手写数字识别(详细代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64. ...

  4. 【TensorFlow-windows】(三) 多层感知器进行手写数字识别(mnist)

    主要内容: 1.基于多层感知器的mnist手写数字识别(代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64. ...

  5. TensorFlow.NET机器学习入门【5】采用神经网络实现手写数字识别(MNIST)

    从这篇文章开始,终于要干点正儿八经的工作了,前面都是准备工作.这次我们要解决机器学习的经典问题,MNIST手写数字识别. 首先介绍一下数据集.请首先解压:TF_Net\Asset\mnist_png. ...

  6. 基于卷积神经网络的手写数字识别分类(Tensorflow)

    import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dat ...

  7. 基于多层感知机的手写数字识别(Tensorflow实现)

    import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_dat ...

  8. 吴裕雄--天生自然python机器学习:基于支持向量机SVM的手写数字识别

    from numpy import * def img2vector(filename): returnVect = zeros((1,1024)) fr = open(filename) for i ...

  9. 【TensorFlow-windows】(一)实现Softmax Regression进行手写数字识别(mnist)

    博文主要内容有: 1.softmax regression的TensorFlow实现代码(教科书级的代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3 ...

随机推荐

  1. route -n 讲解

    我们经常会出现临时添加路由,或者是路由重启路由丢失等导致网络不通的情况,上网查发现很多介绍或者没有实验跟进导致理解的时候很费劲的情况,可能人家认为是比较简单的事情了,但是很多不尽然,老手也不一定能很快 ...

  2. 使用nmtui命令解决network-scripts目录下无网卡对应配置文件问题

    //网卡通过命令ifconfig可以识别到,但是在配置文件目录下,没有该文件,一旦重启等配置了该地址的应用则可能会出现问题所以需要重新生成对应配置文件,我首先想到的就是用 nmtui 这个程序来重新生 ...

  3. 反射解决微信开发加解密illegal key size,不需要修改JDK jar包

    在微信开发时,消息接口时,涉及到消息加密,抛出了 java.security.InvalidKeyException: Illegal key size 的异常,异常堆栈如下: 按照网上的解决方案,都 ...

  4. 《手把手教你》系列基础篇(九十二)-java+ selenium自动化测试-框架设计基础-POM设计模式简介(详解教程)

    1.简介 页面对象模型(Page Object Model)在Selenium Webdriver自动化测试中使用非常流行和受欢迎,作为自动化测试工程师应该至少听说过POM这个概念.本篇介绍POM的简 ...

  5. 从零开始搭建GoLang语言开发环境

    更多干货文章,更多最新文章,欢迎到作者主博客 菜鸟厚非 一.安装 GoLang 1.1 下载 首先访问 https://go.dev/dl/ 下载 GoLang,下载完成后双击安装即可.如下: 1.2 ...

  6. Java继承实例解析

    Java继承 前言 继承是面向对象语法的三大特征之一.继承可以降低代码编写的冗余度,提高编程的效率.通过继承,子类获得了父类的成员变量和方法.一个子类如何继承父类的字段和方法,如何修改从父类继承过来的 ...

  7. Win10系统链接蓝牙设备

    1. 进入控制面板,选择 设备 2. 进入设备界面,删除已有蓝牙,如果蓝牙耳机已经链接其他设备,先断开链接 3. 点击添加蓝牙或其他设备 4. 选择蓝牙,选择你的蓝牙耳机名称

  8. Android开发的开始

    Android 软件 手机软件哦,目前只有一层外壳,进一步功能等待开发. 下载地址

  9. Redis源码漂流记(二)-搭建Redis调试环境

    Redis源码漂流记(二)-搭建Redis调试环境 一.目标 搭建Redis调试环境 简要理解Redis命令运转流程 二.前提 1.有一些c知识简单基础(变量命名.常用数据类型.指针等) 可以参考这篇 ...

  10. BottomNavigationView点击刷新问题

    BottomNavigationView点击刷新问题 问题: 项目中使用了BottomNavigationView作为底部导航栏. 点击item切换的时候发现会有闪烁现象出现. 原因: BottomN ...