关于torch.nn.Embedding的浅显理解

最近在使用词嵌入向量表示我的数据标签,并且在试图理解torch.nn.Embedding函数。

torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, _freeze=False, device=None, dtype=None)

这里只解释我对前两个参数的理解,这也是我唯二理解的:num_embeddings(int) -- size of the dictionary of embeddings,其实就是你给Embedding函数的张量里互不相同的数的个数;embedding_dim (int) -- the size of each embedding vector也即生成的词嵌入向量的最后一个维度。For example:

python 复制代码
import torch.nn as nn
import torch

known_label_lt = nn.Embedding(3, 10)

label = torch.tensor([
    [1, 0, 1, 0, 1],
    [2, 1, 0, 2, 1],
    [1, 1, 2, 1, 0],
    [1, 1, 0, 1, 2]
]).long() # without .long(), will result in an error. 

state = known_label_lt(label)
print(state.shape)

这里输入的向量label里只能包含三个不同的数:0,1,2 。或者反过来说known_label_lt的第一个参数只能是3,known_label_lt的第二个参数就决定了label的每一个数会被扩展到10维。所以最后生成的词嵌入维度是:

python 复制代码
torch.Size([4, 5, 10])
相关推荐
老鱼说AI19 小时前
大规模并发处理器程序设计(PMPP)讲解(CUDA架构):第四期:计算架构与调度
c语言·深度学习·算法·架构·cuda
Hello.Reader20 小时前
深度学习 — 从人工智能到深度学习的演进之路(一)
人工智能·深度学习
Zzzz_my21 小时前
正则表达式(RE)
pytorch·python·正则表达式
alex18011 天前
pytorch LSTM类解析
pytorch·机器学习·lstm
剑穗挂着新流苏3121 天前
114_PyTorch 进阶:模型保存与读取的两大方式及“陷阱”避坑指南
人工智能·pytorch·深度学习
GoCoding1 天前
Triton + RISC-V
pytorch·openai·编译器
GoCodingInMyWay1 天前
Triton + RISC-V
pytorch·riscv·triton
棱镜研途1 天前
EI会议分享 | 2026年图像处理与模式识别国际会议(IC-IPPR 2026)【SPIE出版】
图像处理·人工智能·深度学习·目标检测·计算机·计算机视觉·视觉检测
rebekk1 天前
pytorch custom op的简单介绍
人工智能·pytorch·python