简体   繁体   English

TensorFlow - 根据另一个变量的形状动态定义变量的形状

[英]TensorFlow - Defining the shape of a variable dynamically, depending on the shape of another variable

Say I have a certain the Tensor x whose dimensions are not defined upon graph initialization. 假设我有一个Tensor x其尺寸未在图初始化时定义。

I can get its shape using: 我可以使用以下形状:

x_shape = tf.shape(input=x)

Now if I want to create a variable based on the values defined in x_shape using: 现在,如果我想基于x_shape定义的值创建变量,使用:

y = tf.get_variable(variable_name="y", shape=[x_shape[0], 10])

I get an error, since the values passed to the argument shape must be int and not Tensor . 我得到一个错误,因为传递给参数形状的值必须是int而不是Tensor How can I create such a dynamically shaped variable without using placeholders? 如何在不使用占位符的情况下创建这样的动态形状变量?

I'm running out of time so this is quick and dirty, but maybe it helps you to get to your solution... It's based on this (dynamic size for tf.zeros) but extends the idea to tf.Variables. 我已经没时间了,所以这很快又很脏,但也许它可以帮助你找到你的解决方案...它基于这个(动态大小为tf.zeros),但将想法扩展到tf.Variables。 Since your variable needs to be initialized anyway - I choose 0s... 既然你的变量需要初始化 - 我选择0 ...

import tensorflow as tf
I1_ph = tf.placeholder(name = "I1",shape=(None,None,None),dtype=tf_dtype)

zerofill = tf.fill(tf.shape(I1_ph), 0.0)
myVar = tf.Variable(0.0)
updateMyVar = tf.assign(myVar,zerofill,validate_shape=False)

res, = sess.run([updateMyVar], { I1_ph:np.zeros((1,2,2)) } )
print ("dynamic variable shape",res.shape)

res, = sess.run([updateMyVar], { I1_ph:np.zeros((3,5,2)) } )
print ("dynamic  variable shape",res.shape)
import tensorflow as tf

x = tf.zeros(shape=[10,20])
x_shape = x.get_shape().as_list()
y = tf.get_variable(shape=x_shape, name = 'y')

Update 更新

You can't create tf.Variable with unknown size. 您无法创建未知大小的tf.Variable For example this code is not valid: 例如,此代码无效:

y = tf.get_variable(shape=[None, 10], name = 'y')

您可以使用x.get_shape()

y = tf.get_variable('y', shape=[x.get_shape()[0], 10])

First argument is variable name. 第一个参数是变量名。

x = tf.zeros(shape=[10,20])
x_shape = x.shape
variable_name ='y'
y = tf.get_variable(variable_name, shape=[x_shape[0], x_shape[1]])

To the best of my knowledge, you cannot create a Variable with a dynamic shape through the shape argument, instead you have to pass this dynamic shape through the initializer of the tf.Variable . 据我所知,您不能通过shape参数创建具有动态形状的变量,而是必须通过tf.Variable的初始化程序传递此动态形状。

This should work: 这应该工作:

zero_init = tf.fill([x_shape[0], 10], tf.constant(0))
# Initialize
y = tf.get_variable(
    "my_var", shape=None, validate_shape=False, initializer=zero_init
)

Note that the shape has to be defined before, or with the first execution of tf.Session.run(...) . 请注意,必须在第一次执行tf.Session.run(...)之前定义形状。 So if your x is a placeholder, you will need to feed a value for it. 因此,如果您的x是占位符,则需要为其提供值。

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

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