如何在图形构造时获得张量的尺寸(在TensorFlow中)?

Tho*_*ran 36 python deep-learning tensorflow tensor

我正在尝试一个不按预期行事的Op.

graph = tf.Graph()
with graph.as_default():
  train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
  embeddings = tf.Variable(
    tf.random_uniform([50000, 64], -1.0, 1.0))
  embed = tf.nn.embedding_lookup(embeddings, train_dataset)
  embed = tf.reduce_sum(embed, reduction_indices=0)
Run Code Online (Sandbox Code Playgroud)

所以我需要知道Tensor的尺寸embed.我知道它可以在运行时完成,但这对于这么简单的操作来说太过分了.什么是更简单的方法呢?

Sha*_*ang 47

我看到大多数人都很困惑tf.shape(tensor),tensor.get_shape() 让我们说清楚:

  1. tf.shape

tf.shape用于动态形状.如果张量的形状是可变的,请使用它.例如:输入是一个具有可变宽度和高度的图像,我们希望将其大小调整为其大小的一半,然后我们可以编写如下内容:
new_height = tf.shape(image)[0] / 2

  1. tensor.get_shape

tensor.get_shape用于固定形状,这意味着张量的形状可以在图中推导出来.

结论: tf.shape几乎可以在任何地方使用,但t.get_shape只能从图形中推断出形状.


Tho*_*ran 44

Tensor.get_shape()这篇文章.

来自文档:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])
Run Code Online (Sandbox Code Playgroud)

  • 在这里,我愚蠢地称`tf.shape(c)`. (4认同)
  • 如果有人想知道:`tf.shape(c)`返回表示`c`形状的1-D整数张量.在这个答案给出的例子中,`tf.shape(c)`返回`Tensor("Shape:0",shape =(2,),dtype = int32)` (4认同)
  • @nobar,如果尺寸为“无”(即,如果未指定),则可能需要使用“ tf.shape(c)”。例如,如果`a = tf.placeholder(tf.int32,(None,2))`,并且您运行`tf.Session()。run(tf.constant(a.get_shape()。as_list()[0 ]),{a:[[1,2]]})`您会收到错误,但可以通过以下方式获取尺寸:tf.Session()。run(tf.shape(a)[0],{a :[[1,2]]})。 (2认同)

小智 9

一个访问值的函数:

def shape(tensor):
    s = tensor.get_shape()
    return tuple([s[i].value for i in range(0, len(s))])
Run Code Online (Sandbox Code Playgroud)

例:

batch_size, num_feats = shape(logits)
Run Code Online (Sandbox Code Playgroud)


Sun*_*Kim 5

只需在构建图形(ops)后打印出嵌入而不运行:

import tensorflow as tf

...

train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
    tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
print (embed)
Run Code Online (Sandbox Code Playgroud)

这将显示嵌入张量的形状:

Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)
Run Code Online (Sandbox Code Playgroud)

通常,在训练模型之前检查所有张量的形状是很好的.