具有可变大小的张量流常数 [英] tensorflow constant with variable size
问题描述
我有一个可变的批量大小,所以我所有的输入都是这样的
I have a variable batch size, so all of my inputs are of the form
tf.placeholder(tf.float32, shape=(None, ...)
接受可变批量大小.但是,您如何创建具有可变批量大小的常量值?问题出在这一行:
to accept the variable batch sizes. However, how might you create a constant value with variable batch size? The issue is with this line:
log_probs = tf.constant(0.0, dtype=tf.float32, shape=[None, 1])
它给了我一个错误:
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
我确信可以用可变批量大小初始化一个常量张量,我该怎么做?
I'm sure it is possible to initialize a constant tensor with variable batch size, how might I do so?
我还尝试了以下方法:
tf.constant(0.0, dtype=tf.float32, shape=[-1, 1])
我收到此错误:
ValueError: Too many elements provided. Needed at most -1, but received 1
推荐答案
A tf.constant()
在图形构建时具有固定的大小和值,因此它可能不适合您的应用程序.
A tf.constant()
has fixed size and value at graph construction time, so it probably isn't the right op for your application.
如果您尝试为每个元素创建一个具有动态大小和相同(常量)值的张量,您可以使用 tf.fill()
和 tf.shape()
以创建适当形状的张量.例如,要创建一个与 input
具有相同形状且值 0.5
的张量 t
:
If you are trying to create a tensor with a dynamic size and the same (constant) value for every element, you can use tf.fill()
and tf.shape()
to create an appropriately-shaped tensor. For example, to create a tensor t
that has the same shape as input
and the value 0.5
everywhere:
input = tf.placeholder(tf.float32, shape=(None, ...))
# `tf.shape(input)` takes the dynamic shape of `input`.
t = tf.fill(tf.shape(input), 0.5)
正如 Yaroslav 在他的评论中提到的,您也可以使用 (NumPy-style) 广播 来避免实现具有动态形状的张量.例如,如果 input
的形状为 (None, 32)
而 t
的形状为 (1, 32)
那么计算 tf.mul(input, t)
将在第一维上广播 t
以匹配 input
的形状.
As Yaroslav mentions in his comment, you may also be able to use (NumPy-style) broadcasting to avoid materializing a tensor with dynamic shape. For example, if input
has shape (None, 32)
and t
has shape (1, 32)
then computing tf.mul(input, t)
will broadcast t
on the first dimension to match the shape of input
.
这篇关于具有可变大小的张量流常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!