在张量流中操纵矩阵元素

Sha*_*gas 10 indexing element matrix variable-assignment tensorflow

如何在tensorflow中执行以下操作?

mat = [4,2,6,2,3] #
mat[2] = 0 # simple zero the 3rd element
Run Code Online (Sandbox Code Playgroud)

我不能使用[]括号,因为它只适用于常量而不适用于变量.我不能使用切片函数,因为它返回一个张量,你不能分配张量.

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)
Run Code Online (Sandbox Code Playgroud)

会打印

[2, 5, -4, 0] 
[2, 5, 0, 0])
Run Code Online (Sandbox Code Playgroud)

dga*_*dga 19

您无法更改张量 - 但是,如您所述,您可以更改变量.

您可以使用三种模式来完成您想要的任务:

(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)
Run Code Online (Sandbox Code Playgroud)

[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)因为它们与普通张量一起工作,而不仅仅是变量.