PyTorch torch.diff 関数
torch.diffPyTorch でテンソルの隣接する要素間の差分を計算するための関数です。計算式は out[i] = input[i+1] - input[i] です。
関数定義
torch.diff(input, n=1, dim=-1, prepend=None, append=None)
引数の説明:
input: 入力テンソルn: 差分回数、デフォルトは1dim: 差分を計算する次元prepend: 計算前に入力に prepend する値append: 計算後に入力に append する値
使用例
例
import torch
# テンソルを作成
x = torch.tensor([1, 3, 6, 10])
# 1階差分を計算
y = torch.diff(x)
print(y)
# テンソルを作成
x = torch.tensor([1, 3, 6, 10])
# 1階差分を計算
y = torch.diff(x)
print(y)
出力結果は次のとおりです:
tensor([2, 3, 4])
例
import torch
# テンソルを作成
x = torch.tensor([1, 3, 6, 10])
# 2階差分を計算
y = torch.diff(x, n=2)
print(y)
# テンソルを作成
x = torch.tensor([1, 3, 6, 10])
# 2階差分を計算
y = torch.diff(x, n=2)
print(y)
出力結果は次のとおりです:
tensor([1, 1])
例
import torch
# 2次元テンソルを作成
x = torch.tensor([[1, 3, 6, 10], [2, 5, 9, 14]])
# 最後の次元で差分を計算
y = torch.diff(x)
print(y)
# 2次元テンソルを作成
x = torch.tensor([[1, 3, 6, 10], [2, 5, 9, 14]])
# 最後の次元で差分を計算
y = torch.diff(x)
print(y)
出力結果は次のとおりです:
tensor([[2, 3, 4],
[3, 4, 5]])
その他の拡張
Pytorch torch リファレンスマニュアル