0

I made a simple example of numpy array indexing and assignment where the goal is to make a small white square on a black screen. How would I replicate the following code using Tensorflow?

black_img = np.zeros([5, 5, 3])
white_rect = np.ones([3, 3])
size = np.arange(3)

black_img[size, size] = white_rect

1 Answers1

0

You can create constants or variables in TensorFlow.

black_img = np.zeros([5, 5, 3], dtype = np.int32)
black_img_tf = tf.constant(np.zeros([5, 5, 3], dtype = np.int32))

Output:

<tf.Tensor: shape=(5, 5, 3), dtype=int32, numpy=
array([[[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])>

However, TensorFlow does not support item assignment like NumPy. However, you can create a new constant or variable using results obtained from NumPy operations.

Code:

black_img[size, size] = white_rect
tf.constant(black_img)

Output:

<tf.Tensor: shape=(5, 5, 3), dtype=int32, numpy=
array([[[1, 1, 1],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [1, 1, 1],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [1, 1, 1],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])>

Note that individual item assignment is not allowed but you can do operations like addition, subtraction on tensors.

c = tf.constant(np.ones([3, 3], dtype = np.int32)) + tf.constant(np.ones([3, 3], dtype = np.int32))
c

Output:

<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[2, 2, 2],
       [2, 2, 2],
       [2, 2, 2]])>
Aniket Bote
  • 3,456
  • 3
  • 15
  • 33
  • So what you are saying is that it is just not possible and my best bet would be to use numpy and convert back into TensorFlow? –  Aug 26 '20 at 18:11
  • Tensorflow doesn't support value assignments. If you try to do value assignments it will just throw a Type error. You can always get the desired results by doing other operations supported by tensorflow. Check [this](https://stackoverflow.com/questions/34685947/adjust-single-value-within-tensor-tensorflow) and [this](https://stackoverflow.com/questions/42883415/how-to-replace-a-value-within-a-tensor-by-indices?noredirect=1&lq=1) for your reference. – Aniket Bote Aug 26 '20 at 18:18