2

I want to do for loop's with dynamic inputs in tensorflow.

I know for the code below reduce_sum is sufficient, but I want to be able to formulate code in the manner described below. So given that I have an array with different sizes, I want to traverse that array.

How can I traverse dynamic length arrays?

Problem:

TypeError: range() integer end argument expected, got Tensor

How can I evaluate get_sum that is outside the session?

sum = get_sum(x, xshape) shouldn't be in the for loop inside session

For example:

import tensorflow as tf
import numpy as np


x = tf.placeholder(tf.float32, shape=[None])
xshape = tf.placeholder(tf.float32, shape=[])


def get_sum(x, xshape):
  sum = 0
  for i in range(xshape):
    sum += x[i]

init = tf.initialize_all_variables()
sum = get_sum(x, xshape)

with tf.Session() as sess:
  sess.run(init)
  for i in range(100):
    length = np.random.randint(0,10)
    a = np.random.randint(0, 10, length)
  print sess.run(sum,feed_dict={x:a, xshape:length})
5
  • 2
    If the number of iterations is unknown ahead of time, wouldn't another kind of loop be more appropriate? Commented Mar 13, 2016 at 15:40
  • what kind of loop? Commented Mar 13, 2016 at 15:41
  • Perhaps a while loop. Commented Mar 13, 2016 at 15:41
  • it is the same problem, you can't get shape as an integer; how are you going to use while loop?- the problem is to convert the shape into an integer, we need to evaluate it; the problem is how? Commented Mar 13, 2016 at 15:43
  • So your question has nothing to do with a loop, but rather how to get a certain integer: got it. Commented Mar 13, 2016 at 15:46

1 Answer 1

1

Dynamic loops are still young in TensorFlow, but they exist. Take a look for example at the fold operators and their implementation. https://www.tensorflow.org/versions/master/api_docs/python/control_flow_ops.html#foldl

Sign up to request clarification or add additional context in comments.

2 Comments

What is the situation now? Thank you
Dynamic loops are well-supported now and there is a number of higher-level operators to make using them easier. You can do, e.g., elems = [1, 2, 3, 4, 5, 6] ; sum = tf.foldl(lambda a, x: a + x, elems), check out tf.foldl and tf.scan API docs. tensorflow.org/api_docs/python/tf/foldl

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.