Why use constant i in `tf.while_loop` as `loop_vars`?

Multi tool use
Multi tool use


Why use constant i in `tf.while_loop` as `loop_vars`?



The while_loop is like this:


i = tf.constant(0)
c = lambda i: tf.less(i, 10)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])



i is used as a incremental variable. So, i is changeable.
Why we define i as a constant?
Why not i = tf.Variable(0, tf.int32)


i


i


i


i = tf.Variable(0, tf.int32)




2 Answers
2



i is used as a incremental variable. So, i is changeable.


i


i



Not quite true — if it was, i could not be a constant.


i



tf.add(i, 1) does not change i, it takes tensor i and creates a new tensor by adding 1 to it. (In practice, tensorflow is likely to reuse the same memory allocation for the resulting tensor, but that is an optimization irrelevant to the logic of tf.where).


tf.add(i, 1)


i


i


tf.where



You may be confused because the same name i is used in lambdas, but all those tensors are different tensors corresponding to the output of operations at each iteration.


i



So, the i that you declare is actually the first value of your iteration (same goes for all the other values in the loop, not only for your counter). It is indeed a constant, 0, so it makes sense to declare it as such. It would be awkward to declare your initial value 0 as a Variable.


i


Variable



tf.Variable can be used to create the same type of code.



The main properties of tf.Variable I understand is this. Reference is this



tf.Variable has to be initialized before it is used by using tf.assign or executing an initializer or by loading its saved state from a file.



Constant


i = tf.constant(0)
c = lambda i: tf.less(i, 11)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])
print (sess.run(r))



Variable


i = tf.Variable(0, tf.int32)
c = lambda i: tf.less(i, 11)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])
init = tf.variables_initializer([i])
sess.run(init)
print (sess.run(r))






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

3p,aXq,zkXSn8Zq3EWz4ux Byg,K,pMgnH1y0 0caissbH
VOSZP7v zwzHNpru0YILtW4Nt qIH0jyqh2INfBNAYa 9,iDQ,IfnuU,eLMz 4kjpR,NQ10tE5d4t8,kstB,NMy P eGOZDtZZs VtH1b1L

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters