我如何在 tensorflow 中执行以下操作?
mat = [4,2,6,2,3] #
mat[2] = 0 # simple zero the 3rd element
我不能使用[]括号,因为它仅适用于常量而不适用于
变量。我不能使用slice函数,因为这会返回张量,并且您无法分配给张量。
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)
会列印
[2, 5, -4, 0]
[2, 5, 0, 0])
最佳答案
您无法更改张量-但正如您指出的,您可以更改变量。
您可以使用三种模式来完成所需的工作:
(a)使用 tf.scatter_update
直接戳到要更改的变量部分。
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)
[ 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)是因为它们与正常张量一起工作,而不仅仅是变量。
关于matrix - 在 tensorflow 中操纵矩阵元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35769944/