2017-09-01 106 views
1

有在tensorflow任何方法都可以实现广播分配矩阵(tf.Variable) 类似下面的代码....tensorflow变量分配广播

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) 

我目前的解决方案可能会遍历所有其他尺寸但可能遭受嵌套循环,如1) 或者必须有一个更聪明的方法来做到这一点,谢谢!

回答

0

不是一般的解决方案(大量的硬编码张量形状的),但我希望这给你的要点为你的例子:

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) 
+0

什么好的技巧!谢谢!它真的很整齐。 –