torch.stack()方法在数据集构造中的应用

torch.stack() 是 PyTorch 中用于将多个张量沿着新维度进行堆叠的操作。在你的代码中,e1_encodings 和 e2_encodings 是从每个句子中提取的 <e1:xxx> 和 <e2:xxx> 的向量,形状为 [hidden_size]。当我们对它们使用 torch.stack() 时,多个向量会堆叠成一个新的二维张量,形状为 [num_sentences, hidden_size],其中 num_sentences 是句子的数量。

如果你想将 <e1:xxx> 和 <e2:xxx> 的向量拼接在一起,那么可以使用 torch.cat() 来沿着第二个维度(dim=1)进行拼接。

拼接的代码示例:

python 复制代码
# 将结果转换为张量
e1_encodings = torch.stack(e1_encodings)  # 形状 [num_sentences, hidden_size]
e2_encodings = torch.stack(e2_encodings)  # 形状 [num_sentences, hidden_size]

# 拼接 e1_encodings 和 e2_encodings
# 通过 dim=1 沿着第二个维度拼接,结果形状 [num_sentences, hidden_size * 2]
combined_encodings = torch.cat((e1_encodings, e2_encodings), dim=1)

print("Combined Encodings shape:", combined_encodings.shape)

解释:

  • torch.stack(e1_encodings) :假设 e1_encodings 是一个列表,其中每个元素是形状 [hidden_size] 的张量。torch.stack() 会将这些向量堆叠成一个新的二维张量,形状为 [num_sentences, hidden_size]。
  • torch.cat((e1_encodings, e2_encodings), dim=1) :使用 torch.cat() 沿着第二个维度(dim=1)将 <e1:xxx> 和 <e2:xxx> 的向量拼接在一起,结果张量的形状变为 [num_sentences, hidden_size * 2]。

举例说明:

假设 e1_encodings 和 e2_encodings 是以下两个列表:

python 复制代码
e1_encodings = [torch.tensor([0.1, 0.2, 0.3]), torch.tensor([0.4, 0.5, 0.6])]
e2_encodings = [torch.tensor([0.7, 0.8, 0.9]), torch.tensor([1.0, 1.1, 1.2])]

使用 torch.stack() 之后,e1_encodings 和 e2_encodings 的形状变为 [2, 3]:

python 复制代码
e1_encodings = tensor([[0.1, 0.2, 0.3],
                       [0.4, 0.5, 0.6]])

e2_encodings = tensor([[0.7, 0.8, 0.9],
                       [1.0, 1.1, 1.2]])

然后使用 torch.cat() 将它们拼接在一起,得到的 combined_encodings 形状为 [2, 6]:

python 复制代码
combined_encodings = tensor([[0.1, 0.2, 0.3, 0.7, 0.8, 0.9],
                             [0.4, 0.5, 0.6, 1.0, 1.1, 1.2]])

这个拼接后的向量可以作为后续任务(例如分类)的输入。

总结:

  • torch.stack() 是沿着新维度将多个张量堆叠在一起,适用于将同一维度的张量变成更高维的张量。
  • torch.cat() 是沿着已有维度进行拼接,适用于将多个张量在某个维度上合并。在你的任务中,torch.cat() 可以将 <e1:xxx> 和 <e2:xxx> 的向量拼接成一个更长的向量,用于后续处理。
相关推荐
回眸&啤酒鸭4 天前
【回眸】Minicart 电商购物车核心功能落地指南
人工智能
一隅论数智4 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
AI的探索之旅4 天前
97 个 OpenCV 实例(三十):双目立体,从标定到点云
人工智能·opencv·计算机视觉
AlbertZein4 天前
Step-5-Preview 上手实测:3D 游戏、金融分析、网页设计一次跑完
人工智能·aigc
LaughingZhu4 天前
Product Hunt 每日热榜 | 2026-09-19
人工智能·深度学习·神经网络·搜索引擎·百度
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
美狐美颜SDK开放平台4 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk