Pytorch 叉乘
阿新 • • 發佈:2018-12-13
使用Pytorch時遇到想要將矩陣進行自身叉乘的情況,例如輸入資料size為[BS, 3]
,那麼需要先將輸入資料轉換為[BS, 3, 1]
和[BS, 1, 3]
,這時叉乘結果size為[BS, 3, 3]
下面為二維矩陣的pytorch程式碼及結果:
import numpy as np
import torch
a = np.array([1, 2, 3])
a = torch.from_numpy(a)
a = a.unsqueeze(0)
a
1 2 3 [torch.IntTensor of size 1x3]
b = np.array([4, 5, 6])
b = torch.from_numpy( b)
b = b.unsqueeze(1)
b
4 5 6 [torch.IntTensor of size 3x1]
c = b*a
c
4 8 12 5 10 15 6 12 18 [torch.IntTensor of size 3x3]
下面為三維資料的叉乘:
m = np.array([[1, 2, 3], [1, 2, 3]])
m = torch.from_numpy(m)
m = m.unsqueeze(2)
m
(0 ,.,.) = 1 2 3 (1 ,.,.) = 1 2 3 [torch.IntTensor of size 2x3x1]
n = np.array( [[4, 5, 6], [4, 5, 6]])
n = torch.from_numpy(n)
n = n.unsqueeze(1)
n
(0 ,.,.) = 4 5 6 (1 ,.,.) = 4 5 6 [torch.IntTensor of size 2x1x3]
res = m*n
res
(0 ,.,.) = 4 5 6 8 10 12 12 15 18 (1 ,.,.) = 4 5 6 8 10 12 12 15 18 [torch.IntTensor of size 2x3x3]