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.]])
相关推荐
DevOpenClub27 分钟前
用 Agent 搭建网页内容采集与结构化处理流水线
人工智能
肖永威28 分钟前
Python多业务并行计算框架插件化演进:从硬编码到动态注册
python·插件化·并行计算·动态注册
yz_aiks30 分钟前
Linux Jar包配置Systemd自启动实战:从排查到配置全流程
linux·python·jar·自启动·systemd
56AI32 分钟前
2026 企业级AI智能体开发平台推荐:聚焦底层安全与准确率的智能体平台
人工智能·安全·智能体
沫儿笙36 分钟前
库卡弧焊机器人白车身焊接节气装置
人工智能·机器人
AI智图坊44 分钟前
多件装组合SKU图的批量生产效率分析:从PS手工到AI自动化的工作流改造
大数据·运维·人工智能·gpt·ai作画·自动化·aigc
threelab1 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
不知名的老吴1 小时前
线程的生命周期之线程“插队“
java·开发语言·python
RSTJ_16251 小时前
PYTHON+AI LLM DAY SEVENTY-ONE
人工智能
圣殿骑士-Khtangc1 小时前
单智能体落地实战:从 ReAct 到 Production-Ready AI Agent 全链路解析
人工智能·react.js