标量:
-
简单操作
- c=a+b
- c=a.b
- c=a
-
长度
向量
-
简单操作
- c=a+b where
- c=b where
- c= a where
-
长度
- 点乘 点积(dot product) 或<a,b>,相同位置的按元素乘积的和
import torch x = torch.arange(4, dtype=torch.float32) y = torch.ones(4, dtype=torch.float32) z = torch.dot(x, y) print(x, y, z)
输出: 两个向量的点积为 元素乘法然后求和。
tensor([0., 1., 2., 3.]) tensor([1., 1., 1., 1.]) tensor(6.)
- 正交
矩阵
-
简单操作
- C=A+B where
- C=B where
- C= A where
-
乘法
- 矩阵向量积(矩阵乘以向量)使用
mv
函数 其中,A的列维必须与b的维数长度一致。import torch x = torch.arange(4, dtype=torch.float32) A = torch.arange(20, dtype=torch.float32).reshape(5, 4) print(A.shape, x.shape, torch.mv(A, x))
输出:
torch.Size([5, 4]) torch.Size([4]) tensor([ 14., 38., 62., 86., 110.])
- 矩阵乘以矩阵
- 范数 取决于如何衡量b和c的长度.。常见范数 :
-
矩阵范数:最小的满足公式的值
-
Frobenius范数
线性代数的实现:
标量由只有一个元素的张量表示
创建m*n的矩阵
# 通过指定m,n创建形状为m*n的矩阵
A = torch.arange(20).reshape(5, 4)
print(A)
- 输出
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
矩阵的转置:
# 矩阵的转置
print(A.T)
输出
tensor([[ 0, 4, 8, 12, 16],
[ 1, 5, 9, 13, 17],
[ 2, 6, 10, 14, 18],
[ 3, 7, 11, 15, 19]])
对称矩阵(symmetric matrix)=
# 对称矩阵
B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]])
print(B)
print("B==B.T", B == B.T)
输出:
tensor([[1, 2, 3],
[2, 0, 4],
[3, 4, 5]])
B==B.T
tensor([[True, True, True],
[True, True, True],
[True, True, True]])
哈达玛积(Hadamard product)(数学符号)
# 哈达玛积
B = A.clone() #通过分配新内存,将A拷贝给B
print("A*B=", A * B)
a = 2
X = torch.arange(24).reshape(2, 3, 4)
print("a+X", a + X)
print("(a*X)形状", (a + X).shape)
输出
A*B=
tensor([[ 0, 1, 4, 9],
[ 16, 25, 36, 49],
[ 64, 81, 100, 121],
[144, 169, 196, 225],
[256, 289, 324, 361]])
a+X
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]]])
(a*X)形状 torch.Size([2, 3, 4])
矩阵向量积
# 通过指定m,n创建形状为m*n的矩阵
A = torch.arange(20).reshape(5, 4)
print(A)
x = torch.arange(4)
print(x)
# 矩阵向量积
print(A.shape, x.shape)
print(torch.mv(A, x))
输出 mv():
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
tensor([0, 1, 2, 3])
torch.Size([5, 4]) torch.Size([4])
tensor([ 14, 38, 62, 86, 110])
矩阵间的乘法AB
# 通过指定m,n创建形状为m*n的矩阵
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
B = torch.ones(4, 3)
# 矩阵间的乘法
print(B, B.shape)
print(torch.mm(A, B))
输出
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]) torch.Size([4, 3])
tensor([[ 6., 6., 6.],
[22., 22., 22.],
[38., 38., 38.],
[54., 54., 54.],
[70., 70., 70.]])
矩阵的范数
范数是向量元素平方和的平方根
# L2范数 向量元素平方和的平方根
u = torch.tensor([3.0, -4.0])
print(torch.norm(u))
输出:
tensor(5.)
矩阵的范数
范数是向量元素的绝对值之和
# L1范数 向量元素的绝对值之和
print(torch.abs(u).sum())
输出
tensor(7.)
矩阵的佛罗贝尼乌斯范数(Frobenius norm)
矩阵元素的平方和的平方根
# 佛罗贝尼乌斯范数
print(torch.norm(torch.ones((4, 9))))
输出
tensor(6.)