PyTorch torch.inner 函数
torch.inner 是 PyTorch 中用于计算两个张量内积的函数。对于向量,它等价于点积;对于高维张量,它在指定维度上计算内积。
函数定义
torch.inner(input, other, out=None)
参数:
input(Tensor): 第一个输入张量。other(Tensor): 第二个输入张量。out(Tensor, 可选): 输出张量。
返回值:
torch.Tensor: 返回内积结果。
使用示例
实例 - 向量内积
import torch
# 创建两个向量
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([4.0, 5.0, 6.0])
# 计算内积
result = torch.inner(a, b)
print("向量 a:", a)
print("向量 b:", b)
print("内积结果:", result)
# 创建两个向量
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([4.0, 5.0, 6.0])
# 计算内积
result = torch.inner(a, b)
print("向量 a:", a)
print("向量 b:", b)
print("内积结果:", result)
输出结果为:
向量 a: tensor([1., 2., 3.]) 向量 b: tensor([4., 5., 6.]) 内积结果: tensor(32.)
实例 - 矩阵内积
import torch
# 创建两个矩阵
A = torch.randn(2, 3)
B = torch.randn(2, 3)
# 在最后维度计算内积
result = torch.inner(A, B)
print("A 形状:", A.shape)
print("B 形状:", B.shape)
print("结果形状:", result.shape)
# 创建两个矩阵
A = torch.randn(2, 3)
B = torch.randn(2, 3)
# 在最后维度计算内积
result = torch.inner(A, B)
print("A 形状:", A.shape)
print("B 形状:", B.shape)
print("结果形状:", result.shape)

Pytorch torch 参考手册