Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables with dynamic shape TensorFlow

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?

like image 855
gergf Avatar asked Apr 06 '17 18:04

gergf


People also ask

How do you initialize a TensorFlow variable in a matrix?

First, remember that you can use the TensorFlow eye functionality to easily create a square identity matrix. We create a 5x5 identity matrix with a data type of float32 and assign it to the Python variable identity matrix. So we used tf. eye, give it a size of 5, and the data type is float32.

Is tf variable trainable?

To make this easier, the variable constructor supports a trainable=<bool> parameter. tf. GradientTape watches trainable variables by default: with tf.


2 Answers

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}))
like image 76
kafman Avatar answered Sep 22 '22 07:09

kafman


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))}))
like image 44
hychiang Avatar answered Sep 23 '22 07:09

hychiang