shape 和 get_shape 和 tf.shape

先说结论再看例子

1. 运行环境不同

  • shape 和 get_shape 返回元组,故无需 Session,可直接获取;
  • 而 tf.shape 返回 Tensor,需要 Session            【只有 Tensor 才需要 Session】

2. 适用对象不同

  • tf.shape 适用于 Tensor,还有 ndarray,list;
  • shape 适用于 Tensor,还有 ndarray;
  • get_shape 只适用于 Tensor;

代码如下

########## tf.shape ##########
### 用函数获取,返回 Tensor
# 针对所有 Tensor,包括 Variable,array、list 也可以
d5 = tf.shape(tf.random_normal((2, 3)))     ### Tensor
print(d5)       # Tensor("Shape:0", shape=(2,), dtype=int32)
d6 = tf.shape(tf.Variable([1. ,2.]))        ### Variable
n3 = tf.shape(np.array([[1, 2], [3, 4]]))   ### ndarray
n4 = tf.shape([1, 2])                       ### list
with tf.Session() as sess1:
    print(sess1.run(d5))        # [2 3]
    print(sess1.run(d6))        # [2]
    print(sess1.run(n3))        # [2 2]
    print(sess1.run(n4))        # [2]
    

########## shape ##########
### 直接获取,返回元组
# 针对所有 Tensor,包括 Variable,array 也可以
d1 = tf.random_uniform((3, 2)).shape        ### Tensor
print(d1)       # (3, 2)
d2 = tf.Variable([1. ,2.]).shape            ### Variable
print(d2)       # (2,)
n1 = np.array([[1, 2], [3, 4]]).shape       ### ndarray
print(n1)       # (2, 2)


########## get_shape ##########
### 直接获取,返回元组
# 针对所有 Tensor,包括 Variable,不包括 array
d3 = tf.random_uniform((3, 2)).get_shape()  ### Tensor
print(d3)       # (3, 2)
d4 = tf.Variable([1. ,2.]).get_shape()      ### Variable
print(d4)       # (2,)
# n2 = np.array([[1, 2], [3, 4]]).get_shape()     ### 报错 AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

参考资料:

https://blog.csdn.net/m0_37744293/article/details/78254691

猜你喜欢

转载自www.cnblogs.com/yanshw/p/12372314.html