1.矩陣的轉置
方法:
t()
a=torch.randint(1,10,[2,3])
print(a,'\n')
print(a.t())
輸出結果
tensor([[2, 8, 2],
[9, 2, 4]])
tensor([[2, 9],
[8, 2],
[2, 4]])
transpose(維度下標1,維度下標2)
:任意兩個維度之間的轉換
a=torch.randint(1,10,[2,3,4,5])
print(a.shape)
a1=a.transpose(1,3)
print(a1.shape)
輸出結果
torch.Size([2, 3, 4, 5])
torch.Size([2, 5, 4, 3])
permute(維度的下標)
:所有維度之間的任意轉換
a=torch.randint(1,10,[2,3,4,5])
print(a.shape)
a1=a.permute(2,3,1,0)
print(a1.shape)
輸出結果
torch.Size([2, 3, 4, 5])
torch.Size([4, 5, 3, 2])
2.矩陣的四則運算
矩陣的加法:2行3列矩陣+2行3列矩陣:
a=torch.randint(1,10,[2,3])
b=torch.randint(1,10,[2,3])
print(a,'\n')
print(b,'\n')
print(a+b,'\n')
輸出結果
tensor([[4, 1, 8],
[6, 7, 4]])
tensor([[9, 7, 1],
[5, 1, 6]])
tensor([[13, 8, 9],
[11, 8, 10]])
2行3列矩陣+1行3列矩陣:會先將第二個矩陣復制一行,然后再相加
a=torch.randint(1,10,[2,3])
b=torch.randint(1,10,[1,3])
print(a,'\n')
print(b,'\n')
print(a+b,'\n')
輸出結果
tensor([[9, 2, 3],
[2, 7, 9]])
tensor([[7, 8, 2]])
tensor([[16, 10, 5],
[ 9, 15, 11]])
2行1列矩陣+1行3列矩陣:會先將第一個矩陣復制成三列,然后將第二個矩陣復制成兩行,再進行相加
a=torch.randint(1,10,[2,1])
b=torch.randint(1,10,[1,3])
print(a,'\n')
print(b,'\n')
print(a+b,'\n')
輸出結果
tensor([[3],
[2]])
tensor([[4, 2, 5]])
tensor([[7, 5, 8],
[6, 4, 7]])
cat(所要相加的矩陣,維度)
:兩個矩陣的某個維度相加
除了相加的維度之外,其余的維度的值必須相同
a=torch.randint(1,10,[2,3])
b=torch.randint(1,10,[1,3])
print(a.shape)
print(b.shape)
print(torch.cat([a,b],dim=0).shape,'\n')
輸出結果
torch.Size([2, 3])
torch.Size([1, 3])
torch.Size([3, 3])
stack()
:會在所相加維度之前加一個2維的維度,用於兩個tensor相加,但不想合並。
a=torch.randint(1,10,[1,3])
b=torch.randint(1,10,[1,3])
print(a.shape)
print(b.shape)
print(torch.stack([a,b],dim=0).shape)
print(torch.stack([a,b],dim=1).shape)
輸出結果
torch.Size([1, 3])
torch.Size([1, 3])
torch.Size([2, 1, 3])
torch.Size([1, 2, 3])
矩陣的外積
a=torch.tensor([[1,2],[3,4]])
b=torch.tensor([[1,2],[3,4]])
print(a)
print(b)
print(a*b)
輸出結果
tensor([[1, 2],
[3, 4]])
tensor([[1, 2],
[3, 4]])
tensor([[ 1, 4],
[ 9, 16]])
matmul(矩陣a,矩陣b)
: 計算矩陣的內積(推薦)
@
:計算矩陣的內積
a=torch.tensor([[1,2],[3,4]])
b=torch.tensor([[1,2],[3,4]])
print(a)
print(b)
print(torch.matmul(a,b)) #推薦使用此方法
print(a@b) # 不推薦
輸出結果
tensor([[1, 2],
[3, 4]])
tensor([[1, 2],
[3, 4]])
tensor([[ 7, 10],
[15, 22]])
tensor([[ 7, 10],
[15, 22]])