2.3 线性代数
2.3.1标量
只有一个元素的张量表示标量
python
import torch
x=torch.tensor(3)
print(x)
python
tensor(3)
2.3.2向量
一维张量表示向量,可以被视为标量值组成的列表
python
import torch
x=torch.arange(3)
print(x)
python
tensor([0, 1, 2])
通过索引来访问元素
python
print(x[2])
python
tensor(2)
向量的长度=维度
可以用len()或.shape属性访问
python
print(len(x))
print(x.shape)
python
3
torch.Size([3])
2.3.3矩阵
具有两个轴的张量
python
import torch
x=torch.arange(20).reshape(5,4)
print(x)
python
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
矩阵的转置
python
print(x.T)
python
tensor([[ 0, 4, 8, 12, 16],
[ 1, 5, 9, 13, 17],
[ 2, 6, 10, 14, 18],
[ 3, 7, 11, 15, 19]])
对称矩阵的转置等于其本身
2.3.4张量
具有任意数量轴的n维数组
python
import torch
x=torch.arange(24).reshape(2,3,4)
print(x)
python
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
2.3.5张量算法的基本性质
任何按元素的一元运算不会改变其形状
python
import torch
x=torch.arange(24).reshape(2,3,4)
y=x.clone()
z=2
print(x+y)#加法
print(x*y)#乘法Hadamard积
print(x+2)#标量的运算
python
tensor([[[ 0, 2, 4, 6],
[ 8, 10, 12, 14],
[16, 18, 20, 22]],
[[24, 26, 28, 30],
[32, 34, 36, 38],
[40, 42, 44, 46]]])
tensor([[[ 0, 1, 4, 9],
[ 16, 25, 36, 49],
[ 64, 81, 100, 121]],
[[144, 169, 196, 225],
[256, 289, 324, 361],
[400, 441, 484, 529]]])
tensor([[[ 2, 3, 4, 5],
[ 6, 7, 8, 9],
[10, 11, 12, 13]],
[[14, 15, 16, 17],
[18, 19, 20, 21],
[22, 23, 24, 25]]])
2.3.6降维求和
可以通过设置axis来进行行求和或列求和
python
import torch
x=torch.arange(12).reshape(3,4)
print(x)
print(x.sum())
print(x.sum(axis=0))
print(x.sum(axis=1))
python
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
tensor(66)
tensor([12, 15, 18, 21])
tensor([ 6, 22, 38])
也可以设置keepdims保持轴数不变
python
import torch
x=torch.arange(12).reshape(3,4)
print(x.sum(axis=0))
print(x.sum(axis=0,keepdim=True))
python
tensor([12, 15, 18, 21])
tensor([[12, 15, 18, 21]])
同样,计算平均值也可以指定轴降维
python
import torch
x=torch.arange(12,dtype=torch.float32).reshape(3,4)
print(x.mean())
python
tensor(5.5000)
2.3.7向量的点积
即相同位置元素乘积之和,只能用于向量(一维张量)
python
import torch
x=torch.arange(4,dtype=torch.float32)
y=torch.ones(4,dtype=torch.float32)
print(torch.dot(x,y))
python
tensor(6.)
2.3.8矩阵乘法
n行m列矩阵与m行l列矩阵相乘会得到n行l列矩阵
python
import torch
x=torch.arange(20,dtype=torch.float32).reshape(5,4)
y=torch.ones(4,3)
print(torch.mm(x,y))
python
tensor([[ 6., 6., 6.],
[22., 22., 22.],
[38., 38., 38.],
[54., 54., 54.],
[70., 70., 70.]])
2.3.9范数
向量的范数表示一个向量的大小
L2范数
向量元素平方和的平方根
python
import torch
x=torch.tensor([3.0,-4.0])
print(torch.norm(x))
python
tensor(5.)
L1范数
表示为向量元素绝对值之和
python
import torch
x=torch.tensor([3.0,-4.0])
print(torch.abs(x).sum())
python
tensor(7.)
Frobenius范数
矩阵元素平方和的平方根,满足向量范数的所有性质,像是矩阵型向量的L2范数
python
import torch
x=torch.ones(4,9)
print(torch.norm(x))
python
tensor(6.)