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

转自:https://blog.csdn.net/m0_37393514/article/details/82226754

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

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

如果你在上面的代码上添加上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)) #报错
 

结果:

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

 

--------------------- 本文来自 爱抠脚的coder 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/m0_37393514/article/details/82226754?utm_source=copy

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值