PyTorch 索引与切片-Tensor基本操作

以如下 tensor a 为例,展示常用的 indxing, slicing 及其他高阶操作

python3 复制代码
>>> a = torch.rand(4,3,28,28)
>>> a.shape
torch.Size([4, 3, 28, 28])
  • Indexing: 使用索引获取目标对象,[x,x,x,....]

    python3 复制代码
    >>> a[0].shape
    torch.Size([3, 28, 28])
    >>> a[0,0].shape
    torch.Size([28, 28])
    >>> a[0,0,0].shape 
    torch.Size([28])
    >>> a[0,0,0,0].shape 
    torch.Size([])
  • Slicing: 使用切片获取一截目标对象,::step

    python3 复制代码
    >>> a[:2].shape
    torch.Size([2, 3, 28, 28])
    >>> a[0, :2].shape 
    torch.Size([2, 28, 28])
    >>> a[0, 0, :2].shape 
    torch.Size([2, 28])
    >>> a[0, 0, 0, :2].shape 
    torch.Size([2])
  • 其他汇总:

    python3 复制代码
    >>> a.index_select(dim, torch.tensor([idx_1,idx_2, ...]))  ## by specific idx
    >>> torch.take(a, torch.tensor([idx_1, idx2, ...]))  ## 不指定 dim 先打平 a 再按序提取 
    >>> a[a.ge(0.5)]  ## by mask=a.ge(0.5),该方法没有保持 shape

相关推荐
老胖闲聊1 分钟前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1185 分钟前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之35 分钟前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
scdifsn1 小时前
动手学深度学习12.7. 参数服务器-笔记&练习(PyTorch)
pytorch·笔记·深度学习·分布式计算·数据并行·参数服务器
DFminer1 小时前
【LLM】fast-api 流式生成测试
人工智能·机器人
lyaihao1 小时前
使用python实现奔跑的线条效果
python·绘图
郄堃Deep Traffic2 小时前
机器学习+城市规划第十四期:利用半参数地理加权回归来实现区域带宽不同的规划任务
人工智能·机器学习·回归·城市规划
ai大师2 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
海盗儿2 小时前
Attention Is All You Need (Transformer) 以及Transformer pytorch实现
pytorch·深度学习·transformer
GIS小天2 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票