合肥红酒网站建设,江门百度seo公司,企业网站页面,中国信用网站建设的重要性文章目录 区别torch.cat介绍作用参数使用实例关于参数dim为None的使用 区别 先说结论#xff1a;没有区别在功能、用法以及作用上#xff0c;concat函数就是cat函数的别名#xff08;官方就是这样说的#xff09;。下面截图为证#xff1a; 因此接下来就主要是介绍 to… 文章目录 区别torch.cat介绍作用参数使用实例关于参数dim为None的使用 区别 先说结论没有区别在功能、用法以及作用上concat函数就是cat函数的别名官方就是这样说的。下面截图为证 因此接下来就主要是介绍 torch.cat 函数的功能和用法。
torch.cat介绍
参考link torch.cat(tensors, dim0, *, outNone) → 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, xor [x, x, x]。第二个参数 dimint, optiona指定的连接的维度,可选默认就是 dim0表示水平方向上拼接即行拼接。这个参数可以是整数负数0以及没有。其他参数不用管。
使用实例
import torch
x torch.randn(2, 3)
x
# 输出
tensor([[ 1.3524, 0.7867, -0.1423],[ 1.1235, 0.0221, -0.5478]])dim0 表示水平方向的拼接也就说从shape(2, 3) - shape(6, 3)
y torch.cat([x, x, x], dim0)
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]])dim1表示
z torch.cat((x, x, x), dim1)
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的结果和dim1的结果是一致的但是我要说一下dim-1表示的是最后一个维度所以 对于 我举的这个例子只有两个维度而言dim-1和dim1是等效的。
关于参数dim为None的使用
当时我的第一反应是 那我直接就不写这个参数不就得了嘛 所以我尝试了下面的代码也确实发现和dim0的效果是一致的。
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