Tensorflow 中的项目分配

Item assignment in Tensorflow

我正在尝试将 Numpy 中的以下代码转换为 Tensorflow,以便我可以在我的神经网络中使用该代码。可悲的是,由于错误,我还没有这样做,Tensorflow 不支持项目分配,我需要这个代码才能工作。

# Create zeros matrices
l_bbox = np.zeros((6,6), np.float32)
l_score = np.zeros((1,6,6), np.float32)
# Set coordinates
x1, y1, x2, y2 = 1, 1, 5, 4
# Assign coordinates to the zeros matrix
l_score[:, y1:y2, x1:x2] = 1.
l_score
"""
array([[[0., 0., 0., 0., 0., 0.],
        [0., 1., 1., 1., 1., 0.],
        [0., 1., 1., 1., 1., 0.],
        [0., 1., 1., 1., 1., 0.],
        [0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0.]]], dtype=float32)
"""
# Assign varying values to l_bbox
for yy in range(y1, y2):
    l_bbox[yy, x1:x2] = yy - y1
l_bbox
"""
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 1., 0.],
       [0., 2., 2., 2., 2., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]], dtype=float32)
"""

我尝试先在一个循环中执行此操作,然后使用 tf.stack 堆叠列表,但这似乎是一种真正的非张量流方式(并且它不适用于 GPU)。我想要的是一种在 Tensorflow 中对多个批量大小进行上述转换的方法。 答案建议使用 tf.where 但我也不知道如何在特定情况下利用它。如果有任何帮助,我将不胜感激。

假设您拥有的逻辑如图所示简单,您可以像这样切片并直接赋值。但是还有其他功能可以做到这一点。

import numpy as np
import tensorflow as tf

tfl_bbox = tf.Variable(tf.zeros([6, 6]))
tfl_score = tf.Variable(tf.zeros([1, 6, 6]))
# Set coordinates
x1, y1, x2, y2 = 1, 1, 5, 4
# Assign coordinates to the zeros matrix
tfl_score[:, y1:y2, x1:x2].assign(tf.ones_like(tf.constant(1,shape=(1,y2-y1,x2-x1)), dtype=tf.float32))

# Create zeros matrices
l_bbox = np.zeros((6,6), np.float32)
l_score = np.zeros((1,6,6), np.float32)
# Set coordinates
x1, y1, x2, y2 = 1, 1, 5, 4
# Assign coordinates to the zeros matrix
l_score[:, y1:y2, x1:x2] = 1.
print(l_score)
print(tfl_score)
"""
array([[[0., 0., 0., 0., 0., 0.],
        [0., 1., 1., 1., 1., 0.],
        [0., 1., 1., 1., 1., 0.],
        [0., 1., 1., 1., 1., 0.],
        [0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0.]]], dtype=float32)
"""
# Assign varying values to l_bbox
for yy in range(y1, y2):
    l_bbox[yy, x1:x2] = yy - y1
    tfl_bbox[yy, x1:x2].assign(tf.constant(yy - y1,shape=(x2-x1), dtype=tf.float32))
print(l_bbox)
print(tfl_bbox)
"""
array([[0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 1., 1., 1., 1., 0.],
       [0., 2., 2., 2., 2., 0.],
       [0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0.]], dtype=float32)
"""