PyTorch中各种求和运算

首先定义张量A

python 复制代码
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [12., 13., 14., 15.],
        [16., 17., 18., 19.]])

1. 降维求和

降维求和会沿指定轴降低张量的维度,使它变为一个标量。

python 复制代码
A_sum_axis0 = A.sum(axis=0)  # 压缩为一行
tensor([40., 45., 50., 55.]

A_sum_axis1 = A.sum(axis=1)  # 压缩为一列
tensor([ 6., 22., 38., 54., 70.]

A_sum = A.sum(axis=[0, 1])  # 结果与 A.sum() 相同
tensor(190.)

2. 非降维求和

保持轴数不变

python 复制代码
A_sum_axis0 = A.sum(axis=0, keepdims=True)
tensor([[40., 45., 50., 55.]])

A_sum_axis1 = A.sum(axis=1, keepdims=True)
tensor([[ 6.],
        [22.],
        [38.],
        [54.],
        [70.]])

A_sum = A.sum(axis=[0, 1], keepdims=True)
tensor([[190.]])

3. 累积求和

沿某个轴计算A元素的累积总和,此函数不会沿任何轴降低输入张量的维度。

python 复制代码
A_sum_axis0 = A.cumsum(axis=0)
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  6.,  8., 10.],
        [12., 15., 18., 21.],
        [24., 28., 32., 36.],
        [40., 45., 50., 55.]])

A_sum_axis1 = A.cumsum(axis=1)
tensor([[ 0.,  1.,  3.,  6.],
        [ 4.,  9., 15., 22.],
        [ 8., 17., 27., 38.],
        [12., 25., 39., 54.],
        [16., 33., 51., 70.]])
相关推荐
叁两2 小时前
用opencode打造全自动公众号写作流水线,AI 代笔太香了!
前端·人工智能·agent
敏编程2 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪2 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
strayCat232552 小时前
Clawdbot 源码解读 7: 扩展机制
人工智能·开源
王鑫星2 小时前
SWE-bench 首次突破 80%:Claude Opus 4.5 发布,Anthropic 的野心不止于写代码
人工智能
lnix2 小时前
当“大龙虾”养在本地:我们离“反SaaS”的AI未来还有多远?
人工智能·aigc
泉城老铁2 小时前
Dify知识库如何实现多关键词AND检索?
人工智能
阿星AI工作室3 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
databook3 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效