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

2023-11-25

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

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

TypeError: 'Tensor' object does not support item assignment

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

我已经多次阅读 API 文档,但似乎不知道如何做到这一点。提前致谢!


UPDATE:TensorFlow 1.0 包括tf.scatter_nd()运算符,可用于创建delta下面没有创建tf.SparseTensor.


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

假设你有一个tf.constant() tensor:

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

...并且您想添加1.0在位置 [1, 1]。实现此目的的一种方法是定义一个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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

调整张量内的单个值——TensorFlow 的相关文章

随机推荐