StudyAi
首页
课程
专栏
小组
问答
招聘
登录
注册
江户川柯北
真相只有一个!(#^.^#)
12676
访客
66
文章
219408
字数
3
粉丝
私信
关注
访问
Friendly Introduction
(广告:~~ 小兰的AI专栏 ~~)
Pytorch如何判断一个Tensor非空
8个月前
1438字
878阅读
0评论
# 三种容器的真假判断 空张量 和 零张量 的真假 torch.Tensor() 空数组 和 零数组 的真假 np.array() 空列表 和 零列表 的真假 [] 直接判断元素数量, 是最最佳方案。 # Empty-Tensor & Zero-Tensor ``` x=t.Tensor([]) x >>> Variable containing:[torch.FloatTensor with no dimension] a=t.Tensor([0]) a >>> 0 [torch.FloatTensor of size 1] ``` # 利用内置bool, 会模棱两可 ``` x.__bool__() >>> False a.__bool__() Traceback (most recent call last): File "
", line 1, in
RuntimeError: bool value of non-empty torch.FloatTensor objects is ambiguous bool(x) >>> False bool(a) Traceback (most recent call last): File "
", line 1, in
RuntimeError: bool value of non-empty torch.FloatTensor objects is ambiguous ``` # 利用shape,有溢出风险 ``` x.shape torch.Size([]) x.shape[0] > 0 Traceback (most recent call last): File "
", line 1, in
IndexError: tuple index out of range a.shape[0]>0 >>> True if a.shape: print('指向不明确,表意有含糊') ``` # 转化为numpy数组操作 ``` ## 0/empty的numpy数组都为False, 与Tensor不相同。 a.numpy() >>> array([ 0.], dtype=float32) bool(a.numpy()) >>> False x.data.numpy() >>> array([], dtype=float32) bool(x.data.numpy()) >>> False ``` # 转为List列表操作 ``` # 与 np.array 结论一样, 0或empy都为False list(x.data) >>> [] >>> bool(list(x.data)) >>> False list(a) >>> [0.0] bool(list(x.data)) >>> False ``` # 直接判断元素数量, 最佳方案 ``` bool(a.numel()) True bool(x.numel()) False x.numel() 0 ```
收藏 (0)
打赏
点赞 (0)
热门评论
到顶端
发布^_^
powerd by studyai.com 2017