Python Tensorflow动态/静态形状:无法将int转换为Tensor操作
在这段代码中,我得到了输入张量的动态和静态形状。问题是,虽然我的Numpy生成的数组应该被视为张量,但它不是!任何帮助都将不胜感激Python Tensorflow动态/静态形状:无法将int转换为Tensor操作,python,tensorflow,Python,Tensorflow,在这段代码中,我得到了输入张量的动态和静态形状。问题是,虽然我的Numpy生成的数组应该被视为张量,但它不是!任何帮助都将不胜感激 import tensorflow as tf import numpy as np def get_shape(tensor): """ Return the static shape of a tensor only when available """ static_shape = tensor.shape.as_
import tensorflow as tf
import numpy as np
def get_shape(tensor):
"""
Return the static shape of a tensor only when available
"""
static_shape = tensor.shape.as_list()
dynamic_shape = tf.unstack(tf.shape(tensor))
dim = [s[1] if s[0] is None else s[0] for s in zip(static_shape, dynamic_shape)]
return dim
a = tf.placeholder(dtype=tf.float32, shape=[None, 128])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
x = np.random.normal(loc=0.5, scale=0.3, size=[150, 128])
shapes = get_shape(a)
print(sess.run(shapes, feed_dict={a: x}))
换线就行了
dim = [s[1] if s[0] is None else s[0] for s in zip(static_shape, dynamic_shape)]
到
问题是,在本例中,您
s[0]
指的是int
类型,因为它是一个静态形状。但这里我们需要一个有效的tensorflow操作。使用tf.constant(s[0])
而不是s[0]
解决了这个问题。我认为您找不到占位符的静态形状,因为它没有定义。这就是为什么你只能找到动态形状(tf.shape(tensor)为什么你在sess.run(a,feed\u dict={a:x})
执行时传递形状?形状的类型是[,128]
@MohanRadhakrishnan,因为它包含一个Tensorflow操作,所以我想计算形状。@guillaumegg10 Nevermind。get\u形状中的条件处理该操作。
dim = [s[1] if s[0] is None else tf.constant(s[0]) for s in zip(static_shape, dynamic_shape)]