tf.shape()用法:获取张量的大小
打印张量,结果是该张量的类型和形状。
import tensorflow as tf
import numpy as np
a_array = np.array([[1, 2, 3], [4, 5, 6]])
b_list = [[1, 2, 3], [3, 4, 5]]
c_tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
print(a_array)
print(b_list)
print(c_tensor)
# [[1 2 3]
# [4 5 6]]
# [[1, 2, 3], [3, 4, 5]]
# Tensor("Const:0", shape=(2, 3), dtype=int32)
print(tf.shape(a_array))
print(tf.shape(b_list))
print(tf.shape(c_tensor))
# Tensor("Shape:0", shape=(2,), dtype=int32)
# Tensor("Shape_1:0", shape=(2,), dtype=int32)
# Tensor("Shape_2:0", shape=(2,), dtype=int32)
with tf.Session() as sess:
print(sess.run(c_tensor))
# [[1 2 3]
# [4 5 6]]
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]
x.get_shape().as_list()用法:
x.get_shape(),只有tensor才可以使用这种方法,返回的是一个元组。
import tensorflow as tf
import numpy as np
a_array = np.array([[1, 2, 3], [4, 5, 6]])
b_list = [[1, 2, 3], [3, 4, 5]]
c_tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
print(tf.shape(a_array))
print(tf.shape(a_array).get_shape())
print(tf.shape(a_array).get_shape().as_list())
# Tensor("Shape:0", shape=(2,), dtype=int32)
# (2,)
# [2]
print(tf.shape(b_list))
print(tf.shape(b_list).get_shape())
print(tf.shape(b_list).get_shape().as_list())
# Tensor("Shape_3:0", shape=(2,), dtype=int32)
# (2,)
# [2]
print(c_tensor)
print(c_tensor.get_shape())
print(c_tensor.get_shape().as_list())
# Tensor("Const:0", shape=(2, 3), dtype=int32)
# (2, 3)
# [2, 3]
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]
结论:可见只能用于tensor来返回shape,但是是一个元组,需要通过as_list()的操作转换成list。
如果不是元组进行操作的话,会报错!
如果你在上面的代码上添加上a_array.get_shape()会报如下的错误:
print(a_array.get_shape())
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
注意:
第一点:tensor.get_shape()返回的是元组,不能放到sess.run()里面,这个sess.run()里面只能放operation和tensor;否则报错:
# TypeError: Fetch argument TensorShape([Dimension(2)]) has invalid type <class
# 'tensorflow.python.framework.tensor_shape.TensorShapeV1'>, must be a string or Tensor. (Can not convert a
# TensorShapeV1 into a Tensor or Operation.)
第二点:tf.shape()返回的是一个tensor。要想知道是多少,必须通过sess.run()打印出来。
import tensorflow as tf
import numpy as np
a_array = np.array([[1, 2, 3], [4, 5, 6]])
b_list = [[1, 2, 3], [3, 4, 5]]
c_tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
with tf.Session() as sess:
a_array_shape = tf.shape(a_array) # tensor
print("a_array_shape:", a_array_shape)
print("a_array_shape:", sess.run(a_array_shape))
c_tensor_shape = c_tensor.get_shape().as_list() # list
print("c_tensor_shape:", c_tensor_shape)
# a_array_shape: Tensor("Shape:0", shape=(2,), dtype=int32)
# a_array_shape: [2 3]
# c_tensor_shape: [2, 3]
print(sess.run(c_tensor_shape)) # 报错
# TypeError: Fetch argument 2 has invalid type <class 'int'>, must be a string or Tensor.(Can not convert a int
# into a Tensor or Operation.)
sess.run()中不是tensor或者是operation,会报错。