PyTorch torch.cartesian_prod 函数
torch.cartesian_prod 是 PyTorch 中用于计算笛卡尔积的函数。它返回输入张量的笛卡尔积,即所有可能组合的集合。
函数定义
torch.cartesian_prod(*tensors)
使用示例
实例
import torch
# 计算两个张量的笛卡尔积
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5])
result = torch.cartesian_prod(a, b)
print("a:", a)
print("b:", b)
print("笛卡尔积:")
print(result)
# tensor([[1, 4],
# [1, 5],
# [2, 4],
# [2, 5],
# [3, 4],
# [3, 5]])
# 多个张量的笛卡尔积
x = torch.tensor([1, 2])
y = torch.tensor([10, 20, 30])
z = torch.tensor([100, 200])
result = torch.cartesian_prod(x, y, z)
print("三个张量笛卡尔积形状:", result.shape)
print(result)
# 计算两个张量的笛卡尔积
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5])
result = torch.cartesian_prod(a, b)
print("a:", a)
print("b:", b)
print("笛卡尔积:")
print(result)
# tensor([[1, 4],
# [1, 5],
# [2, 4],
# [2, 5],
# [3, 4],
# [3, 5]])
# 多个张量的笛卡尔积
x = torch.tensor([1, 2])
y = torch.tensor([10, 20, 30])
z = torch.tensor([100, 200])
result = torch.cartesian_prod(x, y, z)
print("三个张量笛卡尔积形状:", result.shape)
print(result)

Pytorch torch 参考手册