我觉得问这个问题很尴尬,但是如何调整张量内的单个值?假设您只想将“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/