PyTorch torch.trace 関数


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

torch.tracePyTorch で行列のトレースを計算するための関数です。トレースは行列の主対角成分の和です。

関数定義

torch.trace(input)

パラメータの説明:

  • input: 入力テンソル(少なくとも2次元)

使用例

例

import torch

# 行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# トレース(主対角成分の和)を計算
y = torch.trace(a)
print(y)

出力結果は:

tensor(15)

例

import torch

# 非正方行列を作成
a = torch.tensor([[1, 2, 3], [4, 5, 6]])

# トレースを計算
y = torch.trace(a)
print(y)

出力結果は:

tensor(6)

例

import torch

# 多次元テンソルを作成、最初の2次元のみを考慮
a = torch.randn(3, 4, 4, 5)
y = torch.trace(a)
print(y.shape)

出力結果は:

torch.Size([3, 5])

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

その他の拡張