python神经网络tfrecords文件的写入读取及内容解析

 更新时间:2022年05月04日 10:17:25   作者:Bubbliiiing  
这篇文章主要为大家介绍了python神经网络tfrecords文件的写入读取及内容解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

学习前言

前一段时间对SSD预测与训练的整体框架有了一定的了解,但是对其中很多细节还是把握的不清楚。今天我决定好好了解以下tfrecords文件的构造。

tfrecords格式是什么

tfrecords是一种二进制编码的文件格式,tensorflow专用。能将任意数据转换为tfrecords。更好的利用内存,更方便复制和移动,并且不需要单独的标签文件。

之所以使用到tfrecords格式是因为当今数据爆炸的情况下,使用普通的数据格式不仅麻烦,而且速度慢,这种专门为tensorflow定制的数据格式可以大大增快数据的读取,而且将所有内容规整,在保证速度的情况下,使得数据更加简单明晰。

tfrecords的写入

这个例子将会讲述如何将MNIST数据集写入到tfrecords,本次用到的MNIST数据集会利用tensorflow原有的库进行导入。

from tensorflow.examples.tutorials.mnist import input_data
# 读取MNIST数据集
mnist = input_data.read_data_sets('./MNIST_data', dtype=tf.float32, one_hot=True)

对于MNIST数据集而言,其中的训练集是mnist.train,而它的数据可以分为images和labels,可通过如下方式获得。

# 获得image,shape为(55000,784)
images = mnist.train.images
# 获得label,shape为(55000,10)
labels = mnist.train.labels
# 获得一共具有多少张图片
num_examples = mnist.train.num_examples

接下来定义存储TFRecord文件的地址,同时创建一个writer来写TFRecord文件。

# 存储TFRecord文件的地址
filename = 'record/output.tfrecords'
# 创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)

此时便可以按照一定的格式写入了,此时需要对每一张图片进行循环并写入,在tf.train.Features中利用features字典定义了数据保存的方式。以image_raw为例,其经过函数_float_feature处理后,存储到tfrecords文件的’image/encoded’位置上。

# 将每张图片都转为一个Example,并写入
for i in range(num_examples):
    image_raw = images[i]  # 读取每一幅图像
    image_string = images[i].tostring()
    example = tf.train.Example(
        features=tf.train.Features(
            feature={
                'image/class/label': _int64_feature(np.argmax(labels[i])),
                'image/encoded': _float_feature(image_raw),
                'image/encoded_tostring': _bytes_feature(image_string)
            }
        )
    )
    print(i,"/",num_examples)
    writer.write(example.SerializeToString())  # 将Example写入TFRecord文件

在最终存入前,数据还需要经过处理,处理方式如下:

# 生成整数的属性
def _int64_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
# 生成浮点数的属性
def _float_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# 生成字符串型的属性
def _bytes_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

tfrecords的读取

tfrecords的读取首先要创建一个reader来读取TFRecord文件中的Example。

# 创建一个reader来读取TFRecord文件中的Example
reader = tf.TFRecordReader()

再创建一个队列来维护输入文件列表。

# 创建一个队列来维护输入文件列表
filename_queue = tf.train.string_input_producer(['record/output.tfrecords'])

利用reader读取输入文件列表队列,并用parse_single_example将读入的Example解析成tensor

# 从文件中读出一个Example
_, serialized_example = reader.read(filename_queue)
# 用parse_single_example将读入的Example解析成tensor
features = tf.parse_single_example(
    serialized_example,
    features={
        'image/class/label': tf.FixedLenFeature([], tf.int64),
        'image/encoded': tf.FixedLenFeature([784], tf.float32, default_value=tf.zeros([784], dtype=tf.float32)),
        'image/encoded_tostring': tf.FixedLenFeature([], tf.string)
    }
)

此时我们得到了一个features,实际上它是一个类似于字典的东西,我们额可以通过字典的方式读取它内部的内容,而字典的索引就是我们再写入tfrecord文件时所用的feature。

# 将字符串解析成图像对应的像素数组
labels = tf.cast(features['image/class/label'], tf.int32)
images = tf.cast(features['image/encoded'], tf.float32)
images_tostrings = tf.decode_raw(features['image/encoded_tostring'], tf.float32)

最后利用一个循环输出:

# 每次运行读取一个Example。当所有样例读取完之后,在此样例中程序会重头读取
for i in range(5):
    label, image = sess.run([labels, images])
    images_tostring = sess.run(images_tostrings)
    print(np.shape(image))
    print(np.shape(images_tostring))
    print(label)
    print("#########################")

测试代码

1、tfrecords文件的写入

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 生成整数的属性
def _int64_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
# 生成浮点数的属性
def _float_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# 生成字符串型的属性
def _bytes_feature(value):
    if not isinstance(value,list) and not isinstance(value,np.ndarray):
        value = [value]
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
# 读取MNIST数据集
mnist = input_data.read_data_sets('./MNIST_data', dtype=tf.float32, one_hot=True)
# 获得image,shape为(55000,784)
images = mnist.train.images
# 获得label,shape为(55000,10)
labels = mnist.train.labels
# 获得一共具有多少张图片
num_examples = mnist.train.num_examples
# 存储TFRecord文件的地址
filename = 'record/Mnist_Out.tfrecords'
# 创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
# 将每张图片都转为一个Example,并写入
for i in range(num_examples):
    image_raw = images[i]  # 读取每一幅图像
    image_string = images[i].tostring()
    example = tf.train.Example(
        features=tf.train.Features(
            feature={
                'image/class/label': _int64_feature(np.argmax(labels[i])),
                'image/encoded': _float_feature(image_raw),
                'image/encoded_tostring': _bytes_feature(image_string)
            }
        )
    )
    print(i,"/",num_examples)
    writer.write(example.SerializeToString())  # 将Example写入TFRecord文件
print('data processing success')
writer.close()

运行结果为:

……
54993 / 55000
54994 / 55000
54995 / 55000
54996 / 55000
54997 / 55000
54998 / 55000
54999 / 55000
data processing success

2、tfrecords文件的读取

import tensorflow as tf
import numpy as np
# 创建一个reader来读取TFRecord文件中的Example
reader = tf.TFRecordReader()
# 创建一个队列来维护输入文件列表
filename_queue = tf.train.string_input_producer(['record/Mnist_Out.tfrecords'])
# 从文件中读出一个Example
_, serialized_example = reader.read(filename_queue)
# 用parse_single_example将读入的Example解析成tensor
features = tf.parse_single_example(
    serialized_example,
    features={
        'image/class/label': tf.FixedLenFeature([], tf.int64),
        'image/encoded': tf.FixedLenFeature([784], tf.float32, default_value=tf.zeros([784], dtype=tf.float32)),
        'image/encoded_tostring': tf.FixedLenFeature([], tf.string)
    }
)
# 将字符串解析成图像对应的像素数组
labels = tf.cast(features['image/class/label'], tf.int32)
images = tf.cast(features['image/encoded'], tf.float32)
images_tostrings = tf.decode_raw(features['image/encoded_tostring'], tf.float32)
sess = tf.Session()
# 启动多线程处理输入数据
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# 每次运行读取一个Example。当所有样例读取完之后,在此样例中程序会重头读取
for i in range(5):
    label, image = sess.run([labels, images])
    images_tostring = sess.run(images_tostrings)
    print(np.shape(image))
    print(np.shape(images_tostring))
    print(label)
    print("#########################")

运行结果为:

#########################
(784,)
(784,)
7
#########################
#########################
(784,)
(784,)
4
#########################
#########################
(784,)
(784,)
1
#########################
#########################
(784,)
(784,)
1
#########################
#########################
(784,)
(784,)
9
#########################

以上就是python神经网络tfrecords文件的写入读取及内容解析的详细内容,更多关于python神经网络tfrecords写入读取的资料请关注脚本之家其它相关文章!

相关文章

  • python中对数据进行各种排序的方法

    python中对数据进行各种排序的方法

    这篇文章主要介绍了python中对数据进行各种排序的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-07-07
  • python中pandas nlargest()的详细用法小结

    python中pandas nlargest()的详细用法小结

    df.nlargest()是一个DataFrame的方法,用于返回DataFrame中最大的n个值所在的行,通过调用nlargest()方法,我们返回了分数最高的三个行,并按照降序排列,本文结合实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2023-10-10
  • 将python项目打包成exe与安装包的全过程

    将python项目打包成exe与安装包的全过程

    Python唯二的难题运行速度和源代码反编译,一直是被众多语言所诟病,下面这篇文章主要给大家介绍了关于如何将python项目打包成exe与安装包的相关资料,需要的朋友可以参考下
    2021-11-11
  • python中re.findall函数实例用法

    python中re.findall函数实例用法

    在本篇文章里小编给大家整理了一篇关于python中re.findall函数实例用法相关内容,有兴趣的朋友们可以学习下。
    2021-09-09
  • Python网络编程详解

    Python网络编程详解

    这篇文章主要介绍了Python网络编程详解,涉及具体代码示例,还是挺不错的,这里分享给大家,供需要的朋友参考。
    2017-10-10
  • Python列表list数组array用法实例解析

    Python列表list数组array用法实例解析

    这篇文章主要介绍了Python列表list数组array用法,实例解析了关于数组的各种常见操作,非常具有实用价值,需要的朋友可以参考下
    2014-10-10
  • 用Python绘制一个仿黑洞图像

    用Python绘制一个仿黑洞图像

    黑洞图像大家都知道,毕竟前几年刚发布的时候曾火遍全网,甚至都做成表情包了。本文就来用Python绘制一个仿黑洞图像,希望大家能够喜欢
    2023-02-02
  • Python使用设计模式中的责任链模式与迭代器模式的示例

    Python使用设计模式中的责任链模式与迭代器模式的示例

    这篇文章主要介绍了Python使用设计模式中的责任链模式与迭代器模式的示例,责任链模式与迭代器模式都可以被看作为行为型的设计模式,需要的朋友可以参考下
    2016-03-03
  • python获取文件扩展名的方法

    python获取文件扩展名的方法

    这篇文章主要介绍了python获取文件扩展名的方法,涉及Python针对文件路径的相关操作技巧,非常简单实用,需要的朋友可以参考下
    2015-07-07
  • 一文带你探索Python中15个常见的魔术方法

    一文带你探索Python中15个常见的魔术方法

    在Python中,特殊方法(也称为魔术方法)是由Python解释器自动调用的,我们不需要手动调用它们,本文小编为大家整理了15个常见特殊方法的实现,希望对大家有所帮助
    2024-01-01

最新评论