tensorflow batch函数实现

本文介绍了在TensorFlow中如何实现数据的批处理。通过一个线程读取硬盘上的图片并放入队列,另一个线程负责计算任务,直接从队列获取数据。使用tf.train.Coordinator创建线程协调器,调用tf.train.start_queue_runners启动线程,确保数据正确读取。tf.train.batch函数根据传入参数类型返回tensor列表或单个tensor。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

def get_batch(image, label, image_W, image_H, batch_size, capacity):
    
    image = tf.cast(image, tf.string)
    label = tf.cast(label, tf.int32)
    #生成列队
    input_queue = tf.train.slice_input_producer([image, label])
    
    label = input_queue[1]
    image_contents = tf.read_file(input_queue[0])
    image = tf.image.decode_jpeg(image_contents, channels=3)
    
    image = tf.image.resize_image_with_crop_or_pad(image, image_W, image_H)
    a = tf.reduce_mean(image)
    image = tf.subtract(image,a)
    
    image_batch, label_batch = tf.train.batch([image, label],
                                              batch_size= batch_size,
                                              num_threads= 16, 
                                              capacity = capacity)
 
    
    label_batch = tf.reshape(label_batch, [batch_size])
    image_batch = tf.cast(image_batch, tf.float3
### TensorFlow常见函数列表及说明 #### pad操作 `tf.pad()` 函数用于在张量的不同维度上增加填充。此操作对于卷积网络或自然语言处理任务至关重要[^1]。 ```python import tensorflow as tf paddings = [[1, 1], [2, 2]] tensor = tf.constant([[1, 2], [3, 4]]) result = tf.pad(tensor=tensor, paddings=paddings, mode='CONSTANT', constant_values=0) print(result.numpy()) ``` #### 创建常量张量 通过 `tf.constant()` 可创建一个具有特定值和形状的常量张量。如果提供的是单个数值,整个张量将被该值填满;如果是列表形式的数据,则会依据给定的形状依次填充这些值,当列表长度不足时,默认用最后一位元素补充剩余位置[^2]。 ```python constant_tensor_1d = tf.constant([1., 2., 3.]) constant_tensor_2d = tf.constant(7, shape=[2, 3]) print(constant_tensor_1d.numpy()) print(constant_tensor_2d.numpy()) ``` #### 数据集迭代器设置 利用 `tf.keras.utils.OrderedEnqueuer` 类可以在每个训练周期结束(`on_epoch_end`)后调整数据加载方式,比如开启多进程读取或者打乱样本顺序等[^3]。 ```python from tensorflow.keras.utils import OrderedEnqueuer sequence = ... # 定义自己的Sequence对象 enqueuer = OrderedEnqueuer(sequence, use_multiprocessing=True, shuffle=True) # 后续调用 enqueuer.start() 和获取 batch 的逻辑... ``` #### 改变张量形状 借助于 `tf.reshape()` 方法能够灵活改变输入张量的空间结构而不影响原始数据内容。只需指定新的目标尺寸即可完成转换过程[^4]。 ```python original_tensor = tf.random.uniform((2, 3)) reshaped_tensor = tf.reshape(original_tensor, [-1]) print('Original:', original_tensor.shape) print('Reshaped:', reshaped_tensor.shape) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值