PyTorch torch.index_add 関数


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

torch.index_addは、PyTorch においてソーステンソルの値を指定されたインデックス位置に加算するために使用される関数です。指定された次元に沿って、dim、index指定されたインデックス位置に加算sourceされた値。

関数定義

torch.index_add(input, dim, index, source, *, alpha=1)

引数:

  • input(Tensor): 入力テンソル。
  • dim(int): インデックスの次元。
  • index(Tensor): 1次元の整数テンソルで、加算先の位置を指定します。
  • source(Tensor): ソーステンソル、加算する値。
  • alpha(float, オプション): source のスケール係数(デフォルトは 1)。

戻り値:

  • torch.Tensor: 変更されたテンソルを返します。

使用例

例

import torch

# 入力テンソルを作成
input = torch.randn(4, 5)

# インデックスとソースを作成
index = torch.tensor([0, 2, 3])
source = torch.randn(3, 5)

# dim=0 に沿って追加
output = torch.index_add(input, dim=0, index=index, source=source)

print(入力形状:, input.shape)
print(インデックス:, index)
print(ソース形状:, source.shape)
print(結果形状:, output.shape)
print(n結果:)
print(output)

出力結果:

输入形状: torch.Size([4, 5])
索引: tensor([0, 2, 3])
源形状: torch.Size([3, 5])
结果形状: torch.Size([4, 5])

结果:
tensor([[ 1.8435,  0.3463, -0.1024,  0.5678,  0.1234],
        [-0.5678,  0.8901, -0.2345,  0.6789, -0.1234],
        [ 2.3456,  0.4567,  0.7890, -0.3456,  0.5678],
        [-0.7890,  1.2345,  0.3456, -0.8901,  0.2345]])

例

import torch

# alpha パラメータを使用してソースをスケーリング
input = torch.zeros(5)
index = torch.tensor([0, 2, 4])
source = torch.tensor([10, 20, 30])

# alpha=2 は source * 2 を加算することを示します
output = torch.index_add(input, dim=0, index=index, source=source, alpha=2)

print(入力:, input)
print(ソース:, source)
print(alpha=2 後の結果:, output)

出力結果:

输入: tensor([0., 0., 0., 0., 0.])
源: tensor([10., 20., 30.])
alpha=2 后的结果: tensor([20.,  0., 40.,  0., 60.])

例

import torch

# 他の次元に沿って加算
input = torch.zeros(3, 4, 5)
index = torch.tensor([1, 3])
source = torch.randn(2, 4, 5)

# dim=1 に沿って加算
output = torch.index_add(input, dim=1, index=index, source=source)

print(入力形状:, input.shape)
print(インデックス形状:, index.shape)
print(ソース形状:, source.shape)
print(結果形状:, output.shape)

出力結果:

输入形状: torch.Size([3, 4, 5])
索引形状: torch.Size([2])
源形状: torch.Size([2, 4, 5])
结果形状: torch.Size([3, 4, 5])

例

import torch

# ニューラルネットワークでの応用:アテンション機構
# 複数のkey-valueペアがあり、queryに集約する必要があるとします

# queryとkey-valueを模擬
num_queries = 2
num_kv = 4
dim = 3

# queryのインデックス
query_idx = torch.tensor([0, 1])
# 対応するvalue
values = torch.randn(num_queries, dim) * 10

# 出力
output = torch.zeros(num_kv, dim)
# valueを対応する位置に加算
output = torch.index_add(output, dim=0, index=query_idx, source=values)

print(Queryインデックス:, query_idx)
print("Values:", values)
print(集約結果:, output)

注意:torch.index_add元の入力テンソルは変更されず、新しいテンソルが返されます。もしindexの中に重複するインデックスがある場合、値は累積されます。alphaパラメータはソース値をスケーリングするために使用できます。


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

その他の拡張