在Tensor中调整单值 - TensorFlow [英] Adjust Single Value within Tensor -- TensorFlow

查看:978
本文介绍了在Tensor中调整单值 - TensorFlow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很尴尬地问这个问题,但是你如何调整张量中的单个值呢?假设你想在张量中只有一个值加1?

I feel embarrassed asking this, but how do you adjust a single value within a tensor? Suppose you want to add '1' to only one value within your tensor?

通过索引做这件事不起作用:

Doing it by indexing doesn't work:

TypeError: 'Tensor' object does not support item assignment

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

One approach would be to build an identically shaped tensor of 0's. And then adjusting a 1 at the position you want. Then you would add the two tensors together. Again this runs into the same problem as before.

我已经多次读过API文档了,似乎无法弄清楚如何做到这一点。提前致谢!

I've read through the API docs several times and can't seem to figure out how to do this. Thanks in advance!

推荐答案

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

UPDATE: TensorFlow 1.0 includes a tf.scatter_nd() operator, which can be used to create delta below without creating a tf.SparseTensor.

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

This is actually surprisingly tricky with the existing ops! Perhaps somebody can suggest a nicer way to wrap up the following, but here's one way to do it.

假设你有一个 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 ,代表变化:

...and you want to add 1.0 at location [1, 1]. One way you could do this is to define a tf.SparseTensor, delta, representing the change:

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() 操作从 delta 制作密集张量,并将其添加到 c

Then you can use the tf.sparse_tensor_to_dense() op to make a dense tensor from delta and add it to 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)

这篇关于在Tensor中调整单值 - TensorFlow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆