tensorflow - TensorFlow 2.0 分散添加
问题描述
我想在 TensorFlow 2.0 中实现以下设计。
给定一个memory
形状张量[a, b, c]
、
一个indices
形状张量
和一个形状张 量[a, 1]
,updates
[a, c]
我想在中的值memory
指示的位置递增。indices
updates
tf.tensor_scatter_nd_add
似乎不起作用:
tf.tensor_scatter_nd_add(memory, indices, updates)
返回{InvalidArgumentError}Inner dimensions of output shape must match inner dimensions of updates shape. Output: [a,b,c] updates: [a,c] [Op:TensorScatterAdd]
。
真的有必要updates
拥有与 一样多的内部维度memory
吗?在我的逻辑中,memory[indices]
(作为伪代码)应该已经是一个张量 shape [a, c]
。而且,形状tf.gather_nd(params=memory, indices=indices, batch_dims=1)
已经是[a, c]
。
你能推荐一个替代品吗?
谢谢。
解决方案
我想你想要的是这样的:
import tensorflow as tf
a, b, c = 3, 4, 5
memory = tf.ones([a, b, c])
indices = tf.constant([[2], [0], [3]])
updates = 10 * tf.reshape(tf.range(a * c, dtype=memory.dtype), [a, c])
print(updates.numpy())
# [[ 0. 10. 20. 30. 40.]
# [ 50. 60. 70. 80. 90.]
# [100. 110. 120. 130. 140.]]
# Make indices for first dimension
ind_a = tf.range(tf.shape(indices, out_type=indices.dtype)[0])
# Make full indices
indices_2 = tf.concat([tf.expand_dims(ind_a, 1), indices], axis=1)
# Scatter add
out = tf.tensor_scatter_nd_add(memory, indices_2, updates)
print(out.numpy())
# [[[ 1. 1. 1. 1. 1.]
# [ 1. 1. 1. 1. 1.]
# [ 1. 11. 21. 31. 41.]
# [ 1. 1. 1. 1. 1.]]
#
# [[ 51. 61. 71. 81. 91.]
# [ 1. 1. 1. 1. 1.]
# [ 1. 1. 1. 1. 1.]
# [ 1. 1. 1. 1. 1.]]
#
# [[ 1. 1. 1. 1. 1.]
# [ 1. 1. 1. 1. 1.]
# [ 1. 1. 1. 1. 1.]
# [101. 111. 121. 131. 141.]]]
推荐阅读
- javascript - 将 react-datepicker css 加载到 jsx 文件中的问题
- python - 当 A 是条纹矩阵时,如何使用 scipy.linalg.solve_banded 求解 Ax = b?
- html - 具有不透明度值的悬停背景和具有不透明度不同值的悬停按钮
- jenkins - 失败的 Git 和 Github 插件及其在 Jenkins 中的依赖项安装
- php - 如何使用内部联接从两个日期之间的数据库中获取数据?
- python-3.6 - 尝试安装到 virtualenv 时出现 Pipenv 错误
- android - SecurityException:调用者不再运行,上次停止
- maven-3 - 如何解决“产品不包含强制属性'版本'。请确保您在产品文件中输入了版本”
- javascript - 无法从滚动条中选择视频的搜索时间
- javascript - 错误:捆绑失败:TypeError:无法读取 null 的属性“绑定”