【写在前面】
用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对应起来
1 importos2 class_names_to_ids = {'jimaocai': 0, 'qc': 1, 'qingcai': 2}3 data_dir = 'flower_photos/'
4 output_path = 'list.txt'
5 fd = open(output_path, 'w')6 for class_name inclass_names_to_ids.keys():7 images_list = os.listdir(data_dir +class_name)8 for image_name inimages_list:9 fd.write('{}/{} {}\n'.format(class_name, image_name, class_names_to_ids[class_name]))10 fd.close()
为了方便后期查看label标签,也可定义labels.txt
jimaocai
qc
qingcai
随机生成训练集和验证集(在总量中随机选取350个样本作为验证集)
1 importrandom2 _NUM_VALIDATION = 350
3 _RANDOM_SEED =04 list_path = 'list.txt'
5 train_list_path = 'list_train.txt'
6 val_list_path = 'list_val.txt'
7 fd =open(list_path)8 lines =fd.readlines()9 fd.close()10 random.seed(_RANDOM_SEED)11 random.shuffle(lines)12 fd = open(train_list_path, 'w')13 for line inlines[_NUM_VALIDATION:]:14 fd.write(line)15 fd.close()16 fd = open(val_list_path, 'w')17 for line inlines[:_NUM_VALIDATION]:18 fd.write(line)19 fd.close()
生成TFRecord数据
importsys#sys.path.insert(0, '../models/slim/') models-master research
sys.path.insert(0, './models/research/slim/') #把后面的路径插入到系统路径中 idx=0
from datasets importdataset_utilsimportmathimportosimporttensorflow as tf#根据list路径 把数据转化为TFRecord#def convert_dataset(list_path, data_dir, output_dir, _NUM_SHARDS=5):
def convert_dataset(list_path, data_dir, output_dir, _NUM_SHARDS=3):
fd=open(list_path)
lines= [line.split() for line infd]
fd.close()
num_per_shard= int(math.ceil(len(lines) /float(_NUM_SHARDS)))
with tf.Graph().as_default():
decode_jpeg_data= tf.placeholder(dtype=tf.string)