Manipulating matrix elements in tensorflow

后端 未结 1 1711
南旧
南旧 2020-12-09 12:05

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 becaus

1条回答
  •  盖世英雄少女心
    2020-12-09 13:05

    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)
    

    [ 2 5 -4 0]

    [ 2 9 -4 0]

    [ 2 9 -4 0]

    (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.

    0 讨论(0)
提交回复
热议问题