TensorFlow 生成多个 TFRecord 文件实例

今天早睡
今天早睡
发布时间:2026-10-13| 6人浏览过
原创

本文提供使用 TensorFlow 批量生成多个 TFRecord 文件的完整代码示例。通过设定 shard 数量和每个 shard 的数据量,遍历指定目录下的图片资源,调整尺寸并序列化写入多个 TFRecord 文件,适用于大规模图像数据的模型训练准备。

TensorFlow 生成多个 TFRecord 文件代码示例

以下直接展示实现代码。


import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os
i = 0
j = 0
num_shards = 100#总共写入的文件个数
instances_per_shard = 2#每个文件中的数据个数
sess=tf.InteractiveSession()
cwd = "F:/寒假/google--data/新建文件夹/" #图片数据所在目录位置(读者自己去改就好了)
classes = {'daisy','rose'} #预先自己定义的类别,根据自己的需要修改


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]))
   
for index, name in enumerate(classes):#枚举函数
  class_path = cwd + name + "/"#选取具体数据目录
  for img_name in os.listdir(class_path):#遍历文件列表
    img_path = class_path + img_name#图片路径
    img = Image.open(img_path)
    img = img.resize((299, 299)) #图像reshape大小设置,根据自己的需要修改
    img_raw = img.tobytes()
      
    example = tf.train.Example(features=tf.train.Features(feature={
          'label': _int64_feature(index),
          'img_raw': _bytes_feature(img_raw),
          'i': _int64_feature(i),
          'j': _int64_feature(j)
        }))
    filename = ("F:/寒假/google--data/data.tfrecords-%.5d-of-%.5d"%(i,num_shards))
    if j == instances_per_shard-1:
      i+=1
    j+=1
    if j == instances_per_shard:
      j=0
    writer = tf.python_io.TFRecordWriter(filename)
      
    writer.write(example.SerializeToString())#将一个example写入tfrecord文件
writer.close()

以上关于 TensorFlow 生成多个 TFRecord 文件的实例分享完毕,希望能为读者提供参考与帮助。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。