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> 的向量拼接成一个更长的向量,用于后续处理。
相关推荐
Python私教8 分钟前
GenericAgent记忆系统深度解析:四层架构如何让AI拥有永不遗忘的大脑
网络·人工智能·架构
txg66641 分钟前
自动驾驶领域热点简报(2026-04-26 ~ 2026-05-03)
linux·人工智能·自动驾驶
zhaoyong22244 分钟前
MySQL 存储过程中字符集与排序规则不匹配导致查询性能下降的解决方案
jvm·数据库·python
sinat_383437361 小时前
golang如何从Python转型Go开发_golang从Python转型Go开发攻略
jvm·数据库·python
rockey6271 小时前
基于AScript的python3脚本语言发布啦!
python·c#·.net·script·python3·eval·expression·function·动态脚本
gqk011 小时前
Python入门
python
龙山云仓1 小时前
小G&老D求解:第7日·立夏·蝼蝈鸣
人工智能·机器学习
LaughingZhu2 小时前
Product Hunt 每日热榜 | 2026-04-30
人工智能·经验分享·深度学习·神经网络·产品运营
sunneo2 小时前
专栏D-团队与组织-03-产品文化
人工智能·产品运营·aigc·产品经理·ai编程