问题描述
问这个我很尴尬,但是你如何调整张量中的单个值?假设您只想将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.稀疏张量
.
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()
张量:
Let's say you have a 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, 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()
op 从 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)
这篇关于调整张量内的单个值——TensorFlow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!