tensorflow TFRecords文件的生成和读取的方法
作者:Chinneil 时间:2022-04-04 23:21:05
TensorFlow提供了TFRecords的格式来统一存储数据,理论上,TFRecords可以存储任何形式的数据。
TFRecords文件中的数据都是通过tf.train.Example Protocol Buffer的格式存储的。以下的代码给出了tf.train.Example的定义。
message Example {
Features features = 1;
};
message Features {
map<string, Feature> feature = 1;
};
message Feature {
oneof kind {
BytesList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
下面将介绍如何生成和读取tfrecords文件:
首先介绍tfrecords文件的生成,直接上代码:
from random import shuffle
import numpy as np
import glob
import tensorflow as tf
import cv2
import sys
import os
# 因为我装的是CPU版本的,运行起来会有'warning',解决方法入下,眼不见为净~
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
shuffle_data = True
image_path = '/path/to/image/*.jpg'
# 取得该路径下所有图片的路径,type(addrs)= list
addrs = glob.glob(image_path)
# 标签数据的获得具体情况具体分析,type(labels)= list
labels = ...
# 这里是打乱数据的顺序
if shuffle_data:
c = list(zip(addrs, labels))
shuffle(c)
addrs, labels = zip(*c)
# 按需分割数据集
train_addrs = addrs[0:int(0.7*len(addrs))]
train_labels = labels[0:int(0.7*len(labels))]
val_addrs = addrs[int(0.7*len(addrs)):int(0.9*len(addrs))]
val_labels = labels[int(0.7*len(labels)):int(0.9*len(labels))]
test_addrs = addrs[int(0.9*len(addrs)):]
test_labels = labels[int(0.9*len(labels)):]
# 上面不是获得了image的地址么,下面这个函数就是根据地址获取图片
def load_image(addr): # A function to Load image
img = cv2.imread(addr)
img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 这里/255是为了将像素值归一化到[0,1]
img = img / 255.
img = img.astype(np.float32)
return img
# 将数据转化成对应的属性
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]))
def _float_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
# 下面这段就开始把数据写入TFRecods文件
train_filename = '/path/to/train.tfrecords' # 输出文件地址
# 创建一个writer来写 TFRecords 文件
writer = tf.python_io.TFRecordWriter(train_filename)
for i in range(len(train_addrs)):
# 这是写入操作可视化处理
if not i % 1000:
print('Train data: {}/{}'.format(i, len(train_addrs)))
sys.stdout.flush()
# 加载图片
img = load_image(train_addrs[i])
label = train_labels[i]
# 创建一个属性(feature)
feature = {'train/label': _int64_feature(label),
'train/image': _bytes_feature(tf.compat.as_bytes(img.tostring()))}
# 创建一个 example protocol buffer
example = tf.train.Example(features=tf.train.Features(feature=feature))
# 将上面的example protocol buffer写入文件
writer.write(example.SerializeToString())
writer.close()
sys.stdout.flush()
上面只介绍了train.tfrecords文件的生成,其余的validation,test举一反三吧。。
接下来介绍tfrecords文件的读取:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
data_path = 'train.tfrecords' # tfrecords 文件的地址
with tf.Session() as sess:
# 先定义feature,这里要和之前创建的时候保持一致
feature = {
'train/image': tf.FixedLenFeature([], tf.string),
'train/label': tf.FixedLenFeature([], tf.int64)
}
# 创建一个队列来维护输入文件列表
filename_queue = tf.train.string_input_producer([data_path], num_epochs=1)
# 定义一个 reader ,读取下一个 record
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
# 解析读入的一个record
features = tf.parse_single_example(serialized_example, features=feature)
# 将字符串解析成图像对应的像素组
image = tf.decode_raw(features['train/image'], tf.float32)
# 将标签转化成int32
label = tf.cast(features['train/label'], tf.int32)
# 这里将图片还原成原来的维度
image = tf.reshape(image, [224, 224, 3])
# 你还可以进行其他一些预处理....
# 这里是创建顺序随机 batches(函数不懂的自行百度)
images, labels = tf.train.shuffle_batch([image, label], batch_size=10, capacity=30, min_after_dequeue=10)
# 初始化
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess.run(init_op)
# 启动多线程处理输入数据
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
....
#关闭线程
coord.request_stop()
coord.join(threads)
sess.close()
来源:http://blog.csdn.net/u012222949/article/details/72875281
标签:tensorflow,读取
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
php删除路径下的所有文件夹和文件的代码
2023-05-27 18:44:35
优雅地扩大链接响应区域
2010-09-25 13:04:00
![](https://img.aspxhome.com/file/UploadPic/20109/25/2010-09-24_2300081-86s.png)
PL/SQL 日期时间类型函数及运算
2009-02-26 10:45:00
如何使用Python发送HTML格式的邮件
2022-10-01 12:24:02
![](https://img.aspxhome.com/file/2023/9/94179_0s.png)
ASP之对象总结
2008-02-27 13:18:00
怎样管理好css样式
2008-10-12 12:12:00
python样条插值的实现代码
2022-05-11 16:04:05
![](https://img.aspxhome.com/file/2023/3/70833_0s.png)
跨浏览器的本地存储(二):DOM:Storage
2008-08-15 13:39:00
Python双端队列deque的实现
2022-07-07 02:37:29
![](https://img.aspxhome.com/file/2023/2/71552_0s.png)
教你怎么使用sql游标实例分享
2012-07-11 16:14:57
Python OpenCV学习之图像形态学
2022-01-16 21:48:29
![](https://img.aspxhome.com/file/2023/6/93746_0s.jpg)
keras中模型训练class_weight,sample_weight区别说明
2021-09-17 06:23:18
Python ValueError: invalid literal for int() with base 10 实用解决方法
2023-06-18 17:00:40
python用tkinter开发的扫雷游戏
2022-05-16 18:39:40
![](https://img.aspxhome.com/file/2023/8/84978_0s.png)
使用Python实现二分法查找的示例
2022-02-08 13:52:53
![](https://img.aspxhome.com/file/2023/9/85379_0s.png)
Python编程使用matplotlib绘制动态圆锥曲线示例
2021-08-30 03:38:18
![](https://img.aspxhome.com/file/2023/6/85096_0s.png)
python内置模块collections知识点总结
2023-10-27 19:37:08
Python内存管理实例分析
2021-06-13 01:39:21
![](https://img.aspxhome.com/file/2023/5/97745_0s.png)
ASP常见错误详解及解决方案小结 推荐第1/2页
2011-02-24 11:19:00
Python实现圣诞树的多种方法
2023-07-27 01:02:20
![](https://img.aspxhome.com/file/2023/7/61477_0s.jpg)