PyTorch torch.bincount 関数
torch.bincountは PyTorch で各非負整数値の出現回数を計算するための関数です。新しい1次元テンソルを返し、その i 番目の要素は入力内での値 i の出現回数を表します。ヒストグラム計算やグループ統計によく使用されます。
関数定義
torch.bincount(input, weights=None, minlength=0)
使用例
例
import torch
# 基本用法:各値の出現回数を統計する
x = torch.tensor([0, 1, 1, 2, 2, 2, 3, 3, 4])
counts = torch.bincount(x)
print("入力:", x)
print("カウント結果:", counts)
# 出力: tensor([1, 2, 3, 2, 1])
# weights パラメータを使用
x = torch.tensor([0, 1, 1, 2, 2, 2])
weights = torch.tensor([1.0, 2.0, 3.0, 1.0, 2.0, 3.0])
weighted_counts = torch.bincount(x, weights=weights)
print("重み付きカウント:", weighted_counts)
# 出力: tensor([1., 5., 6.])
# 最小長を設定
x = torch.tensor([0])
counts = torch.bincount(x, minlength=5)
print("最小長5:", counts)
# 出力: tensor([1, 0, 0, 0, 0])
# 基本用法:各値の出現回数を統計する
x = torch.tensor([0, 1, 1, 2, 2, 2, 3, 3, 4])
counts = torch.bincount(x)
print("入力:", x)
print("カウント結果:", counts)
# 出力: tensor([1, 2, 3, 2, 1])
# weights パラメータを使用
x = torch.tensor([0, 1, 1, 2, 2, 2])
weights = torch.tensor([1.0, 2.0, 3.0, 1.0, 2.0, 3.0])
weighted_counts = torch.bincount(x, weights=weights)
print("重み付きカウント:", weighted_counts)
# 出力: tensor([1., 5., 6.])
# 最小長を設定
x = torch.tensor([0])
counts = torch.bincount(x, minlength=5)
print("最小長5:", counts)
# 出力: tensor([1, 0, 0, 0, 0])
その他の拡張
Pytorch torch リファレンスマニュアル