Justin Liang Justin Liang - 1 year ago 148
Python Question

Using a loop to populate a matrix in TensorFlow

So I'm trying to populate a matrix in TensorFlow, the size of this matrix changes depending on the inputs so I'm using TensorArray to do it. Essentially, the Numpy equivalent of this is:

areas = np.zeros((len(rows)-1,len(cols)-1))
for r in range(len(rows)-1):
for c in range(len(cols)-1):
areas[r,c] = (rows[r+1]-rows[r])*(cols[c+1]-cols[c])

I tried to implement this in TensorFlow using

i = tf.constant(0)
areas = tf.TensorArray(dtype='float32', size=length_rc-1)
while_condition = lambda i, rows, areas: tf.less(i, length_rc-1)
def row_loop(i, rows, areas):
j = tf.constant(0)
area = tf.TensorArray(dtype='float32', size=length_rc-1)
while_condition = lambda j, cols, area: tf.less(j, length_rc-1)

def col_loop(j, cols, area):
area = area.write(j, tf.multiply(tf.subtract(rows[i+1],rows[i]),tf.subtract(cols[j+1],cols[j])))
return [tf.add(j,1), cols, area]

r = tf.while_loop(while_condition, col_loop, [j, cols, areas])
areas = areas.write(i, r[2].stack())
return [tf.add(i, 1), rows, areas]

# do the loop:
r = tf.while_loop(while_condition, row_loop, [i, rows, areas])
areas = r[2].stack()

p = sess.run([areas], feed_dict={pred_batch: pred, gt_batch: gt})

However, it does not seem to work and I'm not sure why. As you can see my code is similar to this post:
Howe TensorArray and while_loop work together in tensorflow?

But it does not seem to work, anyone know what the issue is? The specific error I'm getting is:

ValueError: Inconsistent shapes: saw (?,) but expected () (and infer_shape=True)

Answer Source

Found the tiny bug:

# do the loop:
r = tf.while_loop(while_condition, row_loop, [i, rows, areas])
areas = r[2].stack()

My input to tf.while_loop was incorrect, it should have been area instead of areas. Other than that, this is a valid way to do a nested loop to populate a matrix.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download