当训练数据量较小时,采用直接读取文件的方式,当训练数据量非常大时,直接读取文件的方式太耗内存,这时应采用高效的读取方法,读取tfrecords文件,这其实是一种二进制文件。tensorflow为其内置了各种存储和读取的函数,方便调用。

  不知道为啥,从tfrecords中读取数据用于训练时,收敛得更快,更平稳。上面两个图是使用tfrecords的准确率和loss值变化,下面是直接读取文件的准确率和loss值变化。

1 生成记录样本的记录文件

 root_dir = os.getcwd()

 def getTrianList():
with open("train.txt","w") as f:
for file in os.listdir(root_dir+'\\dataSet'):
for picFile in os.listdir(root_dir+"\\dataSet\\"+file):
f.write("dataSet/"+file+"/"+picFile+" "+file+"\n")
print(picFile)
if __name__=="__main__":
getTrianList()

  将样本文件路径和标签统一记录到一个txt中,后面生成tfrecords文件就是通过读取这些信息。

  

  注意文件路径和标签之间采用空格,不要使用制表符。

2 读取txt存于数组中

 def load_file(example_list_file):
lines = np.genfromtxt(example_list_file,delimiter=" ",dtype=[('col1', 'S120'), ('col2', 'i8')])
examples = []
labels = []
for example,label in lines:
examples.append(example)
labels.append(label)
#convert to numpy array
return np.asarray(examples),np.asarray(labels),len(lines)

  这段代码主要用来读取第1步生成的txt,将文件路径和标签存于数组中

3 读取图片

 def extract_image(filename,height,width):
print(filename)
image = cv2.imread(filename)
image = cv2.resize(image,(height,width))
b,g,r = cv2.split(image)
rgb_image = cv2.merge([r,g,b])
return rgb_image

  使用cv2读取图片文件

4 转化为tfrecords文件

 def trans2tfRecord(trainFile,name,output_dir,height,width):
if not os.path.exists(output_dir) or os.path.isfile(output_dir):
os.makedirs(output_dir)
_examples,_labels,examples_num = load_file(train_file)
filename = name + '.tfrecords'
writer = tf.python_io.TFRecordWriter(filename)
for i,[example,label] in enumerate(zip(_examples,_labels)):
print("NO{}".format(i))
#need to convert the example(bytes) to utf-8
example = example.decode("UTF-8")
image = extract_image(example,height,width)
image_raw = image.tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'image_raw':_bytes_feature(image_raw),
'height':_int64_feature(image.shape[0]),
'width': _int64_feature(32),
'depth': _int64_feature(32),
'label': _int64_feature(label)
}))
writer.write(example.SerializeToString())
writer.close()
 def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

5 从tfrecords中读取训练数据

 def read_tfRecord(file_tfRecord):
queue = tf.train.string_input_producer([file_tfRecord])
reader = tf.TFRecordReader()
_,serialized_example = reader.read(queue)
features = tf.parse_single_example(
serialized_example,
features={
'image_raw': tf.FixedLenFeature([], tf.string),
'height': tf.FixedLenFeature([], tf.int64),
'width':tf.FixedLenFeature([], tf.int64),
'depth': tf.FixedLenFeature([], tf.int64),
'label': tf.FixedLenFeature([], tf.int64)
}
)
image = tf.decode_raw(features['image_raw'],tf.uint8)
#height = tf.cast(features['height'], tf.int64)
#width = tf.cast(features['width'], tf.int64)
image = tf.reshape(image,[32,32,3])
image = tf.cast(image, tf.float32)
image = tf.image.per_image_standardization(image)
label = tf.cast(features['label'], tf.int64)
print(image,label)
return image,label

  从tfrecords文件中读取image和label,训练的时候,直接使用tf.train.batch函数生成用于训练的batch即可。

 image_batches,label_batches = tf.train.batch([image, label], batch_size=16, capacity=20)

  其余的部分跟之前的训练步骤一样。

tensorflowxun训练自己的数据集之从tfrecords读取数据的更多相关文章

  1. TensorFlow学习笔记——LeNet-5(训练自己的数据集)

    在之前的TensorFlow学习笔记——图像识别与卷积神经网络(链接:请点击我)中了解了一下经典的卷积神经网络模型LeNet模型.那其实之前学习了别人的代码实现了LeNet网络对MNIST数据集的训练 ...

  2. Fast RCNN 训练自己的数据集(3训练和检测)

    转载请注明出处,楼燚(yì)航的blog,http://www.cnblogs.com/louyihang-loves-baiyan/ https://github.com/YihangLou/fas ...

  3. 【faster-rcnn】训练自己的数据集时的坑

    既然faster-rcnn原版发表时候是matlab版代码,那就用matlab版代码吧!不过遇到的坑挺多的,不知道python版会不会好一点. ======= update ========= 总体上 ...

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

    [写在前面] 用Tensorflow(TF)已实现好的卷积神经网络(CNN)模型来训练自己的数据集,验证目前较成熟模型在不同数据集上的准确度,如Inception_V3, VGG16,Inceptio ...

  5. 目标检测算法SSD之训练自己的数据集

    目标检测算法SSD之训练自己的数据集 prerequesties 预备知识/前提条件 下载和配置了最新SSD代码 git clone https://github.com/weiliu89/caffe ...

  6. 可变卷积Deforable ConvNet 迁移训练自己的数据集 MXNet框架 GPU版

    [引言] 最近在用可变卷积的rfcn 模型迁移训练自己的数据集, MSRA官方使用的MXNet框架 环境搭建及配置:http://www.cnblogs.com/andre-ma/p/8867031. ...

  7. caffe训练自己的数据集

    默认caffe已经编译好了,并且编译好了pycaffe 1 数据准备 首先准备训练和测试数据集,这里准备两类数据,分别放在文件夹0和文件夹1中(之所以使用0和1命名数据类别,是因为方便标注数据类别,直 ...

  8. 使用yolo3模型训练自己的数据集

    使用yolo3模型训练自己的数据集 本项目地址:https://github.com/Cw-zero/Retrain-yolo3 一.运行环境 1. Ubuntu16.04. 2. TensorFlo ...

  9. 【tf.keras】在 cifar 上训练 AlexNet,数据集过大导致 OOM

    cifar-10 每张图片的大小为 32×32,而 AlexNet 要求图片的输入是 224×224(也有说 227×227 的,这是 224×224 的图片进行大小为 2 的 zero paddin ...

随机推荐

  1. 自动化测试环境准备robotframework

    (一)针对python2.7版本的自动化环境准备: python 下载地址: https://www.python.org/downloads/ 这里选择Python2.7系列的,后面涉及到wxPyt ...

  2. 【BZOJ3416】Poi2013 Take-out 栈

    [BZOJ3416]Poi2013 Take-out Description 小F喜欢玩一个消除游戏——take-out 保证k+1|n,保证输入数据有解这是一个单人游戏 游戏者的目标是消除初始时给定 ...

  3. 【BZOJ3211】花神游历各国 并查集+树状数组

    [BZOJ3211]花神游历各国 Description Input Output 每次x=1时,每行一个整数,表示这次旅行的开心度 Sample Input 41 100 5 551 1 22 1 ...

  4. mysql用sql创建表完整实例

    create table user_login_latest( id int(11) unsigned NOT NULL AUTO_INCREMENT, user_id int(11) not nul ...

  5. 160329(二)、web.xml配置详解

    1.启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml,读取<listener>和<context-param>两个结点. 2.紧急着,容创建一个Servl ...

  6. ubuntu中vi编辑器键盘错乱的问题

    Ubuntu安装完成后vi编辑器键盘不能正常使用,使用下面方法解决: 编辑文件/etc/vim/vimrc.tiny,将“compatible”改成“nocompatible”非兼容模式: 并添加一句 ...

  7. Java代码规范、基本类型和实例演练

    1.代码分段 当一个方法内部的代码超过7行时,就要考虑分成段落. 使用空行分隔代码 按照代码的功能进行分段 最终效果是一眼就能在宏观上把握代码的结构 (1)举例 Card 分成2段 第一段:定义变量保 ...

  8. Java+selenium+Fitnesse

    刚开始接触selenium是进公司后,老大给我们培训了一下UI自动化(其实也不叫培训啦,就是让我们知道有这么个东西吧,我这么说,老大看到得打人了,哈哈).要进行自动化测试,当然就得搭建一个自动化测试框 ...

  9. ZOJ 3932 Handshakes

    Last week, n students participated in the annual programming contest of Marjar University. Students ...

  10. 适配器模式(Adpater)

    一.适配器模式介绍 适配器模式:将一个类的接口转换成客户希望的另外一个接口.Adapter模式使得原本由于接口不兼容而不能一起工作的类可以一起工作. 例如: NBA中的球员来自不同国家,而世界标准语言 ...