Pytorch 中 tensor的维度拼接
2024-10-19 14:48:17
torch.stack() 和 torch.cat() 都可以按照指定的维度进行拼接,但是两者也有区别,torch.satck() 是增加新的维度进行堆叠,即其维度拼接后会增加一个维度;而torch.cat() 是在原维度上进行堆叠,即其维度拼接后的维度个数和原来一致。具体说明如下:
torch.stack(input,dim)
input: 待拼接的张量序列组(list or tuple),拼接的tensor的维度必须要相等,即tensor1.shape = tensor2.shape
dim: 在哪个新增的维度上进行拼接,不能超过拼接后的张量数据的维度大小,默认为 0
import torch
x1 = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
x2 = torch.tensor([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print(torch.stack((x1,x2),dim=0).shape)
print(torch.stack((x1,x2),dim=1).shape)
print(torch.stack((x1,x2),dim=2).shape)
print(torch.stack((x1,x2),dim=0))
print(torch.stack((x1,x2),dim=1))
print(torch.stack((x1,x2),dim=2))
>> torch.Size([2, 3, 3]) # 2 表示是有两个tensor的拼接,且在第一个维度的位置拼接
>> torch.Size([3, 2, 3])
>> torch.Size([3, 3, 2])
>> tensor([[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]],
[[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]])
>> tensor([[[ 1, 2, 3],
[10, 20, 30]],
[[ 4, 5, 6],
[40, 50, 60]],
[[ 7, 8, 9],
[70, 80, 90]]])
>> tensor([[[ 1, 10],
[ 2, 20],
[ 3, 30]],
[[ 4, 40],
[ 5, 50],
[ 6, 60]],
[[ 7, 70],
[ 8, 80],
[ 9, 90]]])
torch.cat(input, dim)
input: 待拼接的张量序列组(list or tuple),拼接的tensor的维度必须要相等,即tensor1.shape = tensor2.shape
dim: 在哪个已存在的维度上进行拼接,不能超过拼接后的张量数据的维度大小(即原来的维度大小),默认为 0
import torch
x1 = torch.tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
x2 = torch.tensor([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
print(torch.cat((x1,x2),dim=0).shape)
print(torch.cat((x1,x2),dim=1).shape)
print(torch.cat((x1,x2),dim=0))
print(torch.cat((x1,x2),dim=1))
>> torch.Size([6, 3])
>> torch.Size([3, 6])
>> tensor([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
>> tensor([[ 1, 2, 3, 10, 20, 30],
[ 4, 5, 6, 40, 50, 60],
[ 7, 8, 9, 70, 80, 90]])
最新文章
- 开源监控软件ganglia安装手册
- ecliplse高亮显示选中的相同变量
- Paxos算法与Zookeeper分析
- core文件
- 一些bug总结
- 三星嵌入式开发平台 三星Cortex-A9 4412 POP与SCP对比
- angular的GitHub Repository Directive Example学习
- ECSHOP Inject PHPCode Into \library\myship.php Via \admin\template.php &;&; \includes\cls_template.php Vul Tag_PHP_Code Execute Getshell
- Java Thread Status(转)
- 转:说说JSON和JSONP
- JavaScript定时机制setTimeout与setInterval研究
- Android最新支持包Design简介
- supervisor笔记
- Error response from daemon: rpc error: code = Unknown desc = name conflicts with
- .net core 中间件实战
- spark run using IDE / Maven
- js之全局变量与window对象
- DQN-深度Q网络
- lecture1-Word2vec实战班-七月在线nlp
- 基于esky实现python应用的自动升级
热门文章
- tmux 快速上手
- Hadoop(三)通过C#/python实现Hadoop MapReduce
- 【链表】【leetCode高频】: 19. 删除链表的倒数第 N 个结点
- 初始 Django
- 204. Count Primes - LeetCode
- c++ web框架实现之静态反射实现
- 基于 GraphQL 的 BFF 实践
- .NET MAUI 正式版GA发布
- jeecgboot-vue3笔记(九)——treeSelect树形选择组件的使用(异步加载)
- 聊聊 C# 中的多态底层 (虚方法调用) 是怎么玩的