pytorch-张量-张量的计算-基本运算

2基本运算

张量的基本运算方式,一种为逐元素之间的运算,如加减乘除四则运算,幂运算,平方根,对数,数据剪裁等,另一种为矩阵之间的运算,如矩阵相乘,矩阵的转置,矩阵的迹等

import torch

# 矩阵逐元素相乘
a = torch.arange(6.0).reshape(2,3)
b = torch.linspace(10, 20, steps=6).reshape(2, 3)
print("a", a)
print("b", b)
print(a * b)
# 逐元素相除
print(a / b)
# 逐元素相加
print(a + b)
# 逐元素相减
print(a - b)
# 逐元素整除
print(b // a)
# 计算张量的幂可以使用torch.pow()函数,或者使用**
print(torch.pow(a, 3))
print(a ** 3)
# 计算张量的指数可以使用torch.exp()函数
print(torch.exp(a))
# 计算张量的对数可以使用torch.log()函数
print(torch.log(a))
# 计算张量的平方根可以使用torch.sqrt()函数
print(torch.sqrt(a))
print(a ** 0.5)
# 计算张量的平方根倒数可以使用torch.rsqrt()函数
print(torch.rsqrt(a))
print(1 / (a**0.5))

# 对张量的数据裁剪,有根据最大值裁剪torch.clamp_max()函数
# 将大于x的数值都替换为x
print(a, "\n", torch.clamp_max(a, 4))
# 有根据最小值裁剪torch.clamp_min()函数
# 将小于x的数值都替换为x
print(torch.clamp_min(a, 3))
# 有根据范围裁剪torch.clamp()函数
# 按照范围剪裁张量,小于边界的数值都替换为下界值,大于上界的数值都替换为上界
print(torch.clamp(a, 2.5, 4))

# torch.t()计算矩阵的转置
c = torch.t(a)
print(c)
# torch.matmul()输出两个矩阵的乘积
print(a.matmul(c))
# 矩阵相乘只计算最后面的两个维度的乘法
a = torch.arange(12.0).reshape(2, 2, 3)
b = torch.arange(12.0).reshape(2, 3, 2)
print(a, b)
ab = torch.matmul(a, b)
print(ab)
print(ab[0].eq(torch.matmul(a[0], b[0])))
print(ab[0].eq(torch.matmul(a[1], b[0])))

# 计算矩阵的逆
c = torch.rand(3, 3)
d = torch.inverse(c)
print(torch.mm(c, d))

# 计算张量矩阵的迹,对角线元素的和
print(torch.trace(torch.arange(9.0).reshape(3, 3)))

猜你喜欢

转载自blog.csdn.net/weixin_45955630/article/details/111668217