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

torch.stack() 是 PyTorch 中用于将多个张量沿着新维度进行堆叠的操作。在你的代码中,e1_encodingse2_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_encodingse2_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_encodingse2_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> 的向量拼接成一个更长的向量,用于后续处理。
相关推荐
databook5 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室5 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
飞哥数智坊7 小时前
GPT-5-Codex 发布,Codex 正在取代 Claude
人工智能·ai编程
倔强青铜三7 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
虫无涯8 小时前
Dify Agent + AntV 实战:从 0 到 1 打造数据可视化解决方案
人工智能
Dm_dotnet10 小时前
公益站Agent Router注册送200刀额度竟然是真的
人工智能
算家计算10 小时前
7B参数拿下30个世界第一!Hunyuan-MT-7B本地部署教程:腾讯混元开源业界首个翻译集成模型
人工智能·开源
用户25191624271110 小时前
Python之语言特点
python
机器之心10 小时前
LLM开源2.0大洗牌:60个出局,39个上桌,AI Coding疯魔,TensorFlow已死
人工智能·openai
刘立军10 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql