indexing - 调整张量内的单个值——TensorFlow

标签 indexing addition tensorflow

我觉得问这个问题很尴尬,但是如何调整张量内的单个值?假设您只想将“1”添加到张量中的一个值?

通过索引来做到这一点是行不通的:

TypeError: 'Tensor' object does not support item assignment

一种方法是构建一个形状相同的 0 张量。然后在你想要的位置调整一个1。然后将两个张量加在一起。这又遇到了与之前相同的问题。

我已经多次阅读 API 文档,但似乎不知道如何执行此操作。提前致谢!

最佳答案

更新:TensorFlow 1.0 包括 tf.scatter_nd()运算符,可用于创建下面的 delta,而无需创建 tf.SparseTensor

<小时/>

对于现有的操作来说,这实际上是非常棘手的!也许有人可以建议一种更好的方法来结束以下内容,但这是一种方法。

假设您有一个 tf.constant() 张量:

c = tf.constant([[0.0, 0.0, 0.0],
                 [0.0, 0.0, 0.0],
                 [0.0, 0.0, 0.0]])

...并且您想在位置 [1, 1] 添加 1.0。实现此目的的一种方法是定义 tf.SparseTensor , delta,代表变化:

indices = [[1, 1]]  # A list of coordinates to update.

values = [1.0]  # A list of values corresponding to the respective
                # coordinate in indices.

shape = [3, 3]  # The shape of the corresponding dense tensor, same as `c`.

delta = tf.SparseTensor(indices, values, shape)

然后您可以使用tf.sparse_tensor_to_dense() op 从 delta 生成稠密张量并将其添加到 c:

result = c + tf.sparse_tensor_to_dense(delta)

sess = tf.Session()
sess.run(result)
# ==> array([[ 0.,  0.,  0.],
#            [ 0.,  1.,  0.],
#            [ 0.,  0.,  0.]], dtype=float32)

关于indexing - 调整张量内的单个值——TensorFlow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34685947/

相关文章:

python - 有条件地创建零梯度的自定义 Keras 损失函数

python - 将 tensorflow tf.data.Dataset FlatMapDataset 转换为 TensorSliceDataset

performance - Postgres 上的 "update table"操作非常慢

assembly - 为什么我们要使用addiu而不是addi?

sql - postgresql中的连接索引

java - 单击java中的按钮后将(多个)表单添加到ScrollPane

jquery - 如何在javascript中强制添加而不是连接

python - Tensorflow slim 训练和验证初始模型

mysql - 我应该在用户和用户状态列中创建复合索引吗?

python - 如果索引模数 7 == 0,则从每个 block 中提取每个字符