捷徑

Embedding

class 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)[source][source]

一個簡單的查找表,用於儲存固定字典和大小的嵌入 (embeddings)。

這個模組通常用於儲存詞嵌入,並使用索引來檢索它們。該模組的輸入是索引列表,輸出是相應的詞嵌入。

參數
  • num_embeddings (int) – 嵌入字典的大小

  • embedding_dim (int) – 每個嵌入向量的大小

  • padding_idx (int, optional) – 如果指定,padding_idx 處的條目不會對梯度產生貢獻;因此,padding_idx 處的嵌入向量在訓練期間不會更新,也就是說,它保持為固定的「pad」。對於新構建的 Embedding,padding_idx 處的嵌入向量預設為全零,但可以更新為另一個值以用作 padding 向量。

  • max_norm (float, optional) – 如果給定,則每個範數 (norm) 大於 max_norm 的嵌入向量將被重新歸一化,使其範數為 max_norm

  • norm_type (float, optional) – 用於計算 max_norm 選項的 p 範數的 p 值。預設值為 2

  • scale_grad_by_freq (bool, optional) – 如果給定,這將根據小批量 (mini-batch) 中單詞頻率的倒數來縮放梯度。預設值為 False

  • sparse (bool, optional) – 如果為 True,則相對於 weight 矩陣的梯度將是一個稀疏張量 (sparse tensor)。有關稀疏梯度的更多詳細資訊,請參閱 Notes。

變數

weight (Tensor) – 模組的可學習權重,形狀為 (num_embeddings, embedding_dim),從 N(0,1)\mathcal{N}(0, 1) 初始化

形狀
  • Input: ()(*), IntTensor 或 LongTensor,包含要提取的索引,形狀任意

  • Output: (,H)(*, H), 其中 * 是輸入形狀,H=embedding_dimH=\text{embedding\_dim}

注意

請記住,只有有限數量的最佳化器支援稀疏梯度:目前是 optim.SGD (CUDACPU)、optim.SparseAdam (CUDACPU) 和 optim.Adagrad (CPU)

注意

max_norm 不是 None 時,Embedding 的 forward 方法將會就地修改 weight 張量。 由於梯度計算所需的張量不能就地修改,因此在調用 Embedding 的 forward 方法之前,對 Embedding.weight 執行可微分操作,需要在 max_norm 不是 None 時複製 Embedding.weight。 例如:

n, d, m = 3, 5, 7
embedding = nn.Embedding(n, d, max_norm=1.0)
W = torch.randn((m, d), requires_grad=True)
idx = torch.tensor([1, 2])
a = embedding.weight.clone() @ W.t()  # weight must be cloned for this to be differentiable
b = embedding(idx) @ W.t()  # modifies weight in-place
out = (a.unsqueeze(0) + b.unsqueeze(1))
loss = out.sigmoid().prod()
loss.backward()

範例

>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(10, 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]]])


>>> # example with padding_idx
>>> embedding = nn.Embedding(10, 3, padding_idx=0)
>>> input = torch.LongTensor([[0, 2, 0, 5]])
>>> embedding(input)
tensor([[[ 0.0000,  0.0000,  0.0000],
         [ 0.1535, -2.0309,  0.9315],
         [ 0.0000,  0.0000,  0.0000],
         [-0.1655,  0.9897,  0.0635]]])

>>> # example of changing `pad` vector
>>> padding_idx = 0
>>> embedding = nn.Embedding(3, 3, padding_idx=padding_idx)
>>> embedding.weight
Parameter containing:
tensor([[ 0.0000,  0.0000,  0.0000],
        [-0.7895, -0.7089, -0.0364],
        [ 0.6778,  0.5803,  0.2678]], requires_grad=True)
>>> with torch.no_grad():
...     embedding.weight[padding_idx] = torch.ones(3)
>>> embedding.weight
Parameter containing:
tensor([[ 1.0000,  1.0000,  1.0000],
        [-0.7895, -0.7089, -0.0364],
        [ 0.6778,  0.5803,  0.2678]], requires_grad=True)
classmethod from_pretrained(embeddings, freeze=True, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False)[原始碼][原始碼]

從給定的二維 FloatTensor 建立 Embedding 實例。

參數
  • embeddings (Tensor) – FloatTensor,包含 Embedding 的權重。 第一個維度作為 num_embeddings 傳遞給 Embedding,第二個維度作為 embedding_dim

  • freeze (bool, optional) – 如果 True,張量在學習過程中不會更新。 等同於 embedding.weight.requires_grad = False。 預設值: True

  • padding_idx (int, optional) – 如果指定,則 padding_idx 處的條目不會影響梯度;因此,padding_idx 處的 embedding 向量在訓練期間不會更新,也就是說,它仍然是一個固定的「pad」。

  • max_norm (float, optional) – 請參閱模組初始化文件。

  • norm_type (float, optional) – 請參閱模組初始化文件。預設值 2

  • scale_grad_by_freq (bool, optional) – 請參閱模組初始化文件。預設值 False

  • sparse (bool, optional) – 請參閱模組初始化文件。

範例

>>> # FloatTensor containing pretrained weights
>>> weight = torch.FloatTensor([[1, 2.3, 3], [4, 5.1, 6.3]])
>>> embedding = nn.Embedding.from_pretrained(weight)
>>> # Get embeddings for index 1
>>> input = torch.LongTensor([1])
>>> embedding(input)
tensor([[ 4.0000,  5.1000,  6.3000]])

文件

取得 PyTorch 的完整開發人員文件

檢視文件

教學課程

取得初學者和進階開發人員的深入教學課程

檢視教學課程

資源

尋找開發資源並獲得問題解答

檢視資源