首发极术社区
如对Arm相关技术感兴趣,欢迎私信aijishu20加入技术微信群。

流程一览

1.配置docker开发环境
2.训练水果分类模型
3.准备校正数据集
4.准备输入样本
5.修改目录内容及配置文件
6.运行仿真并验证结果
7.文件下载

1.配置docker开发环境

这个过程按照官方的教程来进行即可:

  • 首先下载docker镜像(自行解决网络问题): sudo docker pull zepan/zhouyi

  • 第一次运行镜像时: sudo docker run -i -t zepan/zhouyi /bin/bash

  • 后面再次进入容器前,首先查看容器的ID: docker ps,可以看到类似如下的信息,容器ID为ecf9748d25c7,可以只用前几位来表示它,如ecf

CONTAINER ID   IMAGE          COMMAND
ecf9748d25c7   zepan/zhouyi   "/bin/bash"
  • docker start ecf可以启动容器,docker stop ecf可以关闭容器
  • 容器运行后,输入命令docker exec -it ecf /bin/bash即可进入容器
  • 在部署过程中可能要在容器和主机之间拷贝文件,可以参考以下命令:
#  从主机拷贝文件到容器下的/root/目录
docker cp /Users/Desktop/output_ref.bin ecf:/root/
#  从容器拷贝文件到主机桌面目录
docker cp ecf:/root/output_ref.bin /Users/Desktop/
  • 在容器的/root/demos/目录下有tflite和pb的例程,可以运行进行环境的测试,这里我们将tflite文件夹复制到/root目录下,在此基础上进行后面的部署: cp /root/demos/tflite /root/tflite

2.训练水果分类模型

这里我使用了Kaggle上的一个项目作为参考,用Keras训练了一个MobileNetV2模型,可以用来对水果和蔬菜做分类,验证集准确率为98%左右。然后可以很方便地用Keras将模型保存为.h5文件,再用TFLiteConverter将其转换为.tflite文件。参考代码:

# 保存Keras模型
keras_file = 'keras_model.h5'
tf.keras.models.save_model(model, keras_file)# 转换模型为tflite格式
converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()# 保存模型
with open('model.tflite', 'wb') as f:f.write(tflite_model)

注意:在运行训练代码和转换代码时,最好把tensorflow版本设为1.15.5,以免后面发生其它错误。
✅ 获得keras_model.h5和model.tflite文件

3.准备校正数据集

校正数据集的处理方法要跟模型训练时输入数据的处理方法保持一致。
在模型训练时,输入数据集处理的方法为:

train_generator = tf.keras.preprocessing.image.ImageDataGenerator(# 将图像像素点的值从(0, 255)缩放到(-1, 1)preprocessing_function = lambda x: (x / 127.5) - 1
)

所以在准备校正数据集时,也要将图像像素缩放到(-1, 1):

import cv2
print(train_images.class_indices)
base_dir = '../input/fruit-and-vegetable-image-recognition/train/'filename_list = []
label_list = []for item in train_images.class_indices:class_dir = base_dir + item
#     print(train_images.class_indices[item])filenames = os.listdir(class_dir)for j in range(5):filename_list.append(f'{class_dir}/{filenames[j]}')label_list.append(train_images.class_indices[item])img_num = len(label_list)
# print(img_num, label_list)input_height = 224
input_width = 224
input_channel = 3images = np.zeros([img_num, input_height, input_width, input_channel], np.float32)
for file_name, img_idx in zip(filename_list, range(img_num)):   image = cv2.imread(file_name)
#     print(file_name, label_list[img_idx])image = cv2.resize(image, (input_height, input_width))image = np.array(image, dtype=np.float32)image = image / 127.5image = image - 1images[img_idx] = imagenp.save('dataset.npy', images)labels = np.array(label_list)
np.save('label.npy', labels)

✅ 获得dataset.npy和label.npy文件

4.准备输入样本

选取一张图片,对其做浮点预测,并将输出结果保存为output_ref.bin,将图片保存为input.bin

  • 预测并生成output_ref.bin
model = tf.keras.models.load_model('./keras_model.h5')
img_name = "../input/fruit-and-vegetable-image-recognition/train/mango/Image_13.jpg"
img = tf.keras.preprocessing.image.load_img(img_name, target_size=(224, 224), color_mode='rgb',
)
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array /= 127.5
img_array -= 1
print(img_array.max())
img_array = tf.expand_dims(img_array, 0)predictions = model.predict(img_array, verbose=1, steps=1)
pred = 255 * predictions
pred = pred.astype(np.uint8)
fw=open('output_ref.bin', 'wb')
fw.write(pred)
fw.close()
  • 将样本保存为input.bin
from PIL import Image
from matplotlib import pyplot as plt
import numpy as npinput_height=224
input_width=224
input_channel = 3
mean = [127.5, 127.5, 127.5]
var = 1img = Image.open(img_name)img1 = img.resize((input_width, input_height),Image.ANTIALIAS)
img_arr = (np.array(img1)-mean)/var
img_arr=img_arr.astype(np.int8)# 保存成仿真需要的bin文件
import struct
data=b''
for y in range(img_arr.shape[1]):for x in range(img_arr.shape[0]):data += struct.pack('bbb',img_arr[y,x,0],img_arr[y,x,1],img_arr[y,x,2])fw = open("input.bin", "wb")
fw.write(data)
fw.close()
print("save to input.bin OK")

✅ 获得output_ref.bin和input.bin文件

5.修改目录内容及配置文件

  • 经过上述步骤,我们得到了以下文件,将它们放到对应的文件夹(注意/root/tflite是我们在第一步时复制出来的文件夹):
    | 文件|路径|
    | — | — |
    | model.tflite|/root/tflite/model|
    | dataset.npy |/root/tflite/dataset|
    | label.npy |/root/tflite/dataset |
    | output_ref.bin | /root/tflite |
    | input.bin | /root/tflite/model |

  • /root/tflite/目录下新建fruit_classes.py,内容为:

class_names = '''apple
banana
beetroot
bell pepper
cabbage
capsicum
carrot
cauliflower
chilli pepper
corn
cucumber
eggplant
garlic
ginger
grapes
jalepeno
kiwi
lemon
lettuce
mango
onion
orange
paprika
pear
peas
pineapple
pomegranate
potato
raddish
soy beans
spinach
sweetcorn
sweetpotato
tomato
turnip
watermelon'''.split("\n")
  • 修改/root/tflite/quant_predict.py
from PIL import Image
import cv2
from matplotlib import pyplot as plt
import matplotlib.patches as patches
import numpy as np
import os
import fruit_classes as class_namecurrent_dir = os.getcwd()
label_offset = 0
outputfile = current_dir + '/output_mobilenet_v2.bin'
# 这里的np.uint8是根据模型实际的输出数据类型来确定的
# 可以在生成量化模型后,到/tmp目录下查看类型
npyoutput = np.fromfile(outputfile, dtype=np.uint8)
outputclass = npyoutput.argmax()
print(npyoutput.sum())
head5p = npyoutput.argsort()[-5:][::-1]labelfile = current_dir + '/output_ref.bin'
npylabel = np.fromfile(labelfile, dtype=np.uint8)
labelclass = npylabel.argmax()
print(npylabel.sum())
head5t = npylabel.argsort()[-5:][::-1]print("predict first 5 label:")
for i in head5p:print("    index %4d, prob %3d, name: %s"%(i, npyoutput[i], class_name.class_names[i-label_offset]))print("true first 5 label:")
for i in head5t:print("    index %4d, prob %3d, name: %s"%(i, npylabel[i], class_name.class_names[i-label_offset]))
# Show input picture
print('Detect picture save to result.jpeg')input_path = './model/input.bin'
npyinput = np.fromfile(input_path, dtype=np.int8)
image = np.clip(np.round(npyinput)+128, 0, 255).astype(np.uint8)
image = np.reshape(image, (224, 224, 3))
im = Image.fromarray(image)
im.save('result.jpeg')
  • 修改cfg文件,build和run文件均只需要修改[Parser]部分内容:
[Parser]
model_type = tflite
input_data_format = NHWC
model_name = mobilenet_v2
detection_postprocess =
model_domain = image_classification
input_model = ./model/model.tflite
input = input_2
input_shape = [1, 224, 224, 3]
output = dense_8/Softmax
output_dir = ./

其中input = input_2output = dense_8/Softmax需要与模型的实际输入输出保持一致,可以通过这个网页来可视化模型结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jyrBE43p-1628573869233)(/img/bV5db)]

6.运行仿真并验证结果

运行仿真:

aipubuild config/tflite_mobilenet_v2_run.cfg

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-I4SyPUB3-1628573869241)(/img/bV5dc)]
对比结果:

python quant_predict.py

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dpTeFKou-1628573869243)(/img/bV5dd)]
可以看到,量化后模型的预测结果与量化前模型的预测结果的top5一致,且top1的概率接近

7.文件下载

本文提到的所有文件及代码,可以从这里下载: tflite.zip(提取码: s9ri)
说明:

  1. 压缩包内的fruit-and-vegetable-classification.ipynb展示了模型的训练过程和各个重要文件的生成过程,可以在Kaggle上运行
  2. 压缩包内的tflite_test文件夹,请将其复制到docker下运行

相关阅读:

  • 【周易AIPU 仿真】一篇折腾r329的记录
  • 【R329开发板评测】R329烧录debian踩坑

【周易AIPU 仿真】基于MobileNetV2的水果分类模型在R329开发板上的部署相关推荐

  1. PaddleLite——将水果分类模型部署到树莓派

    本项目手把手带你实现了在树莓派端基于视频流的水果分类. 目录 1. VOC数据集的准备 2. 水果分类模型的训练 3. 树莓派上摄像头的调试和配置 4. 跑通Paddle-Lite-Demo 5. 部 ...

  2. 【周易AIPU 仿真】R329开发板(仿真)部署AIPU初体验

    首发极术社区 如对Arm相关技术感兴趣,欢迎私信aijishu20加入技术微信群. 操作系统:Ubuntu 版 本:20.04 LTS (18.04也一样) 假定当前目录:/root/demo/pb ...

  3. 【周易AIPU 仿真】R329 NASNet模型仿真测试

    首发极术社区 如对Arm相关技术感兴趣,欢迎私信aijishu20加入技术微信群. 一.系统环境 硬件环境:Intel® Core™ i7-8650U CPU @ 1.90GHz 2.11 GHz, ...

  4. 【周易AIPU 仿真】R329开发板模拟仿真

    首发极术社区 如对Arm相关技术感兴趣,欢迎私信aijishu20加入技术微信群. 基本思想:R329开发板可以免费申请,但是需要先做一下模拟仿真,因此在此记录一下仿真过程~ 我本想使用自己曾经训练的 ...

  5. 【周易AIPU 仿真】在R329上部署VGG_16网络模型

    首发极术社区 如对Arm相关技术感兴趣,欢迎私信aijishu20加入技术微信群. 前言 经过一周多时间的探索,参考了n篇历程,跑通了俩个网络模型,这里记录一下VGG_16网络模型的部署.全部操作都是 ...

  6. R语言使用yardstick包的conf_mat函数计算多分类(Multiclass)模型的混淆矩阵、并使用summary函数基于混淆矩阵输出分类模型评估的其它详细指标(kappa、npv等13个)

    R语言使用yardstick包的conf_mat函数计算多分类(Multiclass)模型的混淆矩阵(confusion matrix).并使用summary函数基于混淆矩阵输出分类模型评估的其它详细 ...

  7. 15 分钟搭建一个基于XLNET的文本分类模型——keras实战

    今天笔者将简要介绍一下后bert 时代中一个又一比较重要的预训练的语言模型--XLNET ,下图是XLNET在中文问答数据集CMRC 2018数据集(哈工大讯飞联合实验室发布的中文机器阅读理解数据,形 ...

  8. PaddlePaddle基本用法详解(二)、PaddelPaddle训练水果分类模型

    PaddlePaddle基本用法详解(二).PaddelPaddle训练分类模型 1.基本用法 2.训练水果分类模型 1.基本用法 2.训练水果分类模型 1.数据集预处理与模型定义代码: import ...

  9. elm分类器功能_基于ELM的情绪分类模型研究

    龙源期刊网 http://www.qikan.com.cn 基于 ELM 的情绪分类模型研究 作者:陈珊 来源:<价值工程> 2017 年第 04 期 摘要: 采用计算机进行情绪判断对实现 ...

最新文章

  1. iOS之深入解析数组遍历的底层原理和性能分析
  2. Java常用API(一)Object
  3. 处理Request 的方法中的形参务必加上@RequestParam 注解
  4. 数据库-分组语句及用法
  5. leetcode-136. 只出现一次的数字解法
  6. linuxpython拍照_linux下python抓屏实现方法 -电脑资料
  7. LeetCode Rearrange String k Distance Apart
  8. opencv漫水填充算法
  9. python爬虫工程师工作内容_爬虫岗位职责
  10. SecureCRT for Mac(SSH终端仿真工具)
  11. (转)Matlab映射表数据结构(containers.Map)
  12. Java word转pdf字体格式和样式变乱的问题
  13. 罗马数字转化阿拉伯数字
  14. GB/T 18487电动汽车充电领域国家标准解析 篇一(充电术语和定义)
  15. Java对接谷歌邮箱-代码及其谷歌邮箱账号配置
  16. 如何从初级程序员到中级程序员
  17. 用php上传头像的步骤,php怎么上传头像
  18. 百度收购快钱?消息人士说不大可能
  19. 最近玩喂喂我的小仓鼠吧,玩上瘾了……
  20. vue-router 快速返回上一页

热门文章

  1. 科笛集团冲刺港股:上半年亏2.5亿 红杉与云锋基金是股东
  2. 中国苏打石灰玻璃行业市场供需与战略研究报告
  3. GitHub - polaris-gslb/polaris-gslb: A free, open source GSLB (Global Server Load Balancing) solution
  4. 多路转接IO模型:多路转接多路复用
  5. iPhone 12拍照取消自动曝光方法教程
  6. iPhone 实用技巧 之 快速使用iTools安装ipa软件。本节简单介绍如何使用iTools安装在iPhone上安装ipa软件
  7. BUUCTF-MISC-[GXYCTF2019]SXMgdGhpcyBiYXNlPw==~zip
  8. beginning html5 微盘,Beginning WebGL for HTML5
  9. vsphere esxi设置定时自动关机脚本
  10. IPv4之发送接口: ip_queue_xmi()