Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating matrix elements in tensorflow

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 on variables. 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])
like image 970
Shagas Avatar asked Mar 03 '16 10:03

Shagas


People also ask

Which operator is used to perform matrix multiplication on tensors?

Tensor Hadamard Product As with matrices, the operation is referred to as the Hadamard Product to differentiate it from tensor multiplication. Here, we will use the “o” operator to indicate the Hadamard product operation between tensors. In NumPy, we can multiply tensors directly by multiplying arrays.

How do you access the element in a tensor?

To access elements from a 3-D tensor Slicing can be used. Slicing means selecting the elements present in the tensor by using “:” slice operator. We can slice the elements by using the index of that particular element.


1 Answers

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.

like image 179
dga Avatar answered Sep 25 '22 16:09

dga