Variables with dynamic shape TensorFlow

两盒软妹~` 提交于 2019-12-12 10:39:22

问题


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?


回答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}))



回答2:


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))}))


来源:https://stackoverflow.com/questions/43263017/variables-with-dynamic-shape-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!