文章目录
- 区别
- torch.cat介绍
- 作用
- 参数
- 使用实例
- 关于参数dim为None的使用
区别
先说结论:没有区别在功能、用法以及作用上,concat函数就是cat函数的别名(官方就是这样说的)。下面截图为证:
因此接下来就主要是介绍 torch.cat 函数的功能和用法。
torch.cat介绍
参考🔗:link
torch.cat(tensors, dim=0, *, out=None) → Tensor
作用
将给定序列的张量在给定维度上连接起来。所有张量必须具有相同的形状(除了连接维度之外),或者是一个尺寸为(0,)的一维空张量。
Concatenates the given sequence of seq tensors in the given dimension. All tensors must either have the same shape (except in the concatenating dimension) or be a 1-D empty tensor with size (0,)
参数
- 第一个参数 tensors :除了要连接的维度外,其他维度的形状都要相同的张量。tensors: Tuple[Tensor, …] | List[Tensor]。写法可以是
(x, x, x)or [x, x, x]。 - 第二个参数 dim:
(int, optiona)指定的连接的维度,可选,默认就是 dim=0,表示水平方向上拼接,即行拼接。这个参数可以是整数,负数,0,以及没有。 - 其他参数不用管。
使用实例
import torch
x = torch.randn(2, 3)
x
# 输出
tensor([[ 1.3524, 0.7867, -0.1423],
[ 1.1235, 0.0221, -0.5478]])
dim=0 表示水平方向的拼接,也就说从shape(2, 3) -> shape(6, 3):
y = torch.cat([x, x, x], dim=0)
y
# 输出
tensor([[ 1.3524, 0.7867, -0.1423],
[ 1.1235, 0.0221, -0.5478],
[ 1.3524, 0.7867, -0.1423],
[ 1.1235, 0.0221, -0.5478],
[ 1.3524, 0.7867, -0.1423],
[ 1.1235, 0.0221, -0.5478]])
dim=1表示:
z = torch.cat((x, x, x), dim=1)
z
# 输出
tensor([[ 1.3524, 0.7867, -0.1423, 1.3524, 0.7867, -0.1423, 1.3524, 0.7867, -0.1423],
[ 1.1235, 0.0221, -0.5478, 1.1235, 0.0221, -0.5478, 1.1235, 0.0221, -0.5478]])
重点关注一下 , dim=-1:
xy = torch.cat((x, x, x), dim=-1)
xy
# 输出
tensor([[ 1.3524, 0.7867, -0.1423, 1.3524, 0.7867, -0.1423, 1.3524, 0.7867, -0.1423],
[ 1.1235, 0.0221, -0.5478, 1.1235, 0.0221, -0.5478, 1.1235, 0.0221, -0.5478]])
没错 dim=-1的结果和dim=1的结果是一致的,但是我要说一下dim=-1表示的是最后一个维度,所以 对于 我举的这个例子只有两个维度而言,dim=-1和dim=1是等效的。
关于参数dim为None的使用
当时我的第一反应是 那我直接就不写这个参数不就得了嘛 所以我尝试了下面的代码,也确实发现和dim=0的效果是一致的。
yy = torch.cat([x, x, x])
yy
但是我在查找的时候遇到有文章是将None赋值给参数dim,所以我尝试后出现了问题如下:
文章链接🔗:link。于是我复制文章的代码运行,发现依旧报错。(无语 误导人)

下面图片是查找的文章的说法:

而我问了chatgpt的回答:
References:
【1】https://discuss.pytorch.org/t/what-does-dim-1-mean-in-torch-cat/110883

![【Qt秘籍】[007]-LineEdit Pushbutton控件](https://img-blog.csdnimg.cn/direct/33c3e9396b834cc6bd7bec62a6981cad.png)















![[经验] 羊肺怎么清洗才干净视频 #经验分享#学习方法#其他](https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=https%3A%2F%2Fwww.hao123rr.com%2Fzb_users%2Fcache%2Fly_autoimg%2Fn%2FNTQ2NTE.jpg&pos_id=dupBiJZP)

