栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Pytorch: 矩阵的拼接方法】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Pytorch: 矩阵的拼接方法】

torch.cat((a,b), dim=0) 在张量(tensor)的基础维度上拼接在一起

在给定维度上对输入的张量序列seq 进行连接操作。

参数:
(a, b) – a, b可以是任意相同Tensor 类型。输入数据必须是序列,序列中数据是任意相同的shape的同类型tensor。
dim(int, optional) – 沿着此维连接张量序列。维度不可以超过输入数据的任一个张量的维度。

a1 = torch.rand(4,3,32,32)
a2 = torch.rand(5,3,32,32)
torch.cat([a1,a2],dim=0).shape	
# torch.Size([9, 3, 32, 32])

a2 = torch.rand(4,1,32,32)
torch.cat([a1,a2],dim=1).shape		
# torch.Size([4, 4, 32, 32])

a1 = torch.rand(4,3,16,32)
a2 = torch.rand(4,3,16,32)
torch.cat([a1,a2],dim=3).shape
# torch.Size([4, 3, 16, 64])

a1 = torch.rand(4,3,32,32)
torch.cat([a1,a2],dim=0).shape
# RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 32 but got size 16 for tensor number 1 in the list.

注意:使用torch.cat((a, b),dim)时,除拼接维数dim数值可不同外其余维数数值需相同,方能对齐。

torch.stack([a,b], dim=0) 创造一个新的维度

沿着一个新维度对输入张量序列进行连接。 序列中所有的张量都应该为相同形状。

参数:
[Tensor, Tensor, …] – 待连接的张量序列
dim (int) – 插入的维度。必须介于 0 与 待连接的张量序列数之间。

a1 = torch.rand(4,3,16,32)
a2 = torch.rand(4,3,16,32) 
torch.stack([a1,a2],dim=2).shape	# 添加了一个维度。
# torch.Size([4, 3, 2, 16, 32])

a = torch.rand(32,8)
b = torch.rand(32,8)
torch.stack([a,b],dim=0).shape		
# torch.Size([2, 32, 8])

b = torch.rand([30,8])
torch.stack([a,b],dim=0)     # 要求tensor的size完全相同
RuntimeError: stack expects each tensor to be equal size, but got [32, 8] at entry 0 and [30, 8] at entry 1

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001815.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号