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> 的向量拼接成一个更长的向量,用于后续处理。
相关推荐
leo03084 分钟前
新一代python管理工具--uv
开发语言·python·uv
UQI-LIUWJ5 分钟前
论文略读:MUSE: Machine Unlearning Six-Way Evaluation for Language Models
人工智能·深度学习·机器学习
艾醒(AiXing-w)6 分钟前
探索大语言模型(LLM):使用EvalScope进行模型评估(API方式)
人工智能·语言模型·自然语言处理
熊猫钓鱼>_>13 分钟前
Python小工具开发实战:从零构建自动化文件管理器的心得与体悟
开发语言·python·自动化
汤姆yu44 分钟前
基于python大数据的nba球员可视化分析系统
大数据·开发语言·python
feifeigo1231 小时前
python从环境变量和配置文件中获取配置参数
开发语言·python·adb
羊小猪~~1 小时前
数据库学习笔记(十五)--变量与定义条件与处理程序
数据库·人工智能·笔记·后端·sql·学习·mysql
大洋PHP1 小时前
PyCharm 配置python解释器
python
waterHBO1 小时前
python 爬虫,爬取某乎某个用户的全部内容 + 写个阅读 app,慢慢读。
开发语言·爬虫·python
ahhhhaaaa-1 小时前
【AI图像生成网站&Golang】部署图像生成服务(阿里云ACK+GPU实例)
开发语言·数据仓库·人工智能·后端·阿里云·golang