深度学习入门篇——手把手教你用TensorFlow训练模型

人工智能 深度学习
Tensorflow在更新1.0版本之后多了很多新功能,其中放出了很多用tf框架写的深度网络结构(https://github.com/tensorflow/models ),大大降低了开发难度,利用现成的网络结构,无论fine-tuning还是重新训练方便了不少。

[[206688]]

导语

Tensorflow在更新1.0版本之后多了很多新功能,其中放出了很多用tf框架写的深度网络结构(https://github.com/tensorflow/models ),大大降低了开发难度,利用现成的网络结构,无论fine-tuning还是重新训练方便了不少。最近笔者终于跑通TensorFlow Object Detection API的ssd_mobilenet_v1模型,这里记录下如何完整跑通数据准备到模型使用的整个过程,相信对自己和一些同学能有所帮助。

Object Detection API提供了5种网络结构的预训练的权重,全部是用COCO数据集进行训练,这五种模型分别是SSD+mobilenet、SSD+inception_v2、R-FCN+resnet101、faster RCNN+resnet101、faster RCNN+inception+resnet101。各个模型的精度和计算所需时间如下。下面及介绍下如何使用Object Detection去训练自己的模型。

 

这里TensorFlow的安装就不再说明了,网上的教程一大把,大家可以找到很详尽的安装TensorFlow的文档。

训练前准备:

使用protobuf来配置模型和训练参数,所以API正常使用必须先编译protobuf库,这里可以下载直接编译好的pb库(https://github.com/google/protobuf/releases ),解压压缩包后,把protoc加入到环境变量中:

  1. $ cd tensorflow/models 
  2.  
  3. $ protoc object_detection/protos/*.proto --python_out=.  

(我是把protoc加到环境变量中,遇到找不到*.proto文件的报错,后来把protoc.exe放到models/object_detection目录下,重新执行才可以)

然后将models和slim(tf高级框架)加入python环境变量:

  1. PYTHONPATH=$PYTHONPATH:/your/path/to/tensorflow/models:/your/path/to/tensorflow/models/slim 

数据准备:

数据集需要转化成PASCAL VOC结构,API提供了create_pascal_tf_record.py,把VOC结构数据集转换成.record格式。不过我们发现更简单的方式,Datitran提供一种更简单生产.record格式的方法。

首先需要先要标注图像相应标签,这里可以使用labelImg工具。每标注一张样本,即生成一个xml的标注文件。然后,把这些标注的xml文件,按训练集与验证集分别放置到两个目录下,在Datitran提供了xml_to_csv.py脚本。这里只要指定标注的目录名即可。接下来,然后需要我们把对应的csv格式转换成.record格式。

 

  1. def main(): 
  2.     # image_path = os.path.join(os.getcwd(), 'annotations'
  3.     image_path = r'D:\training-sets\object-detection\sunglasses\label\test' 
  4.     xml_df = xml_to_csv(image_path) 
  5.     xml_df.to_csv('sunglasses_test_labels.csv'index=None) 
  6.     print('Successfully converted xml to csv.' 

调用generate_tfrecord.py,注意要指定–csv_input与–output_path这两个参数。执行下面命令:

  1. python generate_tfrecord.py --csv_input=sunglasses_test_labels.csv --output_path=sunglass_test.record 

这样就生成了训练及验证用的train.record与test.record。接下来指定标签名称,仿照models/ object_detection/data/ pet_label_map.pbtxt,重新创建一个文件,指定标签名。

  1. item { 
  2.   id: 1 
  3.   name'sunglasses' 
  4.  

训练:

根据自己的需要,选择一款用coco数据集预训练的模型,把前缀model.ckpt放置在待训练的目录,这里meta文件保存了graph和metadata,ckpt保存了网络的weights,这几个文件表示预训练模型的初始状态。

打开ssd_mobilenet_v1_pets.config文件,并做如下修改:

num_classes:修改为自己的classes num

 

将所有PATH_TO_BE_CONFIGURED的地方修改为自己之前设置的路径(共5处)

 

其他参数均保持默认参数。

准备好上述文件后就可以直接调用train文件进行训练。

  1. python object_detection/train.py \ 
  2. --logtostderr \ 
  3. --pipeline_config_path= D:/training-sets /data-translate/training/ssd_mobilenet_v1_pets.config \ 
  4. --train_dir=D:/training-sets/data-translate/training  

TensorBoard监控:

通过tensorboard工具,可以监控训练过程,输入西面指令后,在浏览器输入localhost:6006(默认)即可。

  1. tensorboard --logdir= D:/training-sets/data-translate/training  

 

 

 

这里面有很多指标曲线,甚至有模型网络架构,笔者对于这里面很多指标含义还没有弄明白,不过感觉出TensorBoard这个工具应该是极其强大。不过我们可以通过Total_Loss来看整体训练的情况。

 

从整体上看,loss曲线确实是收敛的,整体的训练效果还是满意的。另外,TensorFlow还提供了训练过程中利用验证集验证准确性的能力,但是笔者在调用时,仍有些问题,这里暂时就不详细说明了。

Freeze Model模型导出:

查看模型实际的效果前,我们需要把训练的过程文件导出,生产.pb的模型文件。本来,tensorflow/python/tools/freeze_graph.py提供了freeze model的api,但是需要提供输出的final node names(一般是softmax之类的***一层的激活函数命名),而object detection api提供提供了预训练好的网络,final node name并不好找,所以object_detection目录下还提供了export_inference_graph.py。

  1. python export_inference_graph.py \ 
  2. --input_type image_tensor 
  3. --pipeline_config_path D:/training-sets /data-translate/training/ssd_mobilenet_v1_pets.config \ 
  4. --trained_checkpoint_prefix D:/training-sets /data-translate/training/ssd_mobilenet_v1_pets.config /model.ckpt-* \ 
  5. --output_directory D:/training-sets /data-translate/training/result  

导出完成后,在output_directory下,会生成frozen_inference_graph.pb、model.ckpt.data-00000-of-00001、model.ckpt.meta、model.ckpt.data文件。

调用生成模型:

目录下本身有一个调用的例子,稍微改造如下:

  1. import cv2 
  2. import numpy as np 
  3. import tensorflow as tf 
  4. from object_detection.utils import label_map_util 
  5. from object_detection.utils import visualization_utils as vis_util 
  6.  
  7.  
  8. class TOD(object): 
  9.     def __init__(self): 
  10.         self.PATH_TO_CKPT = r'D:\lib\tf-model\models-master\object_detection\training\frozen_inference_graph.pb' 
  11.         self.PATH_TO_LABELS = r'D:\lib\tf-model\models-master\object_detection\training\sunglasses_label_map.pbtxt' 
  12.         self.NUM_CLASSES = 1 
  13.         self.detection_graph = self._load_model() 
  14.         self.category_index = self._load_label_map() 
  15.  
  16.     def _load_model(self): 
  17.         detection_graph = tf.Graph() 
  18.         with detection_graph.as_default(): 
  19.             od_graph_def = tf.GraphDef() 
  20.             with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb'as fid: 
  21.                 serialized_graph = fid.read() 
  22.                 od_graph_def.ParseFromString(serialized_graph) 
  23.                 tf.import_graph_def(od_graph_def, name=''
  24.         return detection_graph 
  25.  
  26.     def _load_label_map(self): 
  27.         label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS) 
  28.         categories = label_map_util.convert_label_map_to_categories(label_map, 
  29.                                                                     max_num_classes=self.NUM_CLASSES, 
  30.                                                                     use_display_name=True
  31.         category_index = label_map_util.create_category_index(categories) 
  32.         return category_index 
  33.  
  34.     def detect(self, image): 
  35.         with self.detection_graph.as_default(): 
  36.             with tf.Session(graph=self.detection_graph) as sess: 
  37.                 # Expand dimensions since the model expects images to have shape: [1, None, None, 3] 
  38.                 image_np_expanded = np.expand_dims(image, axis=0) 
  39.                 image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0'
  40.                 boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0'
  41.                 scores = self.detection_graph.get_tensor_by_name('detection_scores:0'
  42.                 classes = self.detection_graph.get_tensor_by_name('detection_classes:0'
  43.                 num_detections = self.detection_graph.get_tensor_by_name('num_detections:0'
  44.                 # Actual detection. 
  45.                 (boxes, scores, classes, num_detections) = sess.run( 
  46.                     [boxes, scores, classes, num_detections], 
  47.                     feed_dict={image_tensor: image_np_expanded}) 
  48.                 # Visualization of the results of a detection. 
  49.                 vis_util.visualize_boxes_and_labels_on_image_array( 
  50.                     image, 
  51.                     np.squeeze(boxes), 
  52.                     np.squeeze(classes).astype(np.int32), 
  53.                     np.squeeze(scores), 
  54.                     self.category_index, 
  55.                     use_normalized_coordinates=True
  56.                     line_thickness=8) 
  57.  
  58.         cv2.namedWindow("detection", cv2.WINDOW_NORMAL) 
  59.         cv2.imshow("detection", image) 
  60.         cv2.waitKey(0) 
  61.  
  62. if __name__ == '__main__'
  63.     image = cv2.imread('image.jpg'
  64.     detecotr = TOD() 
  65.     detecotr.detect(image)  

下面是一些图片的识别效果:

 

 

 

End. 

责任编辑:庞桂玉 来源: 36大数据
相关推荐

2022-10-19 14:30:59

2022-08-04 10:39:23

Jenkins集成CD

2021-08-09 13:31:25

PythonExcel代码

2009-04-22 09:17:19

LINQSQL基础

2021-08-02 23:15:20

Pandas数据采集

2021-02-02 13:31:35

Pycharm系统技巧Python

2012-01-11 13:40:35

移动应用云服务

2021-12-11 20:20:19

Python算法线性

2020-03-08 22:06:16

Python数据IP

2011-03-28 16:14:38

jQuery

2021-02-06 14:55:05

大数据pandas数据分析

2021-02-04 09:00:57

SQLDjango原生

2017-01-18 09:04:13

TensorFlow图像识别

2021-05-17 21:30:06

Python求均值中值

2017-10-29 21:43:25

人脸识别

2021-01-30 10:37:18

ScrapyGerapy网络爬虫

2009-08-27 18:10:58

PHP绘制3D图形

2022-03-29 11:11:11

TortoisGitGitee码云

2021-01-27 21:55:13

代码参数值ECharts

2021-06-23 07:16:06

buildroot Linux内核根文件系统
点赞
收藏

51CTO技术栈公众号