6

I need to create a matrix in TensorFlow to store some values. The trick is the matrix has to support dynamic shape.

I am trying to do the same I would do in numpy:

myVar = tf.Variable(tf.zeros((x,y), validate_shape=False)

where x=(?) and y=2. But this does not work because zeros does not support 'partially known TensorShape', so, How should I do this in TensorFlow?

gergf
  • 118
  • 1
  • 8
  • Why do you need a dynamic shape? And can't you fix it by using None as shape descriptor? – rmeertens Apr 07 '17 at 06:27
  • 1
    Because my matrix depends of the number of samples in the batch, which can change. As far as I know, neither tf.zeros or np.zeros accept a None in the shape. – gergf Apr 07 '17 at 06:40
  • Ah, I see. May I ask what you want to do with this matrix?? – rmeertens Apr 07 '17 at 07:20
  • Sure. I'am programming a weighted_softmax for semantic segmentation. I want to weight each class by its prior, so I am calculating the prior of each image when I receive the true labels in the loss function: I need the matrix to store that priors. It would be easier if the loss function could receive additional parameters, so I can compute the priors with Numpy and feed TensorFlow with it, but I don't know any way of doing that. – gergf Apr 07 '17 at 07:47

2 Answers2

1

1) You could use tf.fill(dims, value=0.0) which works with dynamic shapes.

2) You could use a placeholder for the variable dimension, like e.g.:

m = tf.placeholder(tf.int32, shape=[])
x = tf.zeros(shape=[m])

with tf.Session() as sess:
    print(sess.run(x, feed_dict={m: 5}))
kafman
  • 2,862
  • 1
  • 29
  • 51
1

If you know the shape out of the session, this could help.

import tensorflow as tf
import numpy as np

v = tf.Variable([], validate_shape=False)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(v, feed_dict={v: np.zeros((3,4))}))
    print(sess.run(v, feed_dict={v: np.zeros((2,2))}))
hychiang
  • 11
  • 1