PyTorch torch.triu 関数
torch.triuPyTorch において行列の上三角部分(主対角線を含む)を抽出するための関数です。下三角部分は0に設定されます。
関数定義
torch.triu(input, diagonal=0, out=None)
パラメータ説明:
input: 入力テンソルdiagonal: 対角線インデックス。0 は主対角線を表しますout: 出力テンソル
使用例
例
import torch
# 行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 上三角部分を抽出
y = torch.triu(a)
print(y)
# 行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 上三角部分を抽出
y = torch.triu(a)
print(y)
出力結果は次のとおりです:
tensor([[1, 2, 3],
[0, 5, 6],
[0, 0, 9]])
例
import torch
# 行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 主対角線より上の最初の対角線の上三角を抽出
y = torch.triu(a, diagonal=1)
print(y)
# 行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 主対角線より上の最初の対角線の上三角を抽出
y = torch.triu(a, diagonal=1)
print(y)
出力結果は次のとおりです:
tensor([[0, 2, 3],
[0, 0, 6],
[0, 0, 0]])
例
import torch
# 非正方行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 上三角部分を抽出
y = torch.triu(a)
print(y)
# 非正方行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6]])
# 上三角部分を抽出
y = torch.triu(a)
print(y)
出力結果は次のとおりです:
tensor([[1, 2, 3],
[0, 5, 6]])
その他の拡張
Pytorch torch リファレンスマニュアル