スポンサーリンク

2つのTensor配列の要素ごとの最大値・最小値を取得するtorch.maximum、torch.minimum、torch.fmax、torch.fmin【PyTorch】

PyTorch

2つのTensor配列の要素ごとの最大値・最小値を取得するtorch.maximum、torch.minimum、torch.fmax、torch.fminを使う。

2つのTensor配列の要素ごとの最大値を取得するmaximum、fmax

torch.maximumtorch.fmaxの第一引数と第二引数に、Tensor配列を指定すると要素ごとの最大値を取得できる。

import torch

a = torch.tensor((1, 2, -1))
b = torch.tensor((3, 0, 4))

print(torch.maximum(a, b))
# tensor([3, 2, 4])

print(torch.fmax(a, b))
# tensor([3, 2, 4])

片方の配列がスカラーの場合は、スカラー値と各要素との最大値を取得する。

a = torch.tensor((1, 2, -1))
b = torch.tensor((0))

print(torch.maximum(a, b))
# tensor([1, 2, 0])

print(torch.fmax(a, b))
# tensor([1, 2, 0])

maximum、fmaxの違い

配列にnanが含まれる場合の処理が異なる。maximumnanを含んだ結果で、fmaxnanを除外された結果が取得される。

a = torch.tensor((1, float('nan'), -1))
b = torch.tensor((3, 0, 4))

print(torch.maximum(a, b))
# tensor([3., nan, 4.])

print(torch.fmax(a, b))
# tensor([3., 0., 4.])

2つのTensor配列の要素ごとの最小値を取得するminimum、fmin

torch.minimumtorch.fminの第一引数と第二引数に、Tensor配列を指定すると要素ごとの最小値を取得できる。

a = torch.tensor((1, 2, -1))
b = torch.tensor((3, 0, 4))

print(torch.minimum(a, b))
# tensor([ 1,  0, -1])

print(torch.fmin(a, b))
# tensor([ 1,  0, -1])

片方の配列がスカラーの場合は、スカラー値と各要素との最小値を取得する。

a = torch.tensor((1, 2, -1))
b = torch.tensor((0))

print(torch.minimum(a, b))
# tensor([ 0,  0, -1])

print(torch.fmin(a, b))
# tensor([ 0,  0, -1])

minimum、fminの違い

配列にnanが含まれる場合の処理が異なる。minimumnanを含んだ結果で、fminnanを除外された結果が取得される。

a = torch.tensor((1, float('nan'), -1))
b = torch.tensor((3, 0, 4))

print(torch.minimum(a, b))
# tensor([ 1., nan, -1.])

print(torch.fmin(a, b))
# tensor([ 1.,  0., -1.])

関連記事、参考記事

PyTorch公式ページでも紹介されていた本で、「Tensorの仕組み」から「ディープラーニングの実践プロジェクト:肺がんの早期発見」までステップバイステップで説明しているため、中身をよく理解できます。

PyTorch実践入門 (Compass Booksシリーズ)

コメント