スポンサーリンク

1次元配列の内積を計算するtorch.dot【PyTorch】

Python

PyTorchのTensor配列の内積を計算するには、torch.dotを使用する。

torch.dotの使い方

torch.dotを使うことで、内積を計算することができる。

import torch

a = torch.tensor([1, 2, 3])
print(a.shape)
# torch.Size([3])
b = torch.tensor([3, 2, 1])
print(b.shape)
# torch.Size([3])

ab = torch.dot(a, b)
print(ab)
# tensor(10)

NumPyのnumpy.dotと違い、torch.dotは1次元配列かつ要素数が同じ場合しか計算できない。torch.dotで計算できない例について、以下に記す。

スカラーと1次元配列の場合

a = torch.tensor(1)
print(a.shape)
# torch.Size([])
b = torch.tensor([3, 2, 1])
print(b.shape)
# torch.Size([3])

ab = torch.dot(a, b)
# RuntimeError: 1D tensors expected, but got 0D and 1D tensors

配列の要素数が異なる場合

a = torch.tensor([1, 2])
print(a.shape)
# torch.Size([2])
b = torch.tensor([3, 2, 1])
print(b.shape)
# torch.Size([3])

ab = torch.dot(a, b)
# RuntimeError: inconsistent tensor size, expected tensor [2] and src [3] to have the same number of elements, but got 2 and 3 elements respectively

2次元配列の場合

a = torch.tensor([[1, 2, 3],[1, 2, 3]])
print(a.shape)
# torch.Size([2, 3])

b = torch.tensor([[3, 2, 1],[3, 2, 1]])
print(b.shape)
# torch.Size([2, 3])

ab = torch.dot(a, b)
# RuntimeError: 1D tensors expected, but got 2D and 2D tensors

関連記事、参考資料

numpy.dotの場合は、配列が異なっていいても、内積、行列積、掛け算など切り替えてくれるので便利です。ただし、その分意図した処理にならない場合もあるので注意した方がよい。

コメント