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])
'''
相关推荐
chh5634 小时前
从 BERT 到大模型:让模型从“会接龙”到“会回答
人工智能·深度学习·bert
TomEval4 小时前
【测AI】第26篇:线上模型监控与告警体系 — 测试不是终点
人工智能·python·功能测试·ai
prince_zxill5 小时前
PEP 751 pylock.toml 实测:pip 26.3 装 6 个包版本全钉死,但 [web] 选不中任何东西
python·pip·依赖管理·pep 751
Thanks_ks7 小时前
Python 的垃圾回收——引用计数撑起日常,分代回收收拾残局
python·内存管理·垃圾回收·循环引用·引用计数·gc 模块·weakref
CyrusYiVPP7 小时前
实测 uv 0.13.7:同一套包,pip 装 94 秒,它只用 19 秒
人工智能·python
yiangL_7 小时前
Python 学习笔记:递归、turtle绘图、字符串与函数
笔记·python·学习
lula8888 小时前
PVC-U、PVC-C、PVC-O 差一个字母,差的是三种增强路线
python
数字工作台9 小时前
给 LangGraph 加一道可审计记忆:替换默认 Checkpointer,实现防篡改 + 崩溃不丢数据
python·agent
DKPT10 小时前
Python 的 Web 框架:选型选错的人,都踩了同一个坑
python