Search code examples
pythontensorflowassignbroadcasting

tensorflow variable assign broadcasting


is there any method in tensorflow can achieve the broadcasting assignment to matrix (tf.Variable) something like the following code....

a    = tf.Variable(np.zeros([10,10,10,10], np.int32))

# creating a mask and trying to assign the 2nd, 3rd dimension of a
mask = tf.ones([10,10])

# 1) which is work in this case, but only assign one block
op = a[0,:,:,0].assign(mask)

# 2) attempting to broadcasting while not work, size mismatch
op = a[0].assign(mask)

for me current solution might iterate all other dimensions but might suffered from nested looping as in 1) or there must be a smarter way to do so, thanks !


Solution

  • Not a general solution (plenty of hardcoded tensor shapes), but hopefully this gives you the gist for your example:

    a = tf.Variable(np.zeros([10,10,10,10], np.int32))
    mask = tf.ones([10,10],dtype=tf.int32)
    mask_reshaped = tf.reshape(mask,[1,10,10,1]) # make the number of dims match
    mask_broadcast = tf.tile(mask_reshaped, [10, 1, 1, 10]) # do the actual broadcast
    op = a.assign(mask_broadcast)