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 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智2 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙2 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
AI的探索之旅2 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein2 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
LaughingZhu2 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003962 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫2 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
美狐美颜SDK开放平台2 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk