tensorflow分类任务——TFRecord制作自己的数据集

制作数据集的前菜——打乱数组

	x, y = imageNumpyData()
    state = np.random.get_state()
    np.random.shuffle(x)
    np.random.set_state(state)
    np.random.shuffle(y)
    # 打乱之后的x,y作为训练数据
    x = np.array(x)
    y = np.array(y)
  1. 代码运行之前,x是一个list,y是一个array
  2. 使用随机数的方式打乱数据
  3. 如果x和y的数据样本数不一样,容易出现错误
  4. 打乱之后全部变成array

制作数据集的正餐

数据集的流程:

  1. 先读取输入,并把数据保存成固定通道,固定维数。
  2. 保存成numpy的形式,之后打乱数据集
  3. 数据集一张一张写入TFRecord中

注意事项:

  1. Data里面存放数据
  2. record里面存放制作成功的数据集
  3. 需要提前准备好了record这个文件夹,不然容易报错,如果要自动创建文件夹请看我另一篇博客,这个不做赘述
  4. 我的图片格式是JPEG,我在代码中写了判断,同时也可以制作BMP和PNG类型的图片
  5. 我的图片是灰度图,所以是单通道,读者若是彩色图片,相应更改代码,我在下面的解释中有说明
    工程目录结构

所有代码

import numpy as np
import tensorflow as tf
import os
from PIL import Image
import base64
import matplotlib.pyplot as plt


def imageNumpyData():
    # the classification file root path
    rootFilePath = './Data/'
    rootAbsPath = os.path.abspath(rootFilePath)
    node1FloderPath = os.listdir(rootAbsPath)
    node1Path = [os.path.join(rootAbsPath, nodePath) for nodePath in node1FloderPath]
    label = 0
    imageLabel = []
    imageData = []
    for imagePath in node1Path:
        display = 0
        image = os.listdir(imagePath)
        image = [os.path.join(imagePath, file) for file in image]
        # 使用tensorflow
        with tf.Session() as sess:
            for image_raw in image:
                try:
                    img = Image.open(image_raw)
                    if img.format == "BMP":
                        image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()
                        image_data = tf.image.decode_bmp(image_raw_data)
                    if img.format == "JPEG":
                        image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()
                        image_data = tf.image.decode_jpeg(image_raw_data)
                    if img.format == "PNG":
                        image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()
                        image_data = tf.image.decode_png(image_raw_data)
                    if image_data.dtype != tf.float32:
                        image_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)
                    image_data = tf.image.resize_images(image_data, [224, 224])
                    image_temp = np.array(sess.run(image_data))
                    if image_temp.shape[2] == 1:
                        imageData.append(image_temp)
                        imageLabel.append(label)
                        display = display + 1
                        print(str(label) + ':' + str(display))
                except:
                    print(image_raw + '读取失败')
                    # os.remove(image_raw)
        label = label + 1
    one_hot = tf.one_hot(imageLabel, label)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        imageLabel = sess.run(one_hot)
    return imageData, imageLabel


def tfRecordWrite(filename):
    # 生成整数的属性
    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]))

    # filename = 'record/Imageoutput.tfrecords'
    writer = tf.python_io.TFRecordWriter(filename)
    x, y = imageNumpyData()
    state = np.random.get_state()
    np.random.shuffle(x)
    np.random.set_state(state)
    np.random.shuffle(y)
    # 打乱之后的x,y作为训练数据
    x = np.array(x)
    y = np.array(y)

    # 将每张图片都转为一个Example
    height = x.shape[1]
    width = x.shape[2]
    channels = x.shape[3]
    n_class = y.shape[1]

    x = x.reshape([-1, height, width, channels])

    division = int(x.shape[0] * 0.9)

    x_train = x[:division]
    y_train = y[:division]
    x_test = x[division:]
    y_test = y[division:]
    np.savez('testData.npz', test_X=x_test, test_Y=y_test, height=height, width=width, channels=channels,
             n_class=n_class)
    del x_test, y_test
    for i in range(x_train.shape[0]):
        image = x_train[i].tostring()  # 将图像转为字符串
        example = tf.train.Example(features=tf.train.Features(
            feature={
                'image': _bytes_feature(image),
                'label': _int64_feature(np.argmax(y_train[i]))
            }))
        writer.write(example.SerializeToString())  # 将Example写入TFRecord文件
    writer.close()

    return height, width, channels, n_class


filename = r'./record\Imageoutput.tfrecords'
height, width, channels, n_class = tfRecordWrite(filename)
print(height, width, channels, n_class)
print('data processing success')


关键代码解释

                 try:
                    img = Image.open(image_raw)
                    if img.format == "BMP":
                        image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()
                        image_data = tf.image.decode_bmp(image_raw_data)
                    if img.format == "JPEG":
                        image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()
                        image_data = tf.image.decode_jpeg(image_raw_data)
                    if img.format == "PNG":
                        image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()
                        image_data = tf.image.decode_png(image_raw_data)

解释:尝试打开图片,并且图片格式是JPEG,BMP或PNG, tf.gfile.FastGFile的这个地方必须要‘rb’,我看一些书上仅仅是写了一个‘r’,这样并不对。

 if image_data.dtype != tf.float32:
                            image_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)

解释:我做CNN的中,需要float32,这里必须转格式

image_data = tf.image.resize_images(image_data, [224, 224])

解释:把图片更改大小

 if image_temp.shape[2] == 1:
                            imageData.append(image_temp)
                            imageLabel.append(label)

解释:我的是灰度图,所以这里**‘’==1‘’,若是三通道,则‘==3’**

one_hot = tf.one_hot(imageLabel, label)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        imageLabel = sess.run(one_hot)

解释:把得到的label,转换成one-hot形式

 x = x.reshape([-1, height, width, channels])

    division = int(x.shape[0] * 0.9)

    x_train = x[:division]
    y_train = y[:division]
    x_test = x[division:]
    y_test = y[division:]
    np.savez('testData.npz', test_X=x_test, test_Y=y_test, height=height, width=width, channels=channels,
             n_class=n_class)
    del x_test, y_test

解释:这里是我拿出一部分数据保存成‘npz’的形式作为我的测试集,因为我用tfrecord格式的数据作为训练集

 # 生成整数的属性
    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]))

解释:这是我们必须遵从的规则,用整数属性写入label,用字符串形式写入图像数据

# filename = 'record/Imageoutput.tfrecords'
    writer = tf.python_io.TFRecordWriter(filename)

解释:开始写入,并生成文件

    for i in range(x_train.shape[0]):
        image = x_train[i].tostring()  # 将图像转为字符串
        example = tf.train.Example(features=tf.train.Features(
            feature={
                'image': _bytes_feature(image),
                'label': _int64_feature(np.argmax(y_train[i]))
            }))
        writer.write(example.SerializeToString())  # 将Example写入TFRecord文件
    writer.close()

解释:根据数据集大小,一个一个的写入

数据集地址:
链接:https://pan.baidu.com/s/1aIHzKsxUb67sJZAFrGH1ZQ
提取码:lvjp

工程地址:
链接:https://pan.baidu.com/s/1XGAA6UQ0JByhvDYQ__my4g
提取码:dxpn

结束语

希望大家积极学习,有不懂的地方可以加我的微信:ChaofeiLi

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 制作数据集的步骤如下: 1. 收集数据:收集需要用于训练模型的数据,可以是图片、文本、音频等。 2. 数据预处理:对收集到的数据进行预处理,如图像的缩放、裁剪、旋转等操作,文本的分词、去除停用词等操作。 3. 数据标注:对数据进行标注,如图像分类、目标检测、语义分割等标注方式,文本的情感分类、命名实体识别等标注方式。 4. 数据集划分:将数据集划分为训练集、验证集和测试集,一般比例为6:2:2。 5. 数据集存储:将处理好的数据集存储为tfrecord格式,方便后续读取和处理。 在tensorflow2.中,可以使用tf.data.Dataset API来读取和处理tfrecord格式的数据集,具体操作可以参考官方文档。 ### 回答2: TensorFlow 2.0是一个强大的机器学习工具,它可以帮助我们训练并优化模型。在使用TensorFlow 2.0构建机器学习模型之前,我们需要先构建一个数据集。构建数据集的过程通常包括数据的处理、清洗和转换等步骤。 第一步是定义数据集。在TensorFlow 2.0中,数据集tf.data.Dataset对象表示。可以使用tf.data.Dataset.from_tensor_slices()或tf.data.Dataset.from_generator()函数来定义数据集。from_tensor_slices()函数需要将数据存储在一个Numpy数组或一个TensorFlow张量中,而from_generator()函数则需要一个Python生成器来生成数据。 第二步是对数据集进行预处理和清洗操作。在TensorFlow 2.0中,数据预处理和清洗可采用tf.keras.preprocessing模块。例如,可以使用ImageDataGenerator类来对图像进行缩放或裁剪,也可以使用TextVectorization类对文本进行向量化处理。 第三步是将数据集转换成可以用于模型训练的格式。在TensorFlow 2.0中,使用.map()方法可以对数据集应用任何函数。例如,可以使用.map()方法来对每个图像进行缩放操作或者对每个文本进行词袋编码。此外,TensorFlow 2.0还提供了.batch()方法,可以将数据集分成小批量来进行训练。 最后,我们需要在模型训练之前对数据集进行随机化和重复等操作,以确保训练数据的随机性和多样性。TensorFlow 2.0提供了.shuffle()和.repeat()方法,可以很容易地完成这些操作。 在构建数据集时,我们还需要注意一些问题。例如,如果数据集非常大,则可能需要使用TensorFlow 2.0的分布式训练功能来并行处理数据。另外,如果数据集包含多个类型的数据,则需要对数据进行适当的类型转换和归一化处理。此外,还需要保证数据集的质量和一致性,以确保训练模型的准确性和可靠性。 总之,使用TensorFlow 2.0构建数据集的过程需要考虑多个方面,包括数据集的定义、预处理和清洗、转换和数据集的随机化和重复。只有在数据集构建得到优化和精细后,才能使模型的训练更加准确和可靠。 ### 回答3: TensorFlow是一个流行的深度学习框架,它支持制作、读取和处理数据集。在TensorFlow 2.0中,制作数据集可以使用TensorFlow提供的Dataset API。 Dataset API是一种高效地处理大量数据的API,可以自动执行诸如数据读取,预处理,shuffle和batch等操作,以便更好地处理训练数据集和测试数据集。 下面是使用TensorFlow 2.0生成一个简单的数据集的步骤: 1.导入必要的库 ``` import tensorflow as tf import numpy as np ``` 2.生成训练和测试数据 ``` train_data = np.random.randint(0,10,[500,5]) train_label = np.random.randint(0,2,[500,1]) test_data = np.random.randint(0,10,[50,5]) test_label = np.random.randint(0,2,[50,1]) ``` 上述代码中,我们生成了500个训练样本和50个测试样本,每个样本包含5个特征。每个样本都有一个标签,可以是0或1。 3.创建Dataset对象 ``` train_dataset = tf.data.Dataset.from_tensor_slices((train_data,train_label)) test_dataset = tf.data.Dataset.from_tensor_slices((test_data,test_label)) ``` TensorFlow从切片中创建Dataset对象是最常见的方式之一。这里我们使用from_tensor_slices函数从numpy数组中创建Dataset对象。将输入数据和标签作为元组传递给from_tensor_slices函数。 4.对数据集进行预处理 ``` def preprocess(data, label): data = tf.cast(data, tf.float32) / 255. label = tf.cast(label, tf.int32) return data, label ``` 在这个预处理函数中,我们将数据类型转换为float32类型,并将数值归一化为0到1之间的值。标签被转换为int32类型。 5.应用预处理函数到数据集 ``` train_dataset = train_dataset.map(preprocess) test_dataset = test_dataset.map(preprocess) ``` 在这里,我们使用map函数应用预处理函数。这将处理每个元素(特征和标签)。 6.对数据集进行shuffle和batch处理 ``` train_dataset = train_dataset.shuffle(buffer_size=1000).batch(20) test_dataset = test_dataset.batch(20) ``` 使用shuffle和batch函数可以随机打乱数据集,并指定每批的大小。在这里,我们使用大小为20的批次。 7.将数据集用于模型训练 ``` model.fit(train_dataset, epochs=10, validation_data=test_dataset) ``` 最后,我们使用fit函数来训练我们的模型,并使用验证数据集来测试我们的模型性能。这种方法使数据集处理变得容易和高效,增加了数据表现力,提高了模型性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值