【Tensorflow系列】使用Inception_resnet_v2训练自己的数据集并用Tensorboard监控

 

【写在前面】

用Tensorflow(TF)已实现好的卷积神经网络(CNN)模型来训练自己的数据集,验证目前较成熟模型在不同数据集上的准确度,如Inception_V3, VGG16,Inception_resnet_v2等模型。本文验证Inception_resnet_v2基于菜场实拍数据的准确性,测试数据为芹菜、鸡毛菜、青菜,各类别样本约600张,多个菜场拍摄,不同数据源。

 

补充:自己当初的计划是用别人预训练好的模型来再训练自己的数据集已使可以完成新的分类任务,但必须要修改代码改网络结构,并使用迁移学习(Fine-tune)

本文记录了其间的工作过程 ,  相信也会有一些帮助的  : )

 

测试环境:Centos7.3-64位  python3.5.4(Anaconda) 

 

 目录

一.准备

1.安装python
2.安装tensorflow
3.下载TF-slim图像库
4.准备数据
5.下载模型

二.训练

1.读入数据
2.构建模型
3.开始训练
4.执行脚本,训练自己的数据
5.可视化log
【问题】 tensorboard版本已更新,找不到对应包

三.验证

四.测试

 

 

一.准备

1.安装python

推荐Anaconda,可创建虚拟环境,用conda命令易实现虚拟环境管理、包管理,安装包时会查出所有依赖包并一共一键安装, 链接:https://www.anaconda.com/download/

2.安装tensorflow 

进入当下Anaconda的运行环境,我安装的是python2.7版,并创建3.5虚拟环境

conda create -n py35 python=3.5    【py35是虚拟环境的名称; 输入y 安装】

source activate py35  【激活py35环境】

conda install tensorflow  【安装tensorflow-cpu版,有GPU可安装cpu版】

3.下载TF-slim代码库

 

cd  $WORKSPACE   【目录跳转到自己的工作目录下】
git clone https://github.com/tensorflow/models/  

4.准备数据

对所有训练样本按不同样本类别存在不同文件夹下

zsy_train
|---jimaocai
  |---  0.jpg
  |---  ...
|---qc
|---qingcai

下面的代码是为了生成list.txt , 把不同文件夹下的图片和 数字label对应起来

按 Ctrl+C 复制代码

 

按 Ctrl+C 复制代码

为了方便后期查看label标签,也可定义labels.txt

jimaocai
qc
qingcai

随机生成训练集和验证集(在总量中随机选取350个样本作为验证集)

按 Ctrl+C 复制代码

 

按 Ctrl+C 复制代码

生成TFRecord数据

按 Ctrl+C 复制代码

 

按 Ctrl+C 复制代码

得到的文件夹结构如下

复制代码

WORKSPACE
├── zsy_train
├── labels.txt
├── list_train.txt
├── list.txt
├── list_val.txt
├── train
│   ├── data_000-of-003.tfrecord
│   ├── ...
│   └── data_002-of-003.tfrecord
└── val
    ├── data_000-of-003.tfrecord
    ├── ...
    └── data_002-of-003.tfrecord

复制代码

5.下载模型

官方提供了预训练,这里以Inception-ResNet-v2以例

cd $WORKSPACE/checkpoints
wget http://download.tensorflow.org/models/inception_resnet_v2_2016_08_30.tar.gz
tar zxf inception_resnet_v2_2016_08_30.tar.gz

 

二.训练

1.读入数据

读入自己的数据,需要把下面代码写入models/slim/datasets/dataset_classification.py

按 Ctrl+C 复制代码

 

按 Ctrl+C 复制代码

2.构建模型

构建模型取决于个人欲构建什么样的模型,官方都有对应模型的下载链接,只需把对应下载(下载链接:https://github.com/tensorflow/models/tree/master/research/slim)好的模型解压放入到checkpoints中即可

3.开始训练

由于是用已有模型训练自己的数据集,故需对原工程代码做适当调整。

from datasets import dataset_factory

改为:

from datasets import dataset_classification

dataset = dataset_factory.get_dataset(
    FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)

改为:

dataset = dataset_classification.get_dataset(
    FLAGS.dataset_dir, FLAGS.num_samples, FLAGS.num_classes, FLAGS.labels_to_names_path)

tf.app.flags.DEFINE_string(
    'dataset_dir', None, 'The directory where the dataset files are stored.')

后加入:

tf.app.flags.DEFINE_integer(
    'num_samples', 1781, 'Number of samples.')
tf.app.flags.DEFINE_integer(
    'num_classes', 3, 'Number of classes.')
tf.app.flags.DEFINE_string(
    'labels_to_names_path', None, 'Label names file path.')

 4.执行脚本,训练自己的数据

复制代码

cd $WORKSPACE/models/slim    #跳转到工作环境目录
python train_image_classifier.py \     #运行脚本,后面跟的系统参数
    --train_dir=/root/workspace_mrt/model_lab/train_logs \   #train_log目录,当模型训练时,可用tensorboard命令指定该目录,动态监测
    --dataset_dir=../../../train \    #训练数据集   里面是转换好的TFRecord格式
    --num_samples=1781 \           #训练样本数,即值train_set中的总样本数,不包括valid中随机抽取350个样本
    --num_classes=3 \            #样本类别数
    --labels_to_names_path=../../../labels.txt \   
    --model_name=inception_resnet_v2 \
    --checkpoint_path=../../../checkpoints/inception_resnet_v2_2016_08_30.ckpt \      #指定模型位置
    --checkpoint_exclude_scopes=InceptionResnetV2/Logits,InceptionResnetV2/AuxLogits \
    --trainable_scopes=InceptionResnetV2/Logits,InceptionResnetV2/AuxLogits \
    --clone_on_cpu=True        #cpu训练必须加上该参数

#fine-tune要把 --checkpoint_path,--checkpoint_exclude_scopes,--trainable_scopes 加上

复制代码

5.可视化log

为了可视化训练时的loss或其他指标,可用tensorboard,如下命令

tensorboard --logdir=${TRAIN_DIR}
在本教程中,对应执行下面命令
tensorboard --logdir=/root/workspace_mrt/model_lab/train_logs

【问题】 tensorboard版本已更新,找不到对应包

当执行

tensorboard --logdir=/root/workspace_mrt/model_lab/train_logs

时,得到如下错误

ImportError: No module named 'tensorflow.tensorboard.tensorboard'

究其原因,是因为在tensorflow更新时,包的位置和所属关系改变了。执行以下代码,可解决该问题。

cd /root/anaconda2/envs/py35/bin    #跳转到对应python环境的bin目录下,修改tensorboard执行脚本代码,使之适应当前版本
vim tensorboard

import tensorflow.tensorboard.tensorboard

修改为:

import tensorboard.main

sys.exit(tensorflow.tensorboard.tensorboard.main())

修改为: sys.exit(tensorboard.main.main()) 

wq保存,退出,重新执行

 tensorboard --logdir=/root/workspace_mrt/model_lab/train_logs 

命令,无报错。根据日志提示,进入ip:6006进入tensorboard界面。

三.验证

使用自己的数据集,需修改models/slim/eval_image_classifier.py

 from datasets import dataset_factory 

改为:

 from datasets import dataset_classification 

dataset = dataset_factory.get_dataset( FLAGS.dataset_name, FLAGS.dataset_split_name, FLAGS.dataset_dir)

改为:

dataset = dataset_classification.get_dataset(
    FLAGS.dataset_dir, FLAGS.num_samples, FLAGS.num_classes, FLAGS.labels_to_names_path)

tf.app.flags.DEFINE_string(
    'dataset_dir', None, 'The directory where the dataset files are stored.')

后加入

tf.app.flags.DEFINE_integer(
    'num_samples', 350, 'Number of samples.')
tf.app.flags.DEFINE_integer(
    'num_classes', 3, 'Number of classes.')
tf.app.flags.DEFINE_string(
    'labels_to_names_path', None, 'Label names file path.')

验证时执行以下命令即可:

复制代码

python eval_image_classifier.py \
    --checkpoint_path=../../../checkpoints/inception_resnet_v2_2016_08_30.ckpt \
    --eval_dir=/root/workspace_mrt/model_lab/eval_logs \
    --dataset_dir=../../../val \
    --num_samples=350 \
    --num_classes=3 \
    --model_name=inception_resnet_v2

复制代码

可以一边训练一边验证,注意使用其它的GPU或合理分配显存。

同样也可以可视化log,如果已经在可视化训练的log则建议使用其它端口,如:

 tensorboard --logdir ../../../eval_logs/ --port 6007 

 

四.测试

 参考models/slim/eval_image_classifier.py,可编写批量读取图片用模型进行推导的脚本models/slim/test_image_classifier.py

复制代码

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import json
import math
import time
import numpy as np
import tensorflow as tf
from nets import nets_factory
from preprocessing import preprocessing_factory
slim = tf.contrib.slim

tf.app.flags.DEFINE_string(
    'master', '', 'The address of the TensorFlow master to use.')
tf.app.flags.DEFINE_string(
    'checkpoint_path', None,
    'The directory where the model was written to or an absolute path to a '
    'checkpoint file.')
tf.app.flags.DEFINE_string(
    'test_list', '', 'Test image list.')
tf.app.flags.DEFINE_string(
    'test_dir', '.', 'Test image directory.')
tf.app.flags.DEFINE_integer(
    'batch_size', 16, 'Batch size.')
tf.app.flags.DEFINE_integer(
    'num_classes', 3, 'Number of classes.')
tf.app.flags.DEFINE_integer(
    'labels_offset', 0,
    'An offset for the labels in the dataset. This flag is primarily used to '
    'evaluate the VGG and ResNet architectures which do not use a background '
    'class for the ImageNet dataset.')
tf.app.flags.DEFINE_string(
    'model_name', 'inception_resnet_v2', 'The name of the architecture to evaluate.')
tf.app.flags.DEFINE_string(
    'preprocessing_name', None, 'The name of the preprocessing to use. If left '
    'as `None`, then the model_name flag is used.')
tf.app.flags.DEFINE_integer(
    'test_image_size', None, 'Eval image size')
FLAGS = tf.app.flags.FLAGS
def main(_):
    if not FLAGS.test_list:
        raise ValueError('You must supply the test list with --test_list')
    tf.logging.set_verbosity(tf.logging.INFO)
    with tf.Graph().as_default():
        tf_global_step = slim.get_or_create_global_step()
        ####################
        # Select the model #
        ####################
        network_fn = nets_factory.get_network_fn(
            FLAGS.model_name,
            num_classes=(FLAGS.num_classes - FLAGS.labels_offset),
            is_training=False)
        #####################################
        # Select the preprocessing function #
        #####################################
        preprocessing_name = FLAGS.preprocessing_name or FLAGS.model_name
        image_preprocessing_fn = preprocessing_factory.get_preprocessing(
            preprocessing_name,
            is_training=False)
        test_image_size = FLAGS.test_image_size or network_fn.default_image_size
        if tf.gfile.IsDirectory(FLAGS.checkpoint_path):
            checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)
        else:
            checkpoint_path = FLAGS.checkpoint_path
        batch_size = FLAGS.batch_size
        tensor_input = tf.placeholder(tf.float32, [None, test_image_size, test_image_size, 3])
        logits, _ = network_fn(tensor_input)
        logits = tf.nn.top_k(logits, 5)
        config = tf.ConfigProto()
        config.gpu_options.allow_growth = True
        test_ids = [line.strip() for line in open(FLAGS.test_list)]
        tot = len(test_ids)
        results = list()
        with tf.Session(config=config) as sess:
            sess.run(tf.global_variables_initializer())
            saver = tf.train.Saver()
            saver.restore(sess, checkpoint_path)
            time_start = time.time()
            for idx in range(0, tot, batch_size):
                images = list()
                idx_end = min(tot, idx + batch_size)
                print(idx)
                for i in range(idx, idx_end):
                    image_id = test_ids[i]
                    test_path = os.path.join(FLAGS.test_dir, image_id)
                    image = open(test_path, 'rb').read()
                    image = tf.image.decode_jpeg(image, channels=3)
                    processed_image = image_preprocessing_fn(image, test_image_size, test_image_size)
                    processed_image = sess.run(processed_image)
                    images.append(processed_image)
                images = np.array(images)
                predictions = sess.run(logits, feed_dict = {tensor_input : images}).indices
                for i in range(idx, idx_end):
                    print('{} {}'.format(image_id, predictions[i - idx].tolist())
            time_total = time.time() - time_start
            print('total time: {}, total images: {}, average time: {}'.format(
                time_total, len(test_ids), time_total / len(test_ids)))
if __name__ == '__main__':
    tf.app.run()

复制代码

测试时执行以下命令即可:

复制代码

CUDA_VISIBLE_DEVICES="0" python test_image_classifier.py \
    --checkpoint_path=../../../train_logs/ \
    --test_list=../../../list_val.txt \
    --test_dir=../../../val \
    --batch_size=16 \
    --num_classes=3 \
    --model_name=inception_resnet_v2

复制代码

 

【参考】

https://lijiancheng0614.github.io/2017/06/29/2017_06_29_TensorFlow-Slim-image-classification/#%E9%AA%8C%E8%AF%81

https://github.com/tensorflow/models/tree/master/research/slim

【总结】

1.使用Tensorflow预训练模型(TF-slim)可以快速地测试已有成熟模型在不同数据集上的效果,且有利于数据代码架构和核心代码

2.若要自己实现已有成熟的网络模型,包括数据读取、训练、验证、测试,调优,则可用Tensorflow底层API或基于TF的高级API(TensorLayer  TFLearn  TF-slim)实现。从目前了解情况看,TensorLayer更好用,在DeepLearning中迁移学习更是如此

3.TensorFlow是一个非常庞大的架构,新手学习成本太高且难以摸清方向,故此借助下载已有models,调整参数和少量代码有助于进一步认识TensorFlow的实现原理,若想要更深入研究,手写CNN,看源码等都是不可避免的

4.当多看TensorFlow源码,迁移学习的一大利器!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值