1

I would like to slice a tensor and store it in a variable. Slicing with fixed numbers works fine eg: t[0:2]. But slicing a variable with another tensor doesnt work. eg t[t1:t2] Also storing the slice in a tensor works fine but when I try to store it in a tf.Variable i get errors.

import tensorflow as tf
import numpy

i=tf.zeros([2,1],tf.int32)
i2=tf.get_variable('i2_variable',initializer=i) #putting a multidimensional tensor in a variable
i4=tf.ones([10,1],tf.int32)
sess=tf.Session()
sess.run(tf.global_variables_initializer()) #initializing variables
itr=tf.constant(0,tf.int32)

def w_c(i2,itr):
    return tf.less(itr,2)

def w_b(i2,itr):
    i2=i4[(itr*0):((itr*0)+2)] #doesnt work
    #i2=i4[0:2] #works
    #i=i4[(itr*0):((itr*0)+2)] #works with tensor i 
    itr=tf.add(itr,1)
    return[i2,itr]
OP=tf.while_loop(w_c,w_b,[i2,itr])
print(sess.run(OP))

I get following error:

ValueError: Input tensor 'i2_variable/read:0' enters the 
loop with shape (2, 1), but has shape (?, 1) after one iteration. 
To allow the shape to vary across iterations, 
use the `shape_invariants` argument of tf.while_loop to specify a less-specific shape.

1 Answer 1

1

The code does not throw the error if you specify shape_invariants.

   OP=tf.while_loop(w_c,w_b,[i2,itr],shape_invariants=
                                        [ tf.TensorShape([None, None]), 
                                          itr.get_shape()])

It returns this.

  [array([[1],
   [1]]), 2]
Sign up to request clarification or add additional context in comments.

6 Comments

is it mandatory to set shape_invariants even when shape of i2 is same as the value inserted into it.
Not able to give you an expert opinion. But based on the message loop with shape (2, 1), but has shape (?, 1) after one iteration. I relaxed it to be more general. You may also read this
I tried tf.assign(i2, i4[(itr*0):((itr*0)+2)] ). It works normally but doesnt work inside a while loop body.. I get error saying Tensor object has no attribute 'assign' .
Variable i2 is not getting updated coz its not assigned and returned in the while loop. tf.assign returns a tensor so you need to save it into a node and call that node as a while loop variable. 'sess.run([OP,i2])' add this to the end of your code and you will see that i2 value is unchanged.
I have restored the answer to its original state. You may ask another question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.