在深度学习中,经常需要对张量做四则、线性变换和激活等。
1. 单个张量的函数运算
t = torch.rand(2, 2) # 产生一个3x3的张量
print(t)
print(t.sqrt()) # 张量的平方根,张量内部方法
print(torch.sqrt(t)) # 张量的平方根,函数形式
print(t.sqrt_()) # 平方根原地操作
print(torch.sum(t)) # 所有元素求和
print(torch.sum(t, 0)) # 第0维元素求和
print(torch.sum(t, [0, 1])) # 对0,1维元素求和
print(torch.mean(t, [0, 1])) # 对0,1维元素求平均
2. 多个张量的函数运算
pytorch中可以使用加减乘除的运算符进行张量间的运算,也可以使用add、sub、mul和div方法来进行运算。
t1 = torch.rand(2, 2)
t2 = torch.rand(2, 2)
# 元素相加
print(t1.add(t2))
print(t1+t2)
print('=' * 50)
# 元素相减
print(t1.sub(t2))
print(t1-t2)
print('=' * 50)
# 元素相乘
print(t1.mul(t2))
print(t1*t2)
print('=' * 50)
# 元素相除
print(t1.div(t2))
print(t1/t2)
print('=' * 50)
3. 张量的极值和排序
t = torch.randn(3, 3)
print(t)
print(