PyTorch学习笔记:torch.ge、torch.gt、torch.le、torch.lt、torch.ne、torch.eq
介绍
torch.ge(input, other, *, out=None) → Tensor
torch.gt(input, other, *, out=None) → Tensor
torch.le(input, other, *, out=None) → Tensor
torch.lt(input, other, *, out=None) → Tensor
torch.ne(input, other, *, out=None) → Tensor
torch.eq(input, other, *, out=None) → Tensor
功能:逐元素对比
- torch.ge:实现大于等于( ≥ \ge ≥)运算
- torch.gt:实现大于( > \gt >)运算
- torch.le:实现小于等于( ≤ \le ≤)运算
- torch.lt:实现小于( < \lt <)运算
- torch.ne:实现不等于( ≠ \ne =)运算
- torch.eq:实现等于( = = =)运算
前五个结合latex公式符号记忆
输入:
input
:待比较的数组other
:比较数值,可以是数组,也可以是一个数。tensor
或float
格式
输出:布尔张量,尺寸和input
相同,当input
和other
元素之间符合运算时,对应位置元素为True
,否则为Flase
。
注:
- 第二个参数可以是一个数字,也可以是一个张量数组,只要与第一个参数满足广播条件即可;
- 也可以通过
tensor
加后缀的形式实现,如a.ge
,a
相当于input
,即待比较的数组; - 如果输入的是数组,则必须是
tensor
类型
代码案例
import torch
a=torch.arange(5)
b=torch.tensor(3)
print(a)
print(b)
print(torch.ge(a,b))
print(torch.gt(a,b))
print(torch.le(a,b))
print(torch.lt(a,b))
print(torch.ne(a,b))
print(torch.eq(a,b))
输出
tensor([0, 1, 2, 3, 4])
tensor(3)
# 大于等于
tensor([False, False, False, True, True])
# 大于
tensor([False, False, False, False, True])
# 小于等于
tensor([ True, True, True, True, False])
# 小于
tensor([ True, True, True, False, False])
# 不等于
tensor([ True, True, True, False, True])
# 等于
tensor([False, False, False, True, False])
扩展
torch.eq
常用于分类任务中,判断预测值是否与真实值(标签值)相等,然后再配合.sum()
方法,将返回数组中True
的个数求和,从而计算正确预测的个数,最终得到正确率。
代码案例
import torch
import numpy as np
# 从0,1内随机选50个数,作为标签和预测值
labels=torch.tensor(np.random.choice(2,50))
pre=torch.tensor(np.random.choice(2,50))
print(labels)
print(pre)
right=torch.eq(pre,labels).sum().item()
# .sum()是求和操作,将数组中True数量求和
# .item()方法是为了取出数值
print('正确预测:',right,'个')
acc=right/len(labels)
print('准确率为:',acc,'%')
输出
# 标签
tensor([1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1,
0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
1, 1], dtype=torch.int32)
# 预测值
tensor([1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1,
1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,
0, 1], dtype=torch.int32)
正确预测: 31 个
准确率为: 0.62 %
官方文档
torch.ge():https://pytorch.org/docs/stable/generated/torch.ge.html?highlight=torch+ge#torch.ge
torch.gt():https://pytorch.org/docs/stable/generated/torch.gt.html?highlight=torch+gt#torch.gt
torch.le():https://pytorch.org/docs/stable/generated/torch.le.html?highlight=torch+le#torch.le
torch.lt():https://pytorch.org/docs/stable/generated/torch.lt.html?highlight=torch+lt#torch.lt
torch.ne():https://pytorch.org/docs/stable/generated/torch.ne.html?highlight=torch+ne#torch.ne
torch.eq():https://pytorch.org/docs/stable/generated/torch.eq.html?highlight=torch+eq#torch.eq
初步完稿于:2023年1月26日