范数 norm
import torch
a = torch.ones(8)
b = torch.ones(2, 4)
c = torch.ones(2, 3, 4)
print("a:\n{}".format(a))
print("b:\n{}".format(b))
print("c:\n{}".format(c))
print("a.norm(1): {}, b.norm(1): {}, c.norm(1): {}".format(
a.norm(1), b.norm(1), c.norm(1)
))
print("a.norm(2): {}\nb.norm(2): {}\nc.norm(2): {}".format(
a.norm(2), b.norm(2), c.norm(2)
))
print("b.norm(1, dim=1): ", b.norm(1, dim=1))
print("b.norm(2, dim=1): ", b.norm(2, dim=1))
print("c.norm(1, dim=0): \n", c.norm(1, dim=0))
print("c.norm(2, dim=0): \n", c.norm(2, dim=1))
- dim指定哪个维度就会在哪个维度上求范数
- 如:[2, 3, 4]
- dim = 0 → [3, 4]
- dim = 1 → [2, 4]
- dim = 2 → [2, 3]
平均、求和、最小、最大、累乘
import torch
a = torch.arange(8).view(2, 4).float() + 1
print("a:\n{}\n".format(a))
print("a.min(): ", a.min())
print("a.max(): ", a.max())
print("a.mean(): ", a.mean())
print("a.prod(): ", a.prod())
print("a.sum(): ", a.sum())
print("a.argmax(): ", a.argmax())
print("a.argmin(): ", a.argmin())
argmin、argmax
import torch
a = torch.arange(8).view(2, 4).float() + 1
print("a:\n{}\n".format(a))
print("a.argmax(): ",a.argmax())
print("a.argmax(dim=0): ", a.argmax(dim=0))
print("a.argmin(dim=1): ", a.argmin(dim=1))
dim和keepdim
import torch
a = torch.randn(4, 10)
print("a.max(dim=1):\n{}\n".format(a.max(dim=1)))
print("a.argmax(dim=1): ", a.argmax(dim=1), "\n")
print("a.max(dim=1, keepdim=True):\n{}\n".format(
a.max(dim=1, keepdim=True))
)
print("a.argmax(dim=0, keepdim=True):\n{}\n".format(
a.argmax(dim=0, keepdim=True))
)
top-k 和 k-th
import torch
a = torch.randn(4, 10)
print("a.topk(3, dim=1):\n{}\n".format(a.topk(3, dim=1)))
print("a.topk(3, dim=1, largest=False):\n{}\n".format(
a.topk(3, dim=1, largest=False))
)
print("a.kthvalue(8, dim=1):\n{}\n".format(
a.kthvalue(8, dim=1)
))
print("a.kthvalue(3, dim=0):\n{}\n".format(
a.kthvalue(3, dim=0)
))
比较运算
import torch
a = torch.arange(-4, 4).view(2, 4)
print("a:\n{}\n".format(a))
print("a>0:\n{}\n".format(a>0))
print("torch.equal(a>0, torch.gt(a, 0)):",
torch.equal(a>0, torch.gt(a, 0)))
print("a==0:\n{}\n".format(a==0))
print("torch.equal(a==0, torch.eq(a, 0)):",
torch.equal(a==0, torch.eq(a, 0)))
print("a>=0:\n{}\n".format(a>=0))
print("torch.equal(a>=0, torch.ge(a, 0)):",
torch.equal(a>=0, torch.ge(a, 0)))
- 小于和小于等于可直接使用符号
< <= 或在 ge gt 时将矩阵反转
|