torch.cat 使用小节

torch.cat 使用小节

torch.cat 要求在所指定拼接维度之外的所有维度都要匹配,例如

python 复制代码
import torch
v1 = torch.tensor([[1, 2, 3], [4, 5, 6], [4, 5, 6]])  # 3*3
v2 = torch.tensor([[3, 6, 8]])  # 1*3
torch.cat([v1, v2], dim=1)

运行之后会报错

Sizes of tensors must match except in dimension 1. Expected size 3 but got size 1 for tensor number 1 in the list.

这就是因为这两个向量的第 0 个维度不相等,故无法完成 cat 操作,改成 dim=0 即可得到输出:

python 复制代码
tensor([[1, 2, 3],
        [4, 5, 6],
        [4, 5, 6],
        [3, 6, 8]])

这种操作实际上完成了多个 batch 间数据的合并,若想完成同个 batch 内数据的 cat,要保证第 0 个维度大小一致,即 batchsize 相等。

python 复制代码
import torch

v1 = torch.tensor([[1, 2, 3, 3], [4, 5, 6, 6]])  # 2*4
v2 = torch.tensor([[6, 6], [8, 8]])  # 1*3
torch.cat([v1, v2], dim=1)

可得到预期输出:

python 复制代码
tensor([[1, 2, 3, 3, 6, 6],
        [4, 5, 6, 6, 8, 8]])
相关推荐
05664621 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华1 天前
Python与C++:异同点对比
c++·python
hangyuekejiGEO1 天前
GEO技术服务选型指南
大数据·人工智能·python
软萌萌的11 天前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Dxy12393102161 天前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
持敬chijing1 天前
Python概述
开发语言·python
妍妍爱学习1 天前
自动编码器与变分自动编码器:同一脉络下的进化
深度学习·无监督学习·概率模型·自动编码器·变分自动编码器
赤羽尾风1 天前
NumPy快速入门
python·numpy
倒流时光三十年1 天前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django