I am trying to convert the following code in Numpy to Tensorflow, so that I can use that code in my neural network. Sadly, I have failed to so yet, due to the error, that Tensorflow does not support item assignment, which I would need for this code to work.
# 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)
"""
I have tried to do this first in a loop and then stack the lists up using tf.stack
, but that seems like a really non-tensorflow way (and it does not work on a GPU). What I would like to have is a way to do the aforementioned transformation for several batch sizes in Tensorflow. This answer suggests to use tf.where
but I also have no clue how to leverage this in that specific case. I would appreciate any help.
CodePudding user response:
You could slice and directly assign like this assuming the logic you have is simple as shown. But there are also other functions to do this.
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)
"""