PyTorch torch.select_scatter 関数


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

torch.select_scatterPyTorch 中でソーステンソルを指定されたインデックス位置に散布するための関数です。それは、srcの値をinputの指定された次元dimとインデックスindexの位置に散布します。

関数定義

torch.select_scatter(input, src, dim, index)

引数:

  • input(Tensor): 入力テンソル、つまり修正対象のテンソル。
  • src(Tensor): ソーステンソル。input に散布する値です。
  • dim(int): 散布する次元。
  • index(int): 散布する位置インデックス。

戻り値:

  • torch.Tensor: 修正後のテンソルを返します。

使用例

例

import torch

# 入力テンソルとソーステンソルを作成
input = torch.zeros(4, 4)
src = torch.ones(4)

# 最初の次元(行)のインデックス1の位置に src を散布
output = torch.select_scatter(input, src, dim=0, index=1)

print("入力テンソル:")
print(input)
print("nソーステンソル:")
print(src)
print("nインデックス1の位置に散布した結果:")
print(output)

出力結果は次のとおりです:

输入张量:
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])

源张量:
tensor([1., 1., 1., 1.])

在索引1位置散布结果:
tensor([[0., 0., 0., 0.],
        [1., 1., 1., 1.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])

例

import torch

# 3Dテンソルを作成
input = torch.zeros(3, 4, 5)
src = torch.ones(5)

# 2番目の次元(インデックス2)に散布
output = torch.select_scatter(input, src, dim=1, index=2)

print("入力形状:", input.shape)
print("ソース形状:", src.shape)
print("結果形状:", output.shape)
print("n結果 (dim=1, index=2):")
print(output[0])

出力結果は次のとおりです:

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

结果 (dim=1, index=2):
tensor([1., 1., 1., 1., 1.])

例

import torch

# 異なる値を使用
input = torch.arange(16).reshape(4, 4).float()
src = torch.tensor([100, 100, 100, 100])

# 最後の行に散布
output = torch.select_scatter(input, src, dim=0, index=-1)

print("元のテンソル:")
print(input)
print("nインデックス-1の位置に散布:")
print(output)

出力結果は次のとおりです:

原始张量:
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [12., 13., 14., 15.]])

散布到索引-1位置:
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [100., 100., 100., 100.]])

注意:torch.select_scatter元の入力テンソルは変更されず、代わりに新しいテンソルが返されます。srcの次元は、置き換えるスライスの次元と一致する必要があります。


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

その他の拡張