x.get_shape().as_list()和tf.shape()

时间:2022-06-19
本文章向大家介绍x.get_shape().as_list()和tf.shape(),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

tf.shape()

先说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]])
 
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]

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(c_tensor.get_shape())
print(c_tensor.get_shape().as_list())
 
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)))

结果:可见只能用于tensor来返回shape,但是是一个元组,需要通过as_list()的操作转换成list.

(2, 3)
[2 3]
[2 3]
[2 3]
[2 3]

不是元组进行操作的话,会报错!

如果你在上面的代码上添加上a_array.get_shape()会报如下的错误:

print(a_array.get_shape())
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

可见,只有tensor才有这样的特权呀!

下面强调一些注意点:

第一点:tensor.get_shape()返回的是元组,不能放到sess.run()里面,这个里面只能放operation和tensor;

第二点: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)
    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()
    print("c_tensor_shape:",c_tensor_shape)
    #print(sess.run(c_tensor_shape)) #报错

结果:

a_array_shape: Tensor("Shape_6:0", shape=(2,), dtype=int32)
a_array_shape: [2 3]
c_tensor_shape: [2, 3]

如果你把注释掉的那个话再放出来,报错如下:很显然啊,不是tensor或者是operation。

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.)