PyTorch torch.cumsum 関数


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

torch.cumsumPyTorch で累積和を計算するための関数です。指定した次元に沿った累積和、つまり先頭から現在位置までのすべての要素の和を返します。

関数定義

torch.cumsum(input, dim, dtype=None)

使用例

実例

import torch

# 累積和を計算
x = torch.tensor([1, 2, 3, 4, 5])
result = torch.cumsum(x, dim=0)
print("入力:", x)
print("累積和:", result)
# 出力: tensor([1, 3, 6, 10, 15])
# 説明: 1, 1+2=3, 1+2+3=6, 1+2+3+4=10, 1+2+3+4+5=15

# 2次元テンソル
x = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)
# 列ごとに累積
result_col = torch.cumsum(x, dim=0)
print("n列ごとの累積和:")
print(result_col)
# tensor([[ 1,  2,  3],
#         [ 5,  7,  9]])

# 行ごとに累積
result_row = torch.cumsum(x, dim=1)
print("n行ごとの累積和:")
print(result_row)
# tensor([[ 1,  3,  6],
#         [ 4,  9, 15]])

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

その他の拡張