【问题标题】:Variable size mismatch between x.shape and tf.shape(x)?x.shape 和 tf.shape(x) 之间的可变大小不匹配?
【发布时间】:2019-01-19 20:35:09
【问题描述】:

我正在尝试理解 tf 代码,为此我正在打印张量的形状。对于以下代码

print(x.shape)
print(tf.shape(x))

我得到输出

(?, 32, 32, 3)
Tensor("input/Shape:0", shape=(4,), dtype=int32)

这没有多大意义。根据我在网上找到的 tf.shape(x) 可用于动态获取批次的大小。但它给出了相当错误的输出 - 4。我不确定这个 (4,) 来自哪里以及如何为我的张量获得正确的值。

【问题讨论】:

标签: tensorflow


【解决方案1】:

其实这两个结果是一样的。 4(?,32,32,3) 的形状。

x.shape() 返回一个元组,没有sess.run() 也可以得到形状。您可以使用as_list() 将其转换为列表。

tf.shape(x)返回一个张量,你需要运行sess.run()才能得到实际数字。

一个例子:

import tensorflow as tf
import numpy as np

x = tf.placeholder(shape=(None,32,32,3),dtype=tf.float32)
print(x.shape)
print(tf.shape(x))

dim = tf.shape(x)
dim0 = tf.shape(x)[0]

with tf.Session()as sess:
    dim,dim0 = sess.run([dim,dim0],feed_dict={x:np.random.uniform(size=(100,32,32,3))})
    print(dim)
    print(dim0)

#print
(?, 32, 32, 3)
Tensor("Shape:0", shape=(4,), dtype=int32)
[100  32  32   3]
100

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2017-12-12
    • 2015-02-24
    • 2016-06-20
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    相关资源
    最近更新 更多