torch.cat 与torch.stack的区别

torch.cat 与torch.stack的区别
torch.cat
  • 定义:按照规定的维度进行拼接。
  • 实际使用: 例如使用BiLSTM时,将两个方向的向量进行叠加,就是用torch.cat。
python 复制代码
import torch

forward_lstm = torch.randn((2, 10, 3))
backward_lstm = torch.randn((2, 10, 3))

lstm_emd = torch.cat((forward_lstm, backward_lstm), dim=-1)

print(lstm_emd.size())
'''
torch.Size([2, 10, 6])
'''
torch.stack
  • 定义:官方解释是在新的dim上进行叠加。叠加的意思就是增加一个维度。
  • 本质:对张量进行unsqueeze(dim)之后,再进行torch.cat(dim=dim)操作。
  • 实际使用:将张量合在一起,形成一个batch。
python 复制代码
import torch

batch_1 = torch.randn((10, 3))
batch_2 = torch.randn((10, 3))
batch = torch.stack((batch_1, batch_2), dim=0) 
print(batch.size()) 
'''
torch.Size([2, 10, 3])
'''
  • 使用torch.unsqueeze 和torch.cat实现torch.stack功能
python 复制代码
import torch

batch_1 = torch.randn((10, 3))
batch_2 = torch.randn((10, 3))

batch_1 = torch.unsuqeeze(batch_1, dim=0)
batch_2 = torch.unsuqeeze(batch_2, dim=0)
batch = torch.cat((batch_1, batch_2), dim=0) 
print(batch.size()) 
'''
torch.Size([2, 10, 3])
'''
相关推荐
一切皆是因缘际会14 小时前
从概率拟合到内生心智:2026 下一代 AI 架构演进与落地实践
人工智能·深度学习·算法·架构
七颗糖很甜15 小时前
电离层对地基雷达测量精度的影响分析与校正方法
python
AC赳赳老秦15 小时前
知识产权辅助:用 OpenClaw 批量生成专利交底书 / 软著申请材料,自动校验格式与内容合规性
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
小熊Coding15 小时前
Python2D射击冒险闯关游戏2.0版本
python·pygame
FYKJ_201016 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
β添砖java16 小时前
深度学习(19)经典神经网络LeNet
人工智能·深度学习·神经网络
野生的程序媛17 小时前
关于我做了一个玩偶姐姐桌宠
人工智能·深度学习·神经网络·机器学习·chatgpt·ai作画·gpt-3
__Wedream__17 小时前
NTIRE 2026 Challenge on Remote Sensing Infrared Image Super-Resolution冠军方案解读
深度学习·cvpr·超分辨率重建·ntire·图像复原和增强
yanghuashuiyue17 小时前
Deep Agents 框架-CLI
python·langchain·langgraph·deepagents
LaughingZhu17 小时前
Product Hunt 每日热榜 | 2026-05-04
人工智能·经验分享·深度学习·神经网络·产品运营