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])
'''
相关推荐
海边夕阳20061 天前
【每天一个AI小知识】:什么是生成对抗网络?
人工智能·经验分享·深度学习·神经网络·机器学习·生成对抗网络
Wise玩转AI1 天前
Day 27|智能体的 UI 与用户交互层
人工智能·python·ui·ai·chatgpt·ai智能体
s***46981 天前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
runepic1 天前
Python + PostgreSQL 批量图片分发脚本:分类、去重、断点续拷贝
服务器·数据库·python·postgresql
codists1 天前
2025年11月文章一览
python
生而为虫1 天前
31.Python语言进阶
python·scrapy·django·flask·fastapi·pygame·tornado
言之。1 天前
Claude Code 实用开发手册
python
计算机毕设小月哥1 天前
【Hadoop+Spark+python毕设】中国租房信息可视化分析系统、计算机毕业设计、包括数据爬取、Spark、数据分析、数据可视化、Hadoop
后端·python·mysql
2***c4351 天前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
二川bro1 天前
模型部署实战:Python结合ONNX与TensorRT
开发语言·python