PyTorch torch.triu_indices 関数
torch.triu_indicesPyTorch において上三角行列のインデックスを生成するための関数です。上三角部分(対角線を含む)の行インデックスと列インデックスを返します。
関数定義
torch.triu_indices(row, column, offset=0, dtype=torch.long, device='cpu')
パラメータの説明:
row: 行数column: 列数offset: 対角線のオフセットdtype: 返されるデータ型device: デバイス
使用例
例
import torch
# 3x3 行列の上三角インデックスを生成
row, col = torch.triu_indices(3, 3)
print("row:", row)
print("col:", col)
# 3x3 行列の上三角インデックスを生成
row, col = torch.triu_indices(3, 3)
print("row:", row)
print("col:", col)
出力結果は次のとおりです:
row: tensor([0, 0, 0, 1, 1, 2]) col: tensor([0, 1, 2, 1, 2, 2])
例
import torch
# インデックスを生成してインデックス操作に使用
row, col = torch.triu_indices(3, 3, offset=1)
# 3x3 行列を作成
a = torch.ones(3, 3)
# インデックスを使用して上三角部分を設定
a[row, col] = 0
print(a)
# インデックスを生成してインデックス操作に使用
row, col = torch.triu_indices(3, 3, offset=1)
# 3x3 行列を作成
a = torch.ones(3, 3)
# インデックスを使用して上三角部分を設定
a[row, col] = 0
print(a)
出力結果は次のとおりです:
tensor([[1., 1., 1.],
[0., 1., 1.],
[0., 0., 1.]])
例
import torch
# 非正方行列の場合
row, col = torch.triu_indices(3, 4)
print("row:", row)
print("col:", col)
# 非正方行列の場合
row, col = torch.triu_indices(3, 4)
print("row:", row)
print("col:", col)
出力結果は次のとおりです:
row: tensor([0, 0, 0, 1, 1, 2]) col: tensor([0, 1, 2, 1, 2, 2])
その他の拡張機能
Pytorch torch リファレンスマニュアル