批量读取数据next_batch()的简单函数实现

读取方法过程

Method()
# 随机取batch_size个训练样本  
import numpy as np

def next_batch(train_data, train_target, batch_size):  
    index = [ i for i in range(0,len(train_target)) ]  
    np.random.shuffle(index);  
    batch_data = []; 
    batch_target = [];  
    for i in range(0,batch_size):  
        batch_data.append(train_data[index[i]]);  
        batch_target.append(train_target[index[i]])  
    return batch_data, batch_target  

解释: 使用改了numpy中的shuffle(index)函数’
numpy.random.shuffle(x)
Modify a sequence in-place by shuffling its contents.

This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same.

>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8]
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
Python读取TFRecord文件的方法如下: ```python import tensorflow as tf # 创建一个TFRecordDataset对象 dataset = tf.data.TFRecordDataset('data.tfrecord') # 定义读取函数 def parser(record): features = { 'image': tf.io.FixedLenFeature([], dtype=tf.string), 'label': tf.io.FixedLenFeature([], dtype=tf.int64) } parsed = tf.io.parse_single_example(record, features) image = tf.io.decode_jpeg(parsed['image'], channels=3) label = parsed['label'] return image, label # 应用读取函数到每个record dataset = dataset.map(parser) # 创建迭代器 iterator = dataset.make_one_shot_iterator() # 获取数据 image, label = iterator.get_next() ``` 以上代码演示了如何读取名为`data.tfrecord`的TFRecord文件,并解析其中的图像和标签信息。在解析函数`parser`中,我们先定义了TFRecord文件中包含的特征信息,然后使用`tf.io.parse_single_example`函数解析单个record,并对图像数据进行解码。最后,我们使用`map`函数将解析函数应用到每个record上。 当然,如果您使用的是PyTorch,也可以使用以下代码读取TFRecord文件: ```python import torch import torchvision.datasets as datasets import torchvision.transforms as transforms # 定义解析函数 def parser(record): features = { 'image': tf.io.FixedLenFeature([], dtype=tf.string), 'label': tf.io.FixedLenFeature([], dtype=tf.int64) } parsed = tf.io.parse_single_example(record, features) image = tf.io.decode_jpeg(parsed['image'], channels=3) label = parsed['label'] return image, label # 创建数据集对象 dataset = datasets.DatasetFolder( 'data.tfrecord', loader=lambda x: torch.load(x), extensions=('tfrecord') ) # 应用解析函数到每个record dataset.transform = transforms.Compose([ parser ]) # 创建数据加载器 dataloader = torch.utils.data.DataLoader( dataset, batch_size=32, shuffle=True ) # 获取数据 for images, labels in dataloader: # 使用数据进行训练或预测 pass ``` 以上代码演示了如何使用PyTorch的`DatasetFolder`读取TFRecord文件,并使用解析函数`parser`解析图像和标签信息。最后,我们创建了一个数据加载器,并使用其中的数据进行训练或预测。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@RichardWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值