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> 的向量拼接成一个更长的向量,用于后续处理。
相关推荐
JarmanYuo几秒前
ARM (Attention Refinement Module)
python·计算机视觉
正经教主4 分钟前
【基础】Windows开发设置入门4:Windows、Python、Linux和Node.js包管理器的作用和区别(AI整理)
linux·windows·python·包管理器
王哥儿聊AI6 分钟前
基于LLM合成高质量情感数据,提升情感分类能力!!
人工智能·分类·数据挖掘
t1987512811 分钟前
基于MATLAB-GUI图形界面的数字图像处理
人工智能·计算机视觉·matlab
悟空聊架构12 分钟前
10 分钟打造一款超级马里奥小游戏,重拾20 年前的乐趣
人工智能·codebuddy首席试玩官
观察者SK15 分钟前
当硅基存在成为人性延伸的注脚:论情感科技重构社会联结的可能性
人工智能·科技·重构
Q_Q196328847521 分钟前
python的漫画网站管理系统
开发语言·spring boot·python·django·flask·node.js·php
搂……住31 分钟前
第一次做逆向
python
卡尔曼的BD SLAMer37 分钟前
计算机视觉与深度学习 | Python实现EMD-SSA-VMD-LSTM-Attention时间序列预测(完整源码和数据)
python·深度学习·算法·cnn·lstm
深情不及里子1 小时前
AI Agent | Coze 插件使用指南:从功能解析到实操步骤
人工智能·coze·插件配置