比较运算与排序。
pytorch的比较函数中有一些是逐元素比较,操作类似于逐元素操作,还有一些则类似于归并操作。
常见的比较函数如下:
实例:
import torch
import numpy as np
print("===init===")
a = torch.rand(2, 3)
b = torch.rand(2, 3)
print(a)
print(b)
#relation compare
print("===relationship compare===")
print(torch.eq(a, b))
#判断两个tensor的元素是否全部相同
print(torch.equal(a, 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("===sort===")
a = torch.tensor([[1, 4, 4, 3, 5],
[2, 3, 1, 3, 5]])
print(a.shape)
#对目标进行排序并返回索引
print(torch.sort(a, dim=1,
descending=False))
##topk
print("===topk===")
a = torch.tensor([[2, 4, 3, 1, 5],
[2, 3, 5, 1, 4]])
print(a.shape)
#返回最小的两个数及其索引
print(torch.topk(a, k=2, dim=1, largest=False))
print("===kthvalue===")
print(a)
#沿着指定维度返回第二个最小值,并返回索引
print(torch.kthvalue(a, k=2, dim=0))
print(torch.kthvalue(a, k=2, dim=1))
print("===inf/finite/nan===")
a = torch.rand(2, 3)
print(a)
print(a/0)
#是否有界
print(torch.isfinite(a))
#是否有界
print(torch.isfinite(a/0))
#是否无界
print(torch.isinf(a/0))
#是否有空值
print(torch.isnan(a))
a = torch.tensor([1, 2, np.nan]) #第三个是空值
#是否有空值
print(torch.isnan(a))
print("===topk===")
a = torch.rand(2, 3)
print(a)
#最小的前两个
print(torch.topk(a, k=2, dim=1, largest=False))
#最大的前两个
print(torch.topk(a, k=2, dim=1, largest=True))
运行结果:
===init===
tensor([[0.8286, 0.4584, 0.5419],
[0.2349, 0.3512, 0.9192]])
tensor([[0.3839, 0.2025, 0.1396],
[0.8186, 0.3728, 0.9254]])
===relationship compare===
tensor([[False, False, False],
[False, False, False]])
False
tensor([[ True, True, True],
[False, False, False]])
tensor([[ True, True, True],
[False, False, False]])
tensor([[False, False, False],
[ True, True, True]])
tensor([[False, False, False],
[ True, True, True]])
tensor([[True, True, True],
[True, True, True]])
===sort===
torch.Size([2, 5])
torch.return_types.sort(
values=tensor([[1, 3, 4, 4, 5],
[1, 2, 3, 3, 5]]),
indices=tensor([[0, 3, 1, 2, 4],
[2, 0, 1, 3, 4]]))
===topk===
torch.Size([2, 5])
torch.return_types.topk(
values=tensor([[1, 2],
[1, 2]]),
indices=tensor([[3, 0],
[3, 0]]))
===kthvalue===
tensor([[2, 4, 3, 1, 5],
[2, 3, 5, 1, 4]])
torch.return_types.kthvalue(
values=tensor([2, 4, 5, 1, 5]),
indices=tensor([1, 0, 1, 1, 0]))
torch.return_types.kthvalue(
values=tensor([2, 2]),
indices=tensor([0, 0]))
===inf/finite/nan===
tensor([[0.8512, 0.2876, 0.6526],
[0.5522, 0.6726, 0.6073]])
tensor([[inf, inf, inf],
[inf, inf, inf]])
tensor([[True, True, True],
[True, True, True]])
tensor([[False, False, False],
[False, False, False]])
tensor([[True, True, True],
[True, True, True]])
tensor([[False, False, False],
[False, False, False]])
tensor([False, False, True])
===topk===
tensor([[0.2693, 0.9663, 0.3926],
[0.8626, 0.1789, 0.7311]])
torch.return_types.topk(
values=tensor([[0.2693, 0.3926],
[0.1789, 0.7311]]),
indices=tensor([[0, 2],
[1, 2]]))
torch.return_types.topk(
values=tensor([[0.9663, 0.3926],
[0.8626, 0.7311]]),
indices=tensor([[1, 2],
[0, 2]]))