【问题标题】:Batch operation on tensors in TensorFlowTensorFlow中张量的批量操作
【发布时间】:2020-09-01 23:23:50
【问题描述】:

我有一批图像表示为 TensorFlow 张量(比如张量 1),形状为 (2,1024,1024,1),形式为 (B,H,W,C),其中B 是批量大小 2,HW 是图像尺寸 1024 C 是通道数。这个张量的每个元素(即每个像素)存储一个元组(a,b),其中ab 都在0255 范围内。

我有另一个形状为(256,256) 的张量(比如张量 2),每个元素在0255 之间存储一个值。

鉴于此设置,我有以下问题。

我希望将张量 1 中的每个元素值替换为张量 2 中对应的元素值。例如,假设张量 1 中索引(1,200,500,1) 给出的元素包含值(100,20)。我想在像素位置(100,200) 中查找存储在张量 2 中的值,并使用此值修改(1,200,500,1) 处的条目。

我怎样才能以最有效的方式为整个批次做到这一点?

如果有什么不清楚的地方请告诉我。我是 TensorFlow 的初学者,因此将不胜感激。

【问题讨论】:

    标签: python tensorflow batch-processing tensor


    【解决方案1】:

    用 Tensor 2 中的相应元素值替换 Tensor 1 中的元素值尝试这种方式

    tensor1 = tf.Variable(tf.zeros((2,1024,1024,1)), trainable=False)
    tensor2 = tf.constant(np.random.randint(0,255, (255,255,1)), dtype='float32')
    
    tensor12 = tensor1[1,200,500].assign(tensor2[100,200])
    

    在此示例中,您将张量 1 的位置 (1,200,500,1) 中的元素替换为张量 2 的位置 (100,200) 中的元素


    batch_dim = 2
    tensor1 = tf.Variable(tf.zeros((batch_dim,1024,1024,1)), trainable=False)
    tensor2 = tf.constant(np.random.randint(0,255, (1,255,255,1)), dtype='float32')
    
    tensor12 = tensor1[:,:tensor2.shape[1],:tensor2.shape[2]].assign(tf.repeat(tensor2, batch_dim, axis=0))
    

    通过这些行,您将 tensor2 的所有值分配给该批次的所有样本的 tensor1 中的第一个 (255,255) 位置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多