问题描述
如何在 tensorflow 中执行以下操作?
mat = [4,2,6,2,3] #mat[2] = 0 # 第三个元素简单归零
我不能使用 [] 括号,因为它只适用于常量而不适用于变量.我不能使用 slice 函数,因为它返回一个张量而你不能分配给一个张量.
将 tensorflow 导入为 tfsess = tf.Session()var1 = tf.Variable(initial_value=[2, 5, -4, 0])assignZerosOP = (var1[2] = 0) # <------ 这就是我想做的sess.run(tf.initialize_all_variables())打印 sess.run(var1)sess.run(assignZerosOP)打印 sess.run(var1)
将打印
[2, 5, -4, 0][2, 5, 0, 0])
你不能改变张量 - 但是,正如你所指出的,你可以改变一个变量.
您可以使用三种模式来完成您想要的:
(a) 使用 tf.scatter_update
直接戳到你想改变的变量部分.
将 tensorflow 导入为 tfa = tf.Variable(initial_value=[2, 5, -4, 0])b = tf.scatter_update(a, [1], [9])init = tf.initialize_all_variables()使用 tf.Session() 作为 s:s.run(init)打印 s.run(a)打印 s.run(b)打印 s.run(a)
[ 2 5 -4 0]
[ 2 9 -4 0]
[ 2 9 -4 0]
(b) 创建两个 tf.slice()
的张量,不包括要改变的项,然后 tf.concat(0, [a, 0, b])
将它们重新组合在一起.
(c) 创建b = tf.zeros_like(a)
,然后使用tf.select()
从a
中选择哪些项> 你想要,以及你想要的 b
中的哪些零.
我包含 (b) 和 (c) 是因为它们适用于普通张量,而不仅仅是变量.
How can I do the following in tensorflow?
mat = [4,2,6,2,3] #
mat[2] = 0 # simple zero the 3rd element
I can't use the [] brackets because it only works on constants and not onvariables. I cant use the slice function either because that returns a tensor and you can't assign to a tensor.
import tensorflow as tf
sess = tf.Session()
var1 = tf.Variable(initial_value=[2, 5, -4, 0])
assignZerosOP = (var1[2] = 0) # < ------ This is what I want to do
sess.run(tf.initialize_all_variables())
print sess.run(var1)
sess.run(assignZerosOP)
print sess.run(var1)
Will print
[2, 5, -4, 0]
[2, 5, 0, 0])
You can't change a tensor - but, as you noted, you can change a variable.
There are three patterns you could use to accomplish what you want:
(a) Use tf.scatter_update
to directly poke to the part of the variable you want to change.
import tensorflow as tf
a = tf.Variable(initial_value=[2, 5, -4, 0])
b = tf.scatter_update(a, [1], [9])
init = tf.initialize_all_variables()
with tf.Session() as s:
s.run(init)
print s.run(a)
print s.run(b)
print s.run(a)
(b) Create two tf.slice()
s of the tensor, excluding the item you want to change, and then tf.concat(0, [a, 0, b])
them back together.
(c) Create b = tf.zeros_like(a)
, and then use tf.select()
to choose which items from a
you want, and which zeros from b
that you want.
I've included (b) and (c) because they work with normal tensors, not just variables.
这篇关于在张量流中操作矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!