Consider a n x n tensor, such as:
board = tf.zeros([9,9], dtype=tf.int32)
How do I add another tensor (matrix) to it? If this isn't possible, I want to know how to update the value of the (original) tensor (beginning at location (x, y)) with the values in the smaller to_add tensor. Thanks.
to_add = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.int32)
For example, how do I add the following matrices, starting at (1,0)
0 0 0 1 0 0 1 0
0 0 0 1 0 = 0 1 0
0 0 0 0 0 0
CodePudding user response:
import tensorflow as tf
board = tf.zeros([9,9], dtype=tf.int32)
to_add = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.int32)
start = (2, 3)
def add_t_to_t(t_large, t_small, start):
i, j = start
m, n = t_small.shape
large = t_large.numpy()
large[i:i m, j:j n] = t_small.numpy()
return tf.convert_to_tensor(large)
board = add_t_to_t(board, to_add, start)
print(board)
prints
tf.Tensor(
[[0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[0 0 0 1 2 3 0 0 0]
[0 0 0 4 5 6 0 0 0]
[0 0 0 7 8 9 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]], shape=(9, 9), dtype=int32)
Wouldn't know how to do this with pure tensorflow, but I am sure there is a (more cumbersome) way to do so.
CodePudding user response:
Add
follows NumPy broadcasting rules, so you need to add tensors that have the same shape. What you could use is tf.pad()
function to add padding to your to_add
and make it the same shape as board
Here is an example:
import tensorflow as tf
board = tf.zeros([9,9], dtype=tf.int32)
to_add = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.int32)
padding = tf.constant([[0,6],[1,5]], dtype=tf.int32)
padded = tf.pad(to_add, padding)
print('Pad:')
print(padded)
print('New Board:')
new_board = tf.add(board, padded)
print(new_board)
Output:
Pad:
tf.Tensor(
[[0 1 2 3 0 0 0 0 0]
[0 4 5 6 0 0 0 0 0]
[0 7 8 9 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]], shape=(9, 9), dtype=int32)
New Board:
tf.Tensor(
[[0 1 2 3 0 0 0 0 0]
[0 4 5 6 0 0 0 0 0]
[0 7 8 9 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]], shape=(9, 9), dtype=int32)