1、tf.shape()获取张量的大小,比较直接
import tensorflow as tf
import numpy as np
a_array = np.array([[1, 2, 3], [4, 6, 5]])
b_list = [[11, 22, 33], [44, 55, 66]]
c_tensor = tf.constant([[111, 222, 333], [444, 555, 666]], name = 'c_tensor')
with tf.Session() as sess:
print(sess.run(tf.shape(a_array)))
print(sess.run(tf.shape(b_list)))
print(sess.run(tf.shape(c_tensor)))
输出:
[2 3]
[2 3]
[2 3]
2、get_shape().as_list()
x.get_shape()只有tensor才可以使用这种方法,返回的是TensorShape对象,再调用as_list()才能转换成列表
import tensorflow as tf
import numpy as np
a_array = np.array([[1, 2, 3], [4, 6, 5]])
b_list = [[11, 22, 33], [44, 55, 66]]
c_tensor = tf.constant([[111, 222, 333], [444, 555, 666]], name = 'c_tensor')
print(c_tensor.get_shape())
print(c_tensor.get_shape().as_list())
输出:
(2, 3)
[2, 3]
只能用tensor来返回shape,但是是TensorShape对象,需要通过as_list()的操作转换成list
需要注意的是:
第一点:tensor.get_shape()返回的是元组,不能放到sess.run()里面,这个里面只能放operation和tensor
第二点:tf.shape()返回的是一个tensor,必须通过sess.run()运行