基于K210的MNIST手写数字识别
项目已开源链接: Github.
硬件平台
采用Maixduino开发板
在sipeed官方有售
软件平台
使用MaixPy环境进行单片机的编程
官方资源可在这里下载 链接: link.
安装方法在这里先不进行赘述
开发平台
操作系统:macOS系统
模型训练:tensorflow2.1 CPU版
模型转换工具:NNCase v0.2.0 Beta2
nncase下载地址:链接: Github.
让我们开始吧~!
1、配置模型开发环境
打开终端进入anoconda 使用conda create 命令新建虚拟环境
conda create -n tf2.1 python=3.7
激活虚拟环境
conda activate tf2.1
下载安装tensorflow
pip install tensorflow -i https://pypi.doubanio.com/simple/
安装完成后设置pycharm为解释器当前虚拟环境
测试一下吧~~
import tensorflow as tf
print(tf.__version__)
如果输出了正确的版本号就代表成功啦!!
2、模型的建立与训练
本次使用的深度学习的方法去识别手写的数字,这里采用LeNet5卷积神经网络进行模型的搭建。
首先什么是LeNet5呢,这张图很好的说明了网络的架构。简单来讲这个网络包含了两个卷积,池化层 和两个全连接层。
在模型的搭建时有一点需要注意,k210的kpu 最好使用1x1、3x3的卷积核,这样效率比较高。因此根据情况在代码中做调整即可。
具体代码如下:
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import datetime
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(x_train,y_train),(x_test,y_test) = mnist.load_data()
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
image_index = 1
print(y_train[image_index])
plt.imshow(x_train[image_index])
plt.show()
x_train = np.pad(x_train,((0,0),(2,2),(2,2)),'constant',constant_values=0)
x_test = np.pad(x_test,((0,0),(2,2),(2,2)),'constant',constant_values=0)
print(x_train.shape)
print(x_test.shape)
x_train = x_train.astype('float32')
x_train = x_train/255
x_test = x_test/255
x_train = x_train.reshape(x_train.shape[0],32,32,1)
x_test = x_test.reshape(x_test.shape[0],32,32,1)
print(x_train.shape)
print(