简体   繁体   English

具有动态形状TensorFlow的变量

[英]Variables with dynamic shape TensorFlow

I need to create a matrix in TensorFlow to store some values. 我需要在TensorFlow中创建一个矩阵来存储一些值。 The trick is the matrix has to support dynamic shape. 诀窍是矩阵必须支持动态形状。

I am trying to do the same I would do in numpy: 我正在尝试做与numpy中相同的操作:

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

where x=(?) and y=2 . 其中x=(?)y=2 But this does not work because zeros does not support 'partially known TensorShape', so, How should I do this in TensorFlow? 但这不起作用,因为零不支持``部分已知的TensorShape'',那么,我应该如何在TensorFlow中做到这一点?

1) You could use tf.fill(dims, value=0.0) which works with dynamic shapes. 1)您可以使用tf.fill(dims, value=0.0)处理动态形状。

2) You could use a placeholder for the variable dimension, like eg: 2)您可以为可变尺寸使用占位符,例如:

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

with tf.Session() as sess:
    print(sess.run(x, feed_dict={m: 5}))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM