python - tensorflow 变量分配广播

标签 python tensorflow assign broadcasting

tensorflow中有没有什么方法可以实现对矩阵(tf.Variable)的广播赋值 类似于下面的代码....

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) 或者必须有更聪明的方法,谢谢!

最佳答案

不是通用解决方案(大量硬编码张量形状),但希望这能为您的示例提供要点:

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)

关于python - tensorflow 变量分配广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992522/

相关文章:

python - 从 Tensorflow 中删除变量

lisp - Lisp 中的赋值

joomla - 文章作为主页,没有连接菜单

python - 使用 shutil 模块删除目录

python - Django:我需要将两个外键值传递到我的数据库以跟踪评论和用户

python - TensorFlow - tf.layers 与 tf.contrib.layers

轻松记忆起许多不同名称的变量

python - 意外的 split() 行为 Python

python - 如何使用 pandas 从当前行获取过去 12 个月的产品

r - 是否有 R 命令使 Keras Tensorflow-GPU 在 CPU 上运行?