PyTorch torch.multinomial 関数


Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

torch.multinomialPyTorch における多項式サンプリングのための関数で、入力テンソルの各行から確率分布に従ってサンプリングを行います。

関数定義

torch.multinomial(input, num_samples, replacement=False, generator=None)

パラメータの説明

  • input- 確率分布テンソル。各行が確率分布であり、すべての確率の合計は1である必要があります
  • num_samples- サンプリング数
  • replacement- 復元抽出を許可するかどうか(デフォルトはFalse)
  • generator- 乱数生成器(オプション)

使用例

例

import torch

# 確率分布を定義
weights = torch.tensor([[0.0, 1.0],   # 2番目のカテゴリの確率が1
                        [0.5, 0.5],   # 2つのカテゴリの確率が等しい
                        [0.2, 0.3, 0.5]])  # 3つのカテゴリ

# 復元抽出なしのサンプリング
result = torch.multinomial(weights, num_samples=2, replacement=False)
print("確率分布:")
print(weights)
print("復元抽出なしのサンプリング結果(各行から2つサンプリング):")
print(result)

# 復元抽出のサンプリング
result_with_replacement = torch.multinomial(weights, num_samples=5, replacement=True)
print("復元抽出のサンプリング結果(各行から5つサンプリング):")
print(result_with_replacement)

Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

その他の拡張