Python 如何在图构建时获取张量(在 TensorFlow 中)的维度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36966316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:36:53  来源:igfitidea点击:

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

pythontensorflowdeep-learningtensor

提问by Thoran

I am trying an Op that is not behaving as expected.

我正在尝试一个行为不符合预期的操作。

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)

So I need to know the dimensions of the Tensor embed. I know that it can be done at the run time but it's too much work for such a simple operation. What's the easier way to do it?

所以我需要知道 Tensor 的维度embed。我知道它可以在运行时完成,但是对于这样一个简单的操作来说工作量太大了。什么是更简单的方法?

回答by Shang

I see most people confused about tf.shape(tensor)and tensor.get_shape()Let's make it clear:

我看到大多数人对此感到困惑tf.shape(tensor)tensor.get_shape()让我们说清楚:

  1. tf.shape
  1. tf.shape

tf.shapeis used for dynamic shape. If your tensor's shape is changable, use it. An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:
new_height = tf.shape(image)[0] / 2

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

  1. tensor.get_shape
  1. tensor.get_shape

tensor.get_shapeis used for fixed shapes, which means the tensor's shape can be deducedin the graph.

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

Conclusion: tf.shapecan be used almost anywhere, but t.get_shapeonly for shapes can be deduced from graph.

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

回答by Thoran

Tensor.get_shape()from this post.

Tensor.get_shape()这个帖子

From documentation:

从文档

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

回答by Colin Swaney

A function to accessthe values:

访问值的函数:

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

Example:

例子:

batch_size, num_feats = shape(logits)

回答by Sung Kim

Just print out the embed after construction graph (ops) without running:

只需在不运行的情况下打印出构建图 (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)

This will show the shape of the embed tensor:

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

Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)

Usually, it's good to check shapes of all tensors before training your models.

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

回答by kmario23

Let's make it simple as hell. If you want a single number for the number of dimensions like 2, 3, 4, etc.,then just use tf.rank(). But, if you want the exact shape of the tensor then use tensor.get_shape()

让我们让它变得简单。如果你想要一个单一的维度数,2, 3, 4, etc.,那么只需使用tf.rank(). 但是,如果您想要张量的确切形状,请使用tensor.get_shape()

with tf.Session() as sess:
   arr = tf.random_normal(shape=(10, 32, 32, 128))
   a = tf.random_gamma(shape=(3, 3, 1), alpha=0.1)
   print(sess.run([tf.rank(arr), tf.rank(a)]))
   print(arr.get_shape(), ", ", a.get_shape())     


# for tf.rank()    
[4, 3]

# for tf.get_shape()
Output: (10, 32, 32, 128) , (3, 3, 1)

回答by cliffberg

The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See

tf.shape 方法是一个 TensorFlow 静态方法。然而,Tensor 类也有 get_shape 方法。看

https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape

https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape