Object Detection Api使用记录

tensorflow object detection api 详细实践教程 最近由于研究方向的更换,接触到了目标检测(Object Detection)领域,觉得很有意思,并且阅读了该方向的相关经典文献,包括Fast-RCNN、Faster-RCNN、SSD、YOLO以及RetinaNet等。但是对于读研狗或者读博狗的我们来说,复现别人代码并且能够得到在公开数据集上和原作者相近甚至相同的实验结果对于我们做研究甚至以后的工作来说是至关重要的。个人觉得目标检测方向是多个细化方... 阅读详情

0. Ubuntu安装tensorflow-gpu

有关于ubuntu下使用anaconda安装tensorflow-gpu的方法可以参考我这篇文章ubuntu一行命令在Anaconda下安装tensorflow-gpu
安装好之后,tensorflow默认的路径为~/anaconda3/lib/site-packages/tensorflow

1.object detection API下载地址及目录

https://github.com/tensorflow/models
文件下载下来得到models-master.zip
解压之后,将其放在安装好的tensorflow文件夹下,并且将models-master改名字为models,object_detection路径为models/research/object_detection下。

最终得到的我们需要的目录结构为:~/anaconda3/lib/site-packages/tensorflow/models/research/object_detection

2. protoc对object_detection/protos下的文件进行编译

在ubuntu下查看protoc版本

protoc --version

tensorflow object detection API要求protoc版本为2.6.0以上,否则会编译失败,如果版本过低,需要进行升级,升级好之后就可以进行编译了,我的版本是3.6.0。编译命令为:

cd ~/anaconda3/lib/python3.5/site-packages/tensorflow/models/research/
protoc object_detection/protos/*.proto --python_out=.

3.添加环境变量

tensorflow/models/research/ 和 tensorflow/models/research/slim 目录需要添加到PYTHONPATH环境变量中.

gedit ~/.bashrc                     #打开.bashrc

添加环境变量

export PYTHONPATH="/home/leo/anaconda3/lib/python3.5/site-packages/tensorflow/models/research:$PYTHONPATH"
export PYTHONPATH="/home/leo/anaconda3/lib/python3.5/site-packages/tensorflow/models/research/slim:$PYTHONPATH"
source ~/.bashrc                 #使修改立即生效

4.测试object_detection api:

cd ~/anaconda3/lib/python3.5/site-packages/tensorflow/models/research
python object_detection/builders/model_builder_test.py

如果返回ok表明配置正确
在这里插入图片描述

5. 测试已经训练好的模型

COCO数据集是Microsoft发布的用于图像识别训练的数据集,图像中的目标都经过准确的分割及位置定位的,共包括90类目标。Object Detection API默认提供了5个预训练模型,它们都是COCO数据集训练的:
SSD + MobileNet
Inception V2 + SSD
ResNet101 + R-CNN
ResNet101 + Faster R-CNN
Inception-ResNet V2 + Faster R-CNN

这些预训练模型下载地址为:
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md

*新建一个文件夹my_object_detection

  • 新建my_object_detection/models/
    将下载的ssd_mobilenet_v1_coco_2018_01_28解压到其中。形成my_object_detection/models/ssd_mobilenet_v1_coco_2018_01_28/目录结构

  • 新建my_object_detection/images/
    在里面新建test_images/,形成my_object_detection/images/test_images/目录结构
    在里面放两张测试图片或者将原object_detection/test_images/中的两张图片复制过来

  • 新建my_object_detection/data/,将原object_detection/data/中的mscoco_label_map.pbtxt文件复制过来

  • 新建my_object_detection/leo_object_detection_APP_ssd_mobilenet_v1_coco_2018_01_28.py,内容如下:

#encoding:utf-8
import tensorflow as tf
import numpy as np
 
import os
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_utils
 
#下载下来的模型的目录
MODEL_DIR = 'models/ssd_mobilenet_v1_coco_2018_01_28'
#下载下来的模型的文件
MODEL_CHECK_FILE = os.path.join(MODEL_DIR, 'frozen_inference_graph.pb')
#数据集对于的label
MODEL_LABEL_MAP = os.path.join('data', 'mscoco_label_map.pbtxt')
#数据集分类数量,可以打开mscoco_label_map.pbtxt文件看看
MODEL_NUM_CLASSES = 90
 
#这里是获取实例图片文件名,将其放到数组中
PATH_TO_TEST_IMAGES_DIR = 'images/test_images'
TEST_IMAGES_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3)]
 
#输出图像大小,单位是in
IMAGE_SIZE = (12, 8)
 
tf.reset_default_graph()
 
#将模型读取到默认的图中
with tf.gfile.GFile(MODEL_CHECK_FILE, 'rb') as fd:
    _graph = tf.GraphDef()
    _graph.ParseFromString(fd.read())
    tf.import_graph_def(_graph, name='')
 
#加载COCO数据标签,将mscoco_label_map.pbtxt的内容转换成
# {1: {'id': 1, 'name': u'person'}...90: {'id': 90, 'name': u'toothbrush'}}格式
label_map = label_map_util.load_labelmap(MODEL_LABEL_MAP)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=MODEL_NUM_CLASSES)
category_index = label_map_util.create_category_index(categories)
 
#将图片转化成numpy数组形式
def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
 
#在图中开始计算
detection_graph = tf.get_default_graph()
with tf.Session(graph=detection_graph) as sess:
    for image_path in TEST_IMAGES_PATHS:
        print(image_path)
        #读取图片
        image = Image.open(image_path)
        #将图片数据转成数组
        image_np = load_image_into_numpy_array(image)
        #增加一个维度
        image_np_expanded = np.expand_dims(image_np, axis=0)
        #下面都是获取模型中的变量,直接使用就好了
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        #存放所有检测框
        boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        #每个检测结果的可信度
        scores = detection_graph.get_tensor_by_name('detection_scores:0')
        #每个框对应的类别
        classes = detection_graph.get_tensor_by_name('detection_classes:0')
        #检测框的个数
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')
        #开始计算
        (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],
                                                            feed_dict={image_tensor : image_np_expanded})
        #打印识别结果
        print(num_detections)
        print(boxes)
        print(classes)
        print(scores)
 
        #得到可视化结果
        vis_utils.visualize_boxes_and_labels_on_image_array(
            image_np,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8
        )
        #显示
        plt.figure(figsize=IMAGE_SIZE)
        plt.imshow(image_np)
        plt.show()

运行结果:
在这里插入图片描述

在这里插入图片描述

6. 初步训练自己的模型

下载数据集:
下载PASCAL VOC 2012数据集,这是别人已经整理好的数据集,一共有17125张图片,每张图片都有标注,标注的内容包括人、动物、交通工具、家具等20个类别。
将下载好的数据集解压到my_object_detection/images/文件夹下,形成my_object_detection/images/VOCdevkit/VOC2012/的目录结构,VOC2012/目录包含了五个文件夹,其中JPEGImages文件夹中存储了所有的图片,Annotations文件夹存储了每一张图片对应目标的标注。

数据格式转换:
tensorflow训练需要的数据格式是tfrecord类型的,所以在开始训练之前要将PASCAL VOC2012数据集转换为tfrecord格式。
新建my_object_detection/create_pascal_tf_record_train.sh,写入如下内容:

python dataset_tools/create_pascal_tf_record.py --data_dir=my_images/VOCdevkit/ --year=VOC2012 --output_path=my_images/VOCdevkit/pascal_train.record --set=train

新建my_object_detection/create_pascal_tf_record_val.sh,写入如下内容:

python dataset_tools/create_pascal_tf_record.py --data_dir=my_images/VOCdevkit/ --year=VOC2012 --output_path=my_images/VOCdevkit/pascal_val.record --set=val

执行bash create_pascal_tf_record_train.sh
执行bash create_pascal_tf_record_val.sh
可以在my_object_detection/images/VOCdevkit/文件夹下得到pascal_train.record和pascal_val.record两个文件,说明转换成功。

下载预训练模型:
下载faster_rcnn_inception_resnet_v2_atrous_coco模型,将其解压到my_object_detection/models/中。

导入PASCAL_VOC2012数据集的pbtxt文件:
将原object_detection/data/中的pascal_label_map.pbtxt文件复制到my_object_detection/data/中

配置训练参数:
新建my_object_detection/training_config/,将原object_detection/samples/config/faster_rcnn_inception_resnet_v2_atrous_coco.config文件复制到该文件夹下,改名字为faster_rcnn_inception_resnet_v2_atrous_coco_voc2012.config,并对其进行修改:

将num_classes: 90改为num_classes: 20
将num_examples: 8000改为num_examples: 5823
5处PATH_TO_BE_CONFIGURED的修改为对应的目录

我最终修改的目录为:

# Faster R-CNN with Inception Resnet v2, Atrous version;
# Configured for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  faster_rcnn {
    num_classes: 20
    image_resizer {
      keep_aspect_ratio_resizer {
        min_dimension: 600
        max_dimension: 1024
      }
    }
    feature_extractor {
      type: 'faster_rcnn_inception_resnet_v2'
      first_stage_features_stride: 8
    }
    first_stage_anchor_generator {
      grid_anchor_generator {
        scales: [0.25, 0.5, 1.0, 2.0]
        aspect_ratios: [0.5, 1.0, 2.0]
        height_stride: 8
        width_stride: 8
      }
    }
    first_stage_atrous_rate: 2
    first_stage_box_predictor_conv_hyperparams {
      op: CONV
      regularizer {
        l2_regularizer {
          weight: 0.0
        }
      }
      initializer {
        truncated_normal_initializer {
          stddev: 0.01
        }
      }
    }
    first_stage_nms_score_threshold: 0.0
    first_stage_nms_iou_threshold: 0.7
    first_stage_max_proposals: 300
    first_stage_localization_loss_weight: 2.0
    first_stage_objectness_loss_weight: 1.0
    initial_crop_size: 17
    maxpool_kernel_size: 1
    maxpool_stride: 1
    second_stage_box_predictor {
      mask_rcnn_box_predictor {
        use_dropout: false
        dropout_keep_probability: 1.0
        fc_hyperparams {
          op: FC
          regularizer {
            l2_regularizer {
              weight: 0.0
            }
          }
          initializer {
            variance_scaling_initializer {
              factor: 1.0
              uniform: true
              mode: FAN_AVG
            }
          }
        }
      }
    }
    second_stage_post_processing {
      batch_non_max_suppression {
        score_threshold: 0.0
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SOFTMAX
    }
    second_stage_localization_loss_weight: 2.0
    second_stage_classification_loss_weight: 1.0
  }
}

train_config: {
  batch_size: 1
  optimizer {
    momentum_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0003
          schedule {
            step: 900000
            learning_rate: .00003
          }
          schedule {
            step: 1200000
            learning_rate: .000003
          }
        }
      }
      momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  gradient_clipping_by_norm: 10.0
  fine_tune_checkpoint: "./models/faster_rcnn_inception_resnet_v2_atrous_coco_2018_01_28/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "./images/VOCdevkit/pascal_train.record"
  }
  label_map_path: "./data/pascal_label_map.pbtxt"
}

eval_config: {
  num_examples: 5823
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 10
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "./images/VOCdevkit/pascal_val.record"
  }
  label_map_path: "./data/pascal_label_map.pbtxt"
  shuffle: false
  num_readers: 1
}

开始训练:
新建my_object_detection/training_dir/文件夹,用于存放训练结果
新建my_object_detection/leo_object_detection_COCO_VOC2012_training.sh,写入内容如下:

python ~/anaconda3/lib/python3.5/site-packages/tensorflow/models/research/object_detection/legacy/train.py \
	--train_dir=./train_dir/ \
	--pipeline_config_path=./training_config/faster_rcnn_inception_resnet_v2_atrous_coco_voc2012.config \

执行bash leo_object_detection_COCO_VOC2012_training.sh就可以开始训练了:)

7.导出自己训练的模型

新建my_object_detection/export_dir/文件夹,用于存放导出模型
新建my_object_detection/leo_export_inference_graph.sh文件,写入如下内容:

python ~/anaconda3/lib/python3.5/site-packages/tensorflow/models/research/object_detection/export_inference_graph.py \
    --input_type=image_tensor \
    --pipeline_config_path=./training_config/faster_rcnn_inception_resnet_v2_atrous_coco_voc2012.config \
    --trained_checkpoint_prefix=./train_dir/model.ckpt-200000 \
    --output_directory=./export_dir/ \


执行bash leo_export_inference_graph.sh就可以将训练的模型导出了。
导出之后,可以在my_object_detection/export_dir/看到如下结果:
在这里插入图片描述
其中frozen_inference_graph.pb就是最终的结果。
新建my_object_detection/models/faster_rcnn_inception_resnet_v2_atrous_COCO_VOC2012文件夹,
将my_object_detection/export_dir/中的内容剪切到该文件夹中,以便调用。

8.测试自己训练的模型

修改第5步中my_object_detection/leo_object_detection_APP_ssd_mobilenet_v1_coco_2018_01_28.py文件中的相应路径,新生成一个python文件,起名字为my_object_detection/leo_object_detection_APP_faster_rcnn_inception_resnet_v2_atrous_COCO_VOC2012.py,测试训练结果。网上随便找了张图,虽然有的时候把马识别成了狗,但是整个流程工作的很好。
在这里插入图片描述

9.训练自己真正的模型

实际应用中,需要识别的目标千差万别,因此需要对特定目标进行训练。

9.1目标标注

标注工具选用labelImage,github上已经给出了详细的安装和使用教程。
标注完成之后,每张图片会对应一个xml文件,其中存储着标注信息,我这里用爬虫爬取了很多GYY的图片,并对其进行了标注,结果如下。
在这里插入图片描述

  • 新建my_object_detection/images/myimages/文件夹,用于存放自己的图片及标注信息。
  • 新建my_object_detection/images/myimages/my_train_images/GYY/文件夹,并将训练图片以及标注好的xml文件copy进去。
  • 新建my_object_detection/images/myimages/my_test_images/GYY/文件夹,并将测试图片以及标注好的xml文件copy进去。

9.2数据预处理:将xml转换成csv

  • 新建my_object_detection/images/myimages/xml2csv_my_train_images_GYY.py文件,并在其中写入如下内容:
# xml2csv.py

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET

os.chdir('/home/leo/Desktop/object_detection_API_work/my_object_detection/images/myimages/my_train_images/GYY/')
path = '/home/leo/Desktop/object_detection_API_work/my_object_detection/images/myimages/my_train_images/GYY/'

def xml_to_csv(path):
    xml_list = []
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                     int(root.find('size')[1].text),
                     member[0].text,
                     int(member[4][0].text),
                     int(member[4][1].text),
                     int(member[4][2].text),
                     int(member[4][3].text)
                     )
            xml_list.append(value)
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df


def main():
    image_path = path
    xml_df = xml_to_csv(image_path)
    xml_df.to_csv('GYY_train.csv', index=None)
    print('Successfully converted xml to csv.')


main()
  • 新建my_object_detection/images/myimages/xml2csv_my_test_images_GYY.py文件,并在其中写入如下内容:
# xml2csv.py

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET

os.chdir('/home/leo/Desktop/object_detection_API_work/my_object_detection/images/myimages/my_test_images/GYY/')
path = '/home/leo/Desktop/object_detection_API_work/my_object_detection/images/myimages/my_test_images/GYY/'

def xml_to_csv(path):
    xml_list = []
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                     int(root.find('size')[1].text),
                     member[0].text,
                     int(member[4][0].text),
                     int(member[4][1].text),
                     int(member[4][2].text),
                     int(member[4][3].text)
                     )
            xml_list.append(value)
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df


def main():
    image_path = path
    xml_df = xml_to_csv(image_path)
    xml_df.to_csv('GYY_test.csv', index=None)
    print('Successfully converted xml to csv.')


main()

上面两个python文件实现的是将xml标注信息转换成csv格式,cd 到my_object_detection/images/myimages/,执行:

python xml2csv_my_train_images_GYY.py
python xml2csv_my_test_images_GYY.py

然后查看my_object_detection/images/myimages/my_train_images/GYY和my_object_detection/images/myimages/my_test_images/GYY/文件夹,正常情况在两个文件夹下分别会生成GYY_train.csv和GYY_test.csv文件,打开这两个文件,确保里面的内容正确。

9.3数据预处理:将csv转换成tfrecord

  • 新建my_object_detection/images/myimages/leo_generate_tfrecord_train_GYY.py文件,写入:
# leo_generate_tfrecord_train_GYY.py

# -*- coding: utf-8 -*-


"""
Usage:
 # From tensorflow/models/
 # Create train data:
 python generate_tfrecord.py --csv_input=data/tv_vehicle_labels.csv  --output_path=train.record
 # Create test data:
 python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=test.record
"""


import os
import io
import pandas as pd
import tensorflow as tf

from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict


flags = tf.app.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
   if row_label == 'GaoYY':     # 需改动
       return 1
   else:
       None


def split(df, group):
   data = namedtuple('data', ['filename', 'object'])
   gb = df.groupby(group)
   return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]


def create_tf_example(group, path):
   with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
       encoded_jpg = fid.read()
   encoded_jpg_io = io.BytesIO(encoded_jpg)
   image = Image.open(encoded_jpg_io)
   width, height = image.size

   filename = group.filename.encode('utf8')
   image_format = b'jpg'
   xmins = []
   xmaxs = []
   ymins = []
   ymaxs = []
   classes_text = []
   classes = []

   for index, row in group.object.iterrows():
       xmins.append(row['xmin'] / width)
       xmaxs.append(row['xmax'] / width)
       ymins.append(row['ymin'] / height)
       ymaxs.append(row['ymax'] / height)
       classes_text.append(row['class'].encode('utf8'))
       classes.append(class_text_to_int(row['class']))

   tf_example = tf.train.Example(features=tf.train.Features(feature={
       'image/height': dataset_util.int64_feature(height),
       'image/width': dataset_util.int64_feature(width),
       'image/filename': dataset_util.bytes_feature(filename),
       'image/source_id': dataset_util.bytes_feature(filename),
       'image/encoded': dataset_util.bytes_feature(encoded_jpg),
       'image/format': dataset_util.bytes_feature(image_format),
       'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
       'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
       'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
       'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
       'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
       'image/object/class/label': dataset_util.int64_list_feature(classes),
   }))
   return tf_example


def main(_):
   writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
   path = os.path.join(os.getcwd(), 'my_train_images/GYY')         #  需改动
   examples = pd.read_csv(FLAGS.csv_input)
   grouped = split(examples, 'filename')
   for group in grouped:
       tf_example = create_tf_example(group, path)
       writer.write(tf_example.SerializeToString())

   writer.close()
   output_path = os.path.join(os.getcwd(), FLAGS.output_path)
   print('Successfully created the TFRecords: {}'.format(output_path))


if __name__ == '__main__':
   tf.app.run()
  • 新建my_object_detection/images/myimages/leo_generate_tfrecord_test_GYY.py文件,写入:
# leo_generate_tfrecord_test_GYY.py

# -*- coding: utf-8 -*-


"""
Usage:
  # From tensorflow/models/
  # Create train data:
  python generate_tfrecord.py --csv_input=data/tv_vehicle_labels.csv  --output_path=train.record
  # Create test data:
  python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=test.record
"""


import os
import io
import pandas as pd
import tensorflow as tf

from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict


flags = tf.app.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'GaoYY':     # 需改动
        return 1
    else:
        None


def split(df, group):
    data = namedtuple('data', ['filename', 'object'])
    gb = df.groupby(group)
    return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]


def create_tf_example(group, path):
    with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = Image.open(encoded_jpg_io)
    width, height = image.size

    filename = group.filename.encode('utf8')
    image_format = b'jpg'
    xmins = []
    xmaxs = []
    ymins = []
    ymaxs = []
    classes_text = []
    classes = []

    for index, row in group.object.iterrows():
        xmins.append(row['xmin'] / width)
        xmaxs.append(row['xmax'] / width)
        ymins.append(row['ymin'] / height)
        ymaxs.append(row['ymax'] / height)
        classes_text.append(row['class'].encode('utf8'))
        classes.append(class_text_to_int(row['class']))

    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(filename),
        'image/source_id': dataset_util.bytes_feature(filename),
        'image/encoded': dataset_util.bytes_feature(encoded_jpg),
        'image/format': dataset_util.bytes_feature(image_format),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
    }))
    return tf_example


def main(_):
    writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
    path = os.path.join(os.getcwd(), 'my_test_images/GYY')         #  需改动
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples, 'filename')
    for group in grouped:
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())

    writer.close()
    output_path = os.path.join(os.getcwd(), FLAGS.output_path)
    print('Successfully created the TFRecords: {}'.format(output_path))


if __name__ == '__main__':
    tf.app.run()
  • 新建my_object_detection/images/myimages/leo_generate_tfrecord_train_GYY.sh文件,写入:
python leo_generate_tfrecord_train_GYY.py \
    --csv_input=./my_train_images/GYY/GYY_train.csv \
    --output_path=./my_train_images/GYY_train.record \
  • 新建my_object_detection/images/myimages/文件,写入:
python leo_generate_tfrecord_test_GYY.py \
    --csv_input=./my_test_images/GYY/GYY_test.csv \
    --output_path=./my_test_images/GYY_test.record \
  • cd到my_object_detection/images/myimages/文件夹下,执行
bash leo_generate_tfrecord_train_GYY.sh
bash leo_generate_tfrecord_test_GYY.sh
  • 正常生成成功的话,会在my_object_detection/images/myimages/my_train_images文件夹下生成GYY_train.record文件,在my_object_detection/images/myimages/my_test_images文件夹下生成GYY_test.record文件。

9.4设置pbtxt文件

新建my_object_detection/data/GYY_label_map.pbtxt文件,写入:


9.5配置训练参数

复制my_object_detection/training_config/faster_rcnn_inception_resnet_v2_atrous_coco.config文件到该文件夹下,改名字为faster_rcnn_inception_resnet_v2_atrous_coco_GYY.config。并对其进行修改:

将num_classes: 20改为num_classes: 1						#我只有一类,即GaoYY
将num_examples: 5823改为num_examples: 21					#我的验证集图片数量只有21张
5处PATH_TO_BE_CONFIGURED的修改为对应的目录	

我最终修改的目录为:

# Faster R-CNN with Inception Resnet v2, Atrous version;
# Configured for MSCOCO Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.

model {
  faster_rcnn {
    num_classes: 1
    image_resizer {
      keep_aspect_ratio_resizer {
        min_dimension: 600
        max_dimension: 1024
      }
    }
    feature_extractor {
      type: 'faster_rcnn_inception_resnet_v2'
      first_stage_features_stride: 8
    }
    first_stage_anchor_generator {
      grid_anchor_generator {
        scales: [0.25, 0.5, 1.0, 2.0]
        aspect_ratios: [0.5, 1.0, 2.0]
        height_stride: 8
        width_stride: 8
      }
    }
    first_stage_atrous_rate: 2
    first_stage_box_predictor_conv_hyperparams {
      op: CONV
      regularizer {
        l2_regularizer {
          weight: 0.0
        }
      }
      initializer {
        truncated_normal_initializer {
          stddev: 0.01
        }
      }
    }
    first_stage_nms_score_threshold: 0.0
    first_stage_nms_iou_threshold: 0.7
    first_stage_max_proposals: 300
    first_stage_localization_loss_weight: 2.0
    first_stage_objectness_loss_weight: 1.0
    initial_crop_size: 17
    maxpool_kernel_size: 1
    maxpool_stride: 1
    second_stage_box_predictor {
      mask_rcnn_box_predictor {
        use_dropout: false
        dropout_keep_probability: 1.0
        fc_hyperparams {
          op: FC
          regularizer {
            l2_regularizer {
              weight: 0.0
            }
          }
          initializer {
            variance_scaling_initializer {
              factor: 1.0
              uniform: true
              mode: FAN_AVG
            }
          }
        }
      }
    }
    second_stage_post_processing {
      batch_non_max_suppression {
        score_threshold: 0.0
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SOFTMAX
    }
    second_stage_localization_loss_weight: 2.0
    second_stage_classification_loss_weight: 1.0
  }
}

train_config: {
  batch_size: 1
  optimizer {
    momentum_optimizer: {
      learning_rate: {
        manual_step_learning_rate {
          initial_learning_rate: 0.0003
          schedule {
            step: 900000
            learning_rate: .00003
          }
          schedule {
            step: 1200000
            learning_rate: .000003
          }
        }
      }
      momentum_optimizer_value: 0.9
    }
    use_moving_average: false
  }
  gradient_clipping_by_norm: 10.0
  fine_tune_checkpoint: "./models/faster_rcnn_inception_resnet_v2_atrous_coco_2018_01_28/model.ckpt"
  from_detection_checkpoint: true
  # Note: The below line limits the training process to 200K steps, which we
  # empirically found to be sufficient enough to train the pets dataset. This
  # effectively bypasses the learning rate schedule (the learning rate will
  # never decay). Remove the below line to train indefinitely.
  num_steps: 200000
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
}

train_input_reader: {
  tf_record_input_reader {
    input_path: "./images/myimages/my_train_images/GYY_train.record"
  }
  label_map_path: "./data/GYY_label_map.pbtxt"
}

eval_config: {
  num_examples: 21
  # Note: The below line limits the evaluation process to 10 evaluations.
  # Remove the below line to evaluate indefinitely.
  max_evals: 10
}

eval_input_reader: {
  tf_record_input_reader {
    input_path: "./images/myimages/my_test_images/GYY_test.record"
  }
  label_map_path: "./data/GYY_label_map.pbtxt"
  shuffle: false
  num_readers: 1
}

9.6开始训练

新建my_object_detection/train_dir/GYY/文件夹,用于存放bolt的训练结果
新建my_object_detection/leo_object_detection_COCO_GYY_training.sh,写入内容如下:

python ~/anaconda3/lib/python3.5/site-packages/tensorflow/models/research/object_detection/legacy/train.py \
    --train_dir=./train_dir/GYY/ \
    --pipeline_config_path=./training_config/faster_rcnn_inception_resnet_v2_atrous_coco_GYY.config \

执行bash leo_object_detection_COCO_GYY_training.sh就可以开始训练了:)

9.7训练监测

在my_object_detection/文件夹下输入:

tensorboard --logdir=./train_dir/GYY

然后,在浏览器输入127.0.0.1:6006就可以实时看到训练情况了
在这里插入图片描述

9.7导出训练好的模型

新建my_object_detection/export_dir/GYY/ 文件夹,用于存放导出模型
新建my_object_detection/leo_export_inference_graph_GYY.sh文件,写入如下内容:

python ~/anaconda3/lib/python3.5/site-packages/tensorflow/models/research/object_detection/export_inference_graph.py \
    --input_type=image_tensor \
    --pipeline_config_path=./training_config/faster_rcnn_inception_resnet_v2_atrous_coco_GYY.config \
    --trained_checkpoint_prefix=./train_dir/GYY/model.ckpt-5739 \
    --output_directory=./export_dir/GYY/ \


执行bash leo_export_inference_graph_GYY.sh就可以将训练的模型导出了。

9.8测试自己的模型

从网上找几张图片,作为测试,放在my_object_detection/images/test_images/文件夹下,名字分别为GaoYY_test0.jpeg,GaoYY_test1.jpeg,GaoYY_test2.jpeg,GaoYY_test3.jpeg,GaoYY_test4.jpeg,GaoYY_test5.jpeg,GaoYY_test6.jpeg
新建my_object_detection/leo_object_detection_APP_faster_rcnn_inception_resnet_v2_atrous_COCO_GYY.py文件
写入:

#encoding:utf-8
import tensorflow as tf
import numpy as np
 
import os
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_utils
 
#下载下来的模型的目录
MODEL_DIR = 'export_dir/GYY'
#下载下来的模型的文件
MODEL_CHECK_FILE = os.path.join(MODEL_DIR, 'frozen_inference_graph.pb')
#数据集对于的label
MODEL_LABEL_MAP = os.path.join('data', 'GYY_label_map.pbtxt')
#数据集分类数量,可以打开mscoco_label_map.pbtxt文件看看
MODEL_NUM_CLASSES = 1
 
#这里是获取实例图片文件名,将其放到数组中
PATH_TO_TEST_IMAGES_DIR = 'images/test_images'
TEST_IMAGES_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR, 'GaoYY_test{}.jpeg'.format(i)) for i in range(0, 7)]
 
#输出图像大小,单位是in
IMAGE_SIZE = (12, 8)
 
tf.reset_default_graph()
 
#将模型读取到默认的图中
with tf.gfile.GFile(MODEL_CHECK_FILE, 'rb') as fd:
    _graph = tf.GraphDef()
    _graph.ParseFromString(fd.read())
    tf.import_graph_def(_graph, name='')
 
#加载COCO数据标签,将mscoco_label_map.pbtxt的内容转换成
# {1: {'id': 1, 'name': u'person'}...90: {'id': 90, 'name': u'toothbrush'}}格式
label_map = label_map_util.load_labelmap(MODEL_LABEL_MAP)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=MODEL_NUM_CLASSES)
category_index = label_map_util.create_category_index(categories)
 
#将图片转化成numpy数组形式
def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return np.array(image.getdata()).reshape((im_height, im_width, 3)).astype(np.uint8)
 
#在图中开始计算
detection_graph = tf.get_default_graph()
with tf.Session(graph=detection_graph) as sess:
    for image_path in TEST_IMAGES_PATHS:
        print(image_path)
        #读取图片
        image = Image.open(image_path)
        #将图片数据转成数组
        image_np = load_image_into_numpy_array(image)
        #增加一个维度
        image_np_expanded = np.expand_dims(image_np, axis=0)
        #下面都是获取模型中的变量,直接使用就好了
        image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
        #存放所有检测框
        boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
        #每个检测结果的可信度
        scores = detection_graph.get_tensor_by_name('detection_scores:0')
        #每个框对应的类别
        classes = detection_graph.get_tensor_by_name('detection_classes:0')
        #检测框的个数
        num_detections = detection_graph.get_tensor_by_name('num_detections:0')
        #开始计算
        (boxes, scores, classes, num_detections) = sess.run([boxes, scores, classes, num_detections],
                                                            feed_dict={image_tensor : image_np_expanded})
        #打印识别结果
        print(num_detections)
        print(boxes)
        print(classes)
        print(scores)
 
        #得到可视化结果
        vis_utils.visualize_boxes_and_labels_on_image_array(
            image_np,
            np.squeeze(boxes),
            np.squeeze(classes).astype(np.int32),
            np.squeeze(scores),
            category_index,
            use_normalized_coordinates=True,
            line_thickness=8
        )
        #显示
        plt.figure(figsize=IMAGE_SIZE)
        plt.imshow(image_np)
        plt.show()

在my_object_detection/文件夹下执行python leo_object_detection_APP_faster_rcnn_inception_resnet_v2_atrous_COCO_GYY.py,结果如下:

在这里插入图片描述
化妆成这样还能识别出来?怕是水平有点厉害

在这里插入图片描述
等等,难道她老公跟她的关系都能识别出来?水平相当不一样啊

什么情况,所有的女生都被识别成了GaoYY?水平有所下降啊

在这里插入图片描述
连ChaiJ都被识别成GaoYY?水平一般啊

在这里插入图片描述
连男生都识别成了GaoYY?水平也是有限啊
在这里插入图片描述
什么???连高老师都沦陷了!?这水平真的相当相当不行和有限啊

10.总结

Object Detection Api是google提供的基于tensorflow的目标检测API,通过数据标注,确定了训练前的类别,将标注xml转换成csv,然后再转换成tensorflow喜欢的tfrecord,配置一些训练参数,然后开始训练,训练完成后,将训练结果导出成模型,然后再调用这个模型进行目标检测就可以了。
我使用的特定人脸数据进行标注,训练结果在预测范围内,对人脸这类大目标检测的很好,连高老师也被检测出来了,我很严肃,搞通了目标识别API的使用方法只是瞎玩一玩,还是要多看论文,多看文献啊。

基于TensorFlow Object Detection API实现RetinaNet目标检测网络(附源码) RetinaNet是作者Tsung-Yi Lin和Kaiming He于2018年发表的论文Focal Loss for Dense Object Detection中提出的网络。RetinaNet凭借其结构精简清晰、可扩展性强、检测准确率高等特点,成为了很多目标检测算法的baseline。在模型的训练过程中,经常会遇到这样的场景:我们需要保存某个时刻训练好的模型参数,这样在对模型进行微调时,才能使用保存好的参数继续训练,而不是再随机生成参数大范围的拟合。 阅读详情

相关推荐

Ubuntu16 Tensorflow Object Detection API 训练自己的数据集 环境搭建以及问题解决记录

本文主要综合几个切实使用并可用的教程,以及使用过程中遇到的报错和解决问题做一个记录 1. 环境介绍 由于不开学,我用的是自己的笔记本,环境配置如下: 环境配置:Ubuntu16.04+CUDA9.0+CuDNN7.0.5+NVIDIA Driver 418.56+tensorflow-CPU 1. 用GPU跑笔记本散热不好,实在是太热。 电脑显卡:GetForce MX250 4G 电脑内存:8G 处理器:intel core i7 2. Tensorflow Object Detection API配置

cxxxxxxxxxxxxx的博客 951

Tensorflow object detection api数据集检测视频教程

Tensorflow object detection api数据集检测视频培训教程:此课程从应用的角度出发,讲述如何利用深度学习框架tensorflow object detection api来检测自己的数据集,提供了专用的图像标注工具,让初学者入手应用,做出自己的对象检测工具。

机器学习笔记 - windows10+tensorflow2.7安装object detection API

windows10 64位、tensorflow-gpu 2.7.0、python 3.7.11环境下安装object detection api with tensorflow2。 TensorFlow 对象检测 API 是一个构建在 TensorFlow 之上的开源框架,可以轻松构建、训练和部署对象检测模型。 建议创建一个新的独立的python环境,用之前安装过很多东西的环境一是慢,二是可能会各种冲突,即使安装成功也未必能运行,这里我是创建了一个新的3.7.11的环境。

学以致用 知行合一 1549

Tensorflow object detection api 参数详解

一、引言 使用谷歌提供的object detection api图像识别框架,我们可以很方便地重新训练一个预训练模型,用于自己的具体业务。以我所使用的ssd_mobilenet_v1预训练模型为例,训练所需参数都在training文件夹下的ssd_mobilenet_v1_coco.config中预先配置了,只需对少量路径参数做修改即可。 但是这种“傻瓜式”的训练参数配置方法有很大不足。一是无法理解训练参数背后的原理,不利于技术积累;二是一旦遇到需要优化的问题时,不知道如何调整训练参数。例如,我使用默认配置

excelNo1的博客 1775

将自己的数据集制作成TFRecord格式教程

在使用TensorFlow训练神经网络时,首先面临的问题是:网络的输入 此篇文章,教大家将自己的数据集制作成TFRecord格式,feed进网络,除了TFRecord格式,TensorFlow也支持其他格 式的数据,此处就不再介绍了。建议大家使用TFRecord格式,在后面可以通过api进行多线程的读取文件队列。 1. 原本的数据集 此时,我有两类图片,分别是xiansu100,xiansu60,每一类中有10张图片。 2.制作成TFRecord格式 tfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签。如在本例中,只有0,1 两类,想知道文件夹名与label关系的,可以自己

快速了解Spyder

一 面板介绍菜单栏:放置所有功能工具栏:放置快捷菜单,可以通过菜单栏中的View的Toolbars的复选框来勾选工作区:写代码的地方属性页的标题栏:可以显示当前代码的名字和位置查看栏:查看文件、调试时的对象及变量输出栏:查看程序的输出信息,也可以作为shell终端来输入Python语句状态栏:用来显示当前文件权限、编码,光标指向位置和系统内存二 注释功能注释功能为编写代码很常用功能,下面介绍Spy...

实践求真知 1万+

TensorFlow2 Object Detection API安装及运行实验记录

Tensorflow2 Object Detection API安装及简易的确认实验记录

chenxy_bwave的专栏 4271

如何利用三阈值游程理论识别干旱事件_python

如果当前时间点与上一个干旱事件的结束位置相隔不超过一个月(`index - current_event['end_index']

weixin_44259522的博客 1946

记录:使用Tensorflow的Object detection API实现实时目标检测

目录Tensorflow环境的配置和安装版本选择安装Anaconda2/3换源新建一个Anaconda环境安装Tensorflow安装Object detection API训练模型创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入 Ten...

weixin_43727223的博客 821

如何降低 Claude Code 封号风险:实用指南

本文针对 Claude Code 用户频繁遭遇账号封禁的问题,提供了一套经过实战验证的解决方案。通过分析封号的根本原因——共享VPN导致的IP异常标记,文章详细介绍了如何通过"独立服务器+中转服务+环境配置"三步走策略,显著降低封号风险。

goodparty的专栏 2146

【Qt串口调试助手】1.1 - Qt5编写串口调试助手,Qt串口编程

这章来学习串口数据流操作。仿照成品制作一个自己用Qt编写的串口助手。 1. 布局UI界面 创建QWidget工程,布局UI界面:拖入2个 Plain Text Edit,作为串口数据的接收显示和发送框。 拖入几个 Combo Box 、Label 和 Push Button,使用两个Widget进行布局。如下所示。 将接收区的 Plain Text Edit,属性勾选上 readOnly,使其运行时不会被人为的输入操作影响。 加入一些弹簧,使布局美观。(有必要可以加设置不能调整..

Mark_md的博客 9276

记录Tensorflow Object Detection API训练,测试

  使用Tensorflow Object DetectionAPI进行目标检测 目标检测架构:SSD 深度学习框架:TensorFlow 深度神经网络:MobileNet   目标检测步骤总结如下: 1.      收集500+张包含有待检测目标的图片,最少100张; 2.      使用软件LabelImg对图片进行标注;所谓标注即是在图片上画框定位目标,LabelImg会创建...

honk2012的博客 1万+

Challenge 4 - OSCP A

在c盘下发现一个windows.old,在里面可以找到SYSTEM和SAM文件,下载到本地,利用samdump2解密发现没解出来,再来试试pwdump.py(https://github.com/CiscoCXSecurity/creddump7)得到压缩包密码bludecode,解压之后发现一个比较特殊的文件configuration.php,里面有两个类似密码的字符串。登录之后在/opt/backups/下发现几个特殊文件,其中sitebackup3.zip是个正常的压缩包。但是这个压缩包是有密码的。

羽的博客 5798

tensorflow object detection API 使用记录1

目录:开始熟悉API的使用 简介 第一步准备数据 第二步训练模型 第三步评估 总结开始熟悉API的使用简介安装就不用说了 首先介绍一下配置文件的格式,我是参照官方给的API配置说明记录的:API配置 目标检测API是使用protobuf配置训练评估的过程,配置文件可以看作分为5个部分: model:决定你用什么样的模型 train_config: 训练的参数 eval_config: 决定评估时

Arch的博客 5754

嵌入式工程师必学(52):储能系统ESS

能量存储系统(ESS,Energystoragesystems)存在于各种各样的尺寸、形状和技术中。储能系统的技术,即基本的储能机制,自然会影响其重要特性,包括成本、安全性、性能、可靠性和寿命。然而,尽管基础技术很重要,但一个成功的储能项目依赖于对该技术的彻底和深思熟虑的实施,以实现项目的目标。成功的实施取决于储能系统的架构和组装情况。系统的体系结构可以决定其性能和可靠性,与它所使用的技术一致,甚至与之无关。

码农17年的博客 1443

Autosar入门_OS_5

os hook函数说明

u012406840的博客 402

tensorflow object detection API 使用记录2

使用API训练自己的数据使用API训练自己的数据 说明 实际使用 总结说明本文仍然使用谷歌API提供的网络模型框架,有了框架,现在要解决的是如何让网络训练自己的数据,而数据要提供两个东西给配置文件:一是对应的TFrecord文件,二是对应的.pbtxt文件 .pbtxt文件:很简单,照着object_detection/data文件夹下的示例写就好了,注意id: 0代表背景,自己的类别对应的id应为

Arch的博客 2808

中国各城市土地利用类型(城市功能)数据集(shp)

中国各城市土地利用类型(城市功能)数据集时间:2018年全国范围的城市用地类型数据(居住/商业/交通用地等共计11类)分类:居住用地、商业用地、工业用地、医疗设施用地、体育文化设施用地、交通场站用地、绿地等用地类型含城市编码、一级分类5个、二级分类11个1、上海市。

你好,我是小张同学! 1337

Windows10下Object Detection API实战记录(3)——训练自己的目标检测模型

Windows10下Object Detection API实战记录(3)——训练自己的目标检测模型1、创建新模型的文件夹2、下载预训练模型3、创建标签分类的配置文件4、配置config文件5、训练模型6、保存训练的模型7、使用tensorboard查看训练情况模型训练完毕!!! 1、创建新模型的文件夹 网上查了很多资料,发现很多都是直接在Object Detection文件夹下创建新模型的相应文...

qq_40784418的博客 1037

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

tensorflow object_detection coco API安装错误记录

tensorflow object_detection coco API 安装: make时报错: 分别安装gcc 和Cpython 解决: 对应错误信息: gcc:unable to execute 'gcc': No such file or directory 解决: yum install gcc Cpython:gcc: 错误:pycocotools/_mask.c:没有那个文...

bymain的博客 909

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

tensorflow object detection API 使用记录3

将训练好的模型用于视频上的目标检测将训练好的模型用于视频上的目标检测 冻结模型 处理图片 处理视频 前言:一直都是用来检测图片,未来肯定是要应用在视频上,刚好想做个在视频上检测的小demo,不是做跟踪,所以实现起来很简单,只要把视频的每一帧都处理,另存到另一个视频里就可以了。 流程: 把已经训练好的模型冻结下来,即得到.pb文件(既包括权重也包括网络结构) 利用模型对视频每一帧进行处理并保存 冻

Arch的博客 4009

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Intel Movidius神经元计算棒加速-Object Detection API训练MobileNet-SSD模型全流程记录

这篇文章记录在台式机ubuntu16.04下搭建Intel Movidius神经元计算棒2代的开发环境全过程。 建议和我一样第一次安装的小白们直接看官方技术手册,不要看百度上的各种技术贴,能够避免99.9999%的血泪坑… ...

进阶的乔木同学每天都在码代码 2001

Windows10下Object Detection API实战记录(1)——windows10下成功安装TensorFlow Object Detection API(亲测以及踩坑记录)

目录 1、下载源码后解压,修改文件夹名为models 2、安装protoc: 3、编译proto文件 4、添加环境变量 5、运行models/research下的setup.py 6、安装完成...

qq_40784418的博客 1128

自学记录鸿蒙API 13:实现多目标识别Object Detection

通过此次学习和实践,我不仅掌握了多目标识别API的基本功能,还深刻认识到其广阔的应用场景。在未来的开发中,我计划探索更多创新的实现方式,例如结合语音助手,通过语音控制触发目标识别,或与其他AI能力结合,开发更加智能的解决方案。如果你也对多目标识别感兴趣,不妨从这些基础功能开始,一步步实现自己的创意!当然如果你也在这一领域研究,不妨关注我,我们一起进步~!

李游的博客 1088

Windows10下Object Detection API实战记录(2)——自己数据集的制作

这几天学习了tensorflow中的Object Detection API,虽然网上有很多资料,但还是采了很多坑,没有找到完整详细的一整套实战记录,所以自己整理这几天的成果。 Windows10下Object Detection API实战记录(2)——自己数据集的制作1、准备数据集2、数据集的标注2.1 标注工具安装2.2图像标注3、 数据集格式转换3.1xml转cvs3.2cvs转tfrec...

qq_40784418的博客 574
上一篇: 张正友标定法:A Flexible New Technique for Camera Calibration
下一篇: PCD与STL格式及其内涵
Leo-Ma
博客等级 码龄11年 1701粉丝 124原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值