TensorFlow - 根据另一个变量的形状动态定义变量的形状 [英] TensorFlow - Defining the shape of a variable dynamically, depending on the shape of another variable

查看:27
本文介绍了TensorFlow - 根据另一个变量的形状动态定义变量的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个张量 x,其维度未在图初始化时定义.

Say I have a certain the Tensor x whose dimensions are not defined upon graph initialization.

我可以使用:

x_shape = tf.shape(input=x)

现在,如果我想根据 x_shape 中定义的值创建一个变量,使用:

Now if I want to create a variable based on the values defined in x_shape using:

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

我收到一个错误,因为传递给参数形状的值必须是 int 而不是 Tensor.如何在不使用占位符的情况下创建这样一个动态形状的变量?

I get an error, since the values passed to the argument shape must be int and not Tensor. How can I create such a dynamically shaped variable without using placeholders?

推荐答案

我的时间不多了,所以这又快又脏,但也许它可以帮助您找到解决方案...它基于此 (动态大小为tf.zeros) 但将这个想法扩展到 tf.Variables.由于您的变量无论如何都需要初始化 - 我选择 0s...

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. Since your variable needs to be initialized anyway - I choose 0s...

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)

这篇关于TensorFlow - 根据另一个变量的形状动态定义变量的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆