pytorch torch.nn.Embedding

词嵌入矩阵,可以加载使用word2vector,glove

API

CLASS torch.nn.Embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None, max_norm: Optional[float] = None, norm_type: float = 2.0, scale_grad_by_freq: bool = False, sparse: bool = False, _weight: Optional[torch.Tensor] = None)
参数描述
num_embeddings (int)size of the dictionary of embeddings
embedding_dim (int)the size of each embedding vector
padding_idx (int, optional)If given, pads the output with the embedding vector at padding_idx (initialized to zeros) whenever it encounters the index.
max_norm (float, optional)If given, each embedding vector with norm larger than max_norm is renormalized to have norm max_norm.
norm_type (float, optional)The p of the p-norm to compute for the max_norm option. Default 2.
scale_grad_by_freq (boolean, optional)If given, this will scale gradients by the inverse of frequency of the words in the mini-batch. Default False.
sparse (bool, optional)If True, gradient w.r.t. weight matrix will be a sparse tensor. See Notes for more details regarding sparse gradients.
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(10, 3) # 10表示有10个词,3表示3个维度
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.LongTensor([[1,2,4,5],[4,3,2,9]])
>>> embedding(input)
tensor([[[-0.0251, -1.6902,  0.7172],
         [-0.6431,  0.0748,  0.6969],
         [ 1.4970,  1.3448, -0.9685],
         [-0.3677, -2.7265, -0.1685]],

        [[ 1.4970,  1.3448, -0.9685],
         [ 0.4362, -0.4004,  0.9400],
         [-0.6431,  0.0748,  0.6969],
         [ 0.9124, -2.3616,  1.1151]]])

参考:
https://pytorch.org/docs/master/generated/torch.nn.Embedding.html?highlight=nn%20embedding#torch.nn.Embedding
https://www.cnblogs.com/lindaxin/p/7991436.html

### PyTorch `nn.Embedding` 的用法 在自然语言处理 (NLP) 和其他领域中,嵌入层 (`Embedding Layer`) 是非常重要的组件之一。PyTorch 提供了 `torch.nn.Embedding` 类来创建和管理这些嵌入。 #### 创建 Embedding 层 可以通过指定词汇表大小(即词典中的单词数量)以及每个词的维度来初始化一个 embedding 层: ```python import torch from torch import nn embedding = nn.Embedding(num_embeddings=10, embedding_dim=3) ``` 这里 `num_embeddings` 表示词汇量大小,而 `embedding_dim` 则表示每个词语对应的向量长度[^1]。 #### 输入与输出形状 对于输入张量而言,其最后一个维度应当代表 batch 中样本的数量;其余所有前置维度都将被视作单一样本的一部分。因此,在大多数情况下,输入会是一个二维张量 `(batch_size, seq_len)` 或者一维张量 `(seq_len,)` 当批次大小为 1 时。该函数将会返回具有相同前导尺寸的新张量,但在最后增加了一个新的特征轴用于存储 embeddings 结果,形成三维张量 `(batch_size, seq_len, embedding_dim)` 或两维张量 `(seq_len, embedding_dim)` 如果批次大小为 1。 #### 使用预训练权重 如果希望利用已经预先训练好的 word vectors 初始化 embedding 层,则可以这样做: ```python pretrained_weights = ... # 加载预训练权重矩阵 vocab_size, embed_size = pretrained_weights.shape embedding_layer = nn.Embedding(vocab_size, embed_size).from_pretrained(pretrained_weights) ``` 注意这里的 `.from_pretrained()` 方法可以直接接受 numpy 数组或其他形式的数据作为参数,并据此设置初始权重值。 #### 实际应用案例 考虑如下场景:给定一批句子 ID 序列,想要获取它们各自的 embedding 向量以便后续处理。假设我们有一个简单的例子,其中包含三个句子,每句话有两个 token IDs 组成的小序列: ```python input_tensor = torch.LongTensor([[1, 2], [4, 5], [7, 8]]) output_embedding = embedding(input_tensor) print(output_embedding.size()) # 输出应形如: torch.Size([3, 2, 3]) ``` 这段代码片段展示了如何将整数型 tensor 转换成相应的浮点型 embedding vector 形式的操作过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值