我在TensorFlow
中有以下简单代码:
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = tf.shape(a)
t1, t2 = size
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run(size, feed_dict = {a: np.random.randn(3, 4)})
t1
但它不起作用。我希望有张量的形状,a.shape
工作正常但重点是它得到None
的第二个维度。我搜索并知道它的价值我必须使用tf.shape(a)
,但现在问题是我搜索并发现python确实知道张量对象中的内容。我只想检索两个变量中的值。关键是我必须在更复杂的代码中使用此代码,这些大小是更大计算的边缘部分。反正有没有将这些数字作为整数而不分别为它们运行会话?
我不得不说我知道我的代码的以下变体有效:
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = a.shape.as_list()
print(type(size))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run(c, feed_dict = {a: np.random.randn(3, 4)})
print(res)
print(size)
但它将None
作为形状的第二个元素。因此,我必须使用tf.shape
。那些坚持我的问题是重复的人,我运行了建议here并得到以下结果仍然包括None
:
(3, ?)
这有帮助吗?这不是很一般,但由于我不知道你究竟想要实现什么,这可能已经足够了。
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = tf.shape(a)
t1 = size[0]
t2 = size[1]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run([t1, t2], feed_dict = {a: np.random.randn(3, 4)})
print(res)
替代方案:
a = tf.placeholder(dtype = tf.float64, shape = (3, None))
b = tf.Variable(dtype = tf.float64, initial_value = np.random.randn(5, 3))
c = tf.matmul(b, a)
size = tf.shape(a)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
t1, t2 = sess.run(size, feed_dict = {a: np.random.randn(3, 4)})
print(t1, t2)