如何用tf.data读取tfrecord数据4

使用tf.data数据来读取数据,代码如下

def read_and_decode(file_name,shuffle=True):
    def parser(record):
        features = tf.parse_single_example(record,
                                           features={
                                               'label': tf.FixedLenFeature([], tf.int64),
                                               'img_raw': tf.FixedLenFeature([], tf.string),
                                           })  # return image and label
        image = tf.decode_raw(features['img_raw'], tf.uint8)
        img = tf.reshape(image, [64, 64, 3])
        img = tf.cast(img, tf.float32)
        height = image_size
        width = image_size
        # Randomly crop a [height, width] section of the image.随机裁剪
        distorted_image = tf.random_crop(img, [height, width, 3])
        # Randomly flip the image horizontally.随机翻转
        distorted_image = tf.image.random_flip_left_right \
            (distorted_image)
        # 改变亮度
        distorted_image = tf.image.random_brightness(distorted_image,
                                                     max_delta=63)
        # 改变对比度
        distorted_image = tf.image.random_contrast(distorted_image,
                                                   lower=0.2, upper=1.8)
        img = tf.image.per_image_standardization(distorted_image)
        label = tf.cast(features['label'], tf.int32)
        return img,label

    dataset = tf.data.TFRecordDataset(file_name)
    if shuffle:
        dataset = dataset.map(parser).repeat().batch(batch_size).shuffle(buffer_size=1000)
    else:
        dataset = dataset.map(parser).repeat().batch(batch_size)

    iterator = dataset.make_one_shot_iterator()

    img_input, label = iterator.get_next()
    return img_input,label

其中parser函数是自定义的解码函数,之前的代码介绍怎么封装数据,现在需要parser来解码,map(parser)的作用是运行parser这个函数,tf.data.TFRecordDataset(file_name)中的file_name是这样的格式

file_name=["/home/python/dataset/train2.tfrecords","/home/python/dataset/train1.tfrecords"]

可以使用几个不同的tfrecords文件,调用的方式就是
images_train, labels_train = read_and_decode(file_name,shuffle=True)

,然后使用images_train, labels_train = sess.run(images_train,labels_train),然后就可以feed数据了,代码如下

_, loss_value = sess.run([train_op, total_loss],
                                             feed_dict={images_holder: images_batch,
                                                        labels_holder: labels_batch})
好了,这个就是完整的制作tfrecords文件,并且使用tf.data来调用的教程。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值