PyTorch torch.cumprod Function
Pytorch torch Reference Manual
torch.cumprodIt is a function used to compute the cumulative product in PyTorch. It returns the cumulative product along the specified dimension, i.e., the product of all elements from the beginning to the current position.
Function Definition
torch.cumprod(input, dim, dtype=None)
Usage Example
Example
import torch
# Compute the cumulative product
x = torch.tensor([1, 2, 3, 4, 5])
result = torch.cumprod(x, dim=0)
print("Input:", x)
print("Cumulative product:", result)
# Output: tensor([1, 2, 6, 24, 120])
# Explanation: 1, 1*2=2, 1*2*3=6, 1*2*3*4=24, 1*2*3*4*5=120
# 2-dimensional tensor
x = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)
# Cumulative by column
result_col = torch.cumprod(x, dim=0)
print("nCumulative product by column:")
print(result_col)
# tensor([[ 1, 2, 3],
# [ 4, 10, 18]])
# Cumulative by row
result_row = torch.cumprod(x, dim=1)
print("nCumulative product by row:")
print(result_row)
# tensor([[ 1, 2, 6],
# [ 4, 20, 120]])
# Compute the cumulative product
x = torch.tensor([1, 2, 3, 4, 5])
result = torch.cumprod(x, dim=0)
print("Input:", x)
print("Cumulative product:", result)
# Output: tensor([1, 2, 6, 24, 120])
# Explanation: 1, 1*2=2, 1*2*3=6, 1*2*3*4=24, 1*2*3*4*5=120
# 2-dimensional tensor
x = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32)
# Cumulative by column
result_col = torch.cumprod(x, dim=0)
print("nCumulative product by column:")
print(result_col)
# tensor([[ 1, 2, 3],
# [ 4, 10, 18]])
# Cumulative by row
result_row = torch.cumprod(x, dim=1)
print("nCumulative product by row:")
print(result_row)
# tensor([[ 1, 2, 6],
# [ 4, 20, 120]])
Other Extensions