Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 484
Wan-Duo Kurt Ma Avatar asked Sep 04 '26 23:09

Wan-Duo Kurt Ma


1 Answers

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)
like image 75
Ed Bordin Avatar answered Sep 07 '26 13:09

Ed Bordin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!