2025.7.21 テンソル要素に対する条件判定【torch】
テンソルに対して関係演算子を適用するとブロードキャスト展開された論理値型のテンソルが返される。この値を用いて条件の部分一致や全一致判定を行うことができる。
pt.all(arg1)
pt.any(arg1)
arg1 ...論理値型の配列
pt.all
pt.all は arg1 の全要素が True であるときに True を返す。
code:p.py
import torch as pt
x = pt.tensor(3, 3, 2, 3)
mask = x == 2
print(mask)
print(pt.all(mask))
print(pt.all(x > 2))
'''
tensor(False, False, True, False)
tensor(False)
tensor(False)
'''
pt.any
pt.any は arg1 のうち1つでも True があれば True を返す。
code:p.py
import torch as pt
x = pt.tensor(3, 3, 2, 3)
mask = x == 2
print(mask)
print(pt.any(mask))
print(pt.any(x > 2))
'''
tensor(False, False, True, False)
tensor(True)
tensor(True)
'''
引数は 論理型として解釈可能な配列であればよい。
code:p.py
import torch as pt
x = pt.tensor(-2, -1, 0, 1, 2)
print(x)
print(pt.all(x))
print(pt.any(x))
関連:2025.7.21 配列要素に対する条件判定【numpy】