Tensorflow之构建自己的图片数据集TFrecords的方法

以下是详细讲解如何构建自己的图片数据集TFrecords的方法:

什么是TFrecords?

TFrecords是Tensorflow官方推荐的一种数据格式,它将数据序列化为二进制文件,可以有效地减少使用内存的开销,提高数据读写的效率。在Tensorflow的实际应用中,TFrecords文件常用来存储大规模的数据集,比如图像数据集、语音数据集、文本数据集等。

构建自己的图片数据集TFrecords的方法

下面,我将详细讲解如何构建自己的图片数据集TFrecords的方法,包括以下几个步骤:

第一步,准备数据

首先,我们需要准备好图片数据集。在准备数据时,可以将图片数据集按照标签归类到不同的文件夹中,并为每个文件夹命名为对应的标签名。例如,我们下载了一个猫狗分类数据集,将猫的图片归类到一个名为“cat”的文件夹中,将狗的图片归类到一个名为“dog”的文件夹中。

第二步,将图片转换为TFrecords格式

第二步,我们将图片转换成TFrecords格式文件。可以使用Tensorflow提供的API来实现将图片转换为TFrecords文件的功能。以下是一个示例代码:

import tensorflow as tf
import os

# 定义函数,将单张图片转换为Example格式
def _image_to_example(image_path, label):
    with tf.io.gfile.GFile(image_path, 'rb') as f:
        image_data = f.read()
    example = tf.train.Example(features=tf.train.Features(feature={
        'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_data])),
        'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))
    }))
    return example

# 定义函数,将图片文件夹中的所有图片转换为TFrecords格式
def images_to_tfrecords(images_dir, output_file):
    image_extensions = ['.jpg', '.jpeg', '.png']   # 支持的图片格式
    labels = {'cat': 0, 'dog': 1}   # 标签名与标签值的对应关系
    with tf.io.TFRecordWriter(output_file) as writer:
        for label_name, label_value in labels.items():
            image_dir = os.path.join(images_dir, label_name)
            for image_filename in os.listdir(image_dir):
                if os.path.splitext(image_filename)[-1] not in image_extensions:
                    continue
                image_path = os.path.join(image_dir, image_filename)
                example = _image_to_example(image_path, label_value)
                writer.write(example.SerializeToString())

以上代码实现了将单张图片转换为Example格式的函数_image_to_example()和将图片文件夹中的所有图片转换为TFrecords格式的函数images_to_tfrecords()

在使用images_to_tfrecords()函数时,需要传入两个参数:

  • images_dir:包含图片文件夹路径的字符串。
  • output_file:生成的TFrecords文件名。

第三步,使用TFrecords进行数据读取

第三步,我们可以使用Tensorflow提供的Dataset API来读取并解析上一步生成的TFrecords文件。以下是一个示例代码:

import tensorflow as tf

# 定义函数,解析单个Example
def _parse_example_fn(example_proto):
    feature_to_type = {
        'image': tf.io.FixedLenFeature([], dtype=tf.string),
        'label': tf.io.FixedLenFeature([], dtype=tf.int64)
    }
    features = tf.io.parse_single_example(example_proto, feature_to_type)
    image = tf.io.decode_jpeg(features['image'])
    label = features['label']
    return {'image': image}, label

# 定义函数,读取TFrecords文件并返回Dataset
def read_tfrecords(tfrecords_file, image_size, batch_size):
    dataset = tf.data.TFRecordDataset(tfrecords_file)
    dataset = dataset.map(_parse_example_fn)
    dataset = dataset.map(lambda x, y: (tf.image.resize(x['image'], image_size), y))   # 图像缩放
    dataset = dataset.shuffle(buffer_size=batch_size*10)    # 打乱顺序
    dataset = dataset.batch(batch_size=batch_size, drop_remainder=True)    # 批次化
    dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)  # 预读取
    return dataset

以上代码实现了解析单个Example的函数_parse_example_fn()和读取TFrecords文件并返回Dataset的函数read_tfrecords()

在使用read_tfrecords()函数时,需要传入以下三个参数:

  • tfrecords_file:TFrecords文件名。
  • image_size:缩放后的图像尺寸。
  • batch_size:批次大小。

两个示例

示例一:将猫狗分类数据集转换为TFrecords格式

假设我们已经下载了一个猫狗分类数据集,将猫的图片归类到一个名为“cat”的文件夹中,将狗的图片归类到一个名为“dog”的文件夹中。我们将使用上面的代码,将该数据集的图片转换为TFrecords格式。

images_to_tfrecords('path/to/images/dir', 'cats_vs_dogs.tfrecords')

上面的代码将读取包含所有图片数据的文件夹,将所有JPEG和PNG格式的图片转换为TFrecords格式,并将它们写入名为“cats_vs_dogs.tfrecords”的文件中。

示例二:使用TFrecords进行模型训练

假设我们已经将数据集转换为TFrecords格式,并准备好了模型训练代码。我们可以使用上面的代码构建一个TFrecords数据集,并将其输入到模型中进行训练。

# 构建TFrecords数据集
tfrecords_file = 'cats_vs_dogs.tfrecords'
image_size = (224, 224)
batch_size = 32
dataset = read_tfrecords(tfrecords_file, image_size, batch_size)

# 构建模型并进行训练
model = ...
model.fit(dataset, epochs=10)

以上代码使用read_tfrecords()函数构建了一个TFrecords数据集,并将其输入到模型中进行训练。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Tensorflow之构建自己的图片数据集TFrecords的方法 - Python技术站

(0)
上一篇 2023年5月18日
下一篇 2023年4月5日

相关文章

  • tensorflow 基础学习七:模型的持久化

    tf.train.Saver类的使用 保存模型: import tensorflow as tf v1=tf.Variable(tf.constant(1.0,shape=[1]),name=’v1′) v2=tf.Variable(tf.constant(2.0,shape=[1]),name=’v2′) result=v1+v2 init_op=tf.g…

    tensorflow 2023年4月6日
    00
  • tensorflow for windows –转载

    博客来源于http://blog.csdn.net/darlingwood2013/article/details/60322258 安装说明 平台:目前可在Ubuntu、Mac OS、Windows上安装 版本:提供gpu版本、cpu版本 安装方式:pip方式、Anaconda方式 Tips: 在Windows上目前支持python3.5.x gpu版本需…

    2023年4月6日
    00
  • TensorFlow2.0矩阵与向量的加减乘实例

    TensorFlow2.0是一个十分强大的深度学习框架,用于实现矩阵与向量的加减乘是非常常见的操作。本文将介绍如何在TensorFlow2.0中实现这些操作。同时,本文还将提供两个实例说明,以便读者更好的理解。 创建TensorFlow2.0张量 在TensorFlow2.0中,我们可以使用tf.constant()函数来创建张量(Tensor),例如我们可…

    tensorflow 2023年5月18日
    00
  • TensorFlow设置日志级别的几种方式小结

    在 TensorFlow 中,设置日志级别是一个非常常见的任务。TensorFlow 提供了多种设置日志级别的方式,包括使用 tf.logging、使用 tf.compat.v1.logging 和使用 Python 的 logging 模块。下面是 TensorFlow 中设置日志级别的几种方式的详细攻略。 1. 使用 tf.logging 设置日志级别 …

    tensorflow 2023年5月16日
    00
  • 对于tensorflow中的gradient_override_map函数的理解

    # #############添加############## def binarize(self, x): “”” Clip and binarize tensor using the straight through estimator (STE) for the gradient. “”” g = tf.get_default_graph() with…

    tensorflow 2023年4月8日
    00
  • tensorflow中的dropout是怎么实现的?

    1 #调用dropout函数 2 import tensorflow as tf 3 a = tf.Variable([1.0,2.0,3.0,4.5]) 4 sess = tf.Session() 5 init_op = tf.global_variables_initializer() 6 sess.run(init_op) 7 a = tf.nn.dr…

    tensorflow 2023年4月8日
    00
  • tensorflow源码解析之framework-graph

    什么是graph 图构建辅助函数 graph_transfer_info 关系图 涉及的文件 迭代记录 1. 什么是graph graph是TF计算设计的载体,如果拿TF代码的执行和Java代码执行相比,它相当于Java的字节码。关于graph的执行过程,我们在这里简单介绍一下。在graph构建完成,并进行了一些简单优化之后,会对图进行分割,实际上就是执行一…

    tensorflow 2023年4月6日
    00
  • 整理Python中常用的conda命令操作

    整理Python中常用的conda命令操作 Conda是一个流行的Python包管理器,它可以帮助我们管理Python环境和安装Python包。本文将整理Python中常用的conda命令操作,包括创建和管理环境、安装和卸载包、更新和列出包等操作,并提供两个示例说明。 创建和管理环境 创建一个新的环境: bash conda create –name en…

    tensorflow 2023年5月16日
    00
合作推广
合作推广
分享本页
返回顶部