快捷方式

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]

一個簡單的查詢表,用於儲存固定詞典大小的 embedding(詞嵌入)。

此模組常用於儲存詞 embedding(詞嵌入),並使用索引檢索它們。模組的輸入是一個索引列表,輸出是相應的詞 embedding(詞嵌入)。

引數
  • num_embeddings (int) – embedding(詞嵌入)字典的大小

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

  • padding_idx (int, 可選) – 如果指定,padding_idx 處的條目不參與梯度計算;因此,padding_idx 處的 embedding(詞嵌入)向量在訓練期間不會更新,即它保持為固定的“填充”。對於新構造的 Embedding,padding_idx 處的 embedding(詞嵌入)向量預設為全零,但可以更新為其他值用作填充向量。

  • max_norm (float, 可選) – 如果給定,範數大於 max_norm 的每個 embedding(詞嵌入)向量將被重新歸一化為範數 max_norm。

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

  • scale_grad_by_freq (bool, 可選) – 如果給定,這將按 mini-batch 中單詞頻率的倒數縮放梯度。預設為 False

  • sparse (bool, 可選) – 如果為 True,關於 weight 矩陣的梯度將是一個稀疏張量。有關稀疏梯度的更多詳細資訊,請參閱注意部分。

變數

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

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

  • 輸出: (,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)[source][source]

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

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

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

  • padding_idx (int, 可選) – 如果指定,padding_idx 處的條目不參與梯度計算;因此,padding_idx 處的 embedding(詞嵌入)向量在訓練期間不會更新,即它保持為固定的“填充”。

  • max_norm (float, 可選) – 參見模組初始化文件。

  • norm_type (float, 可選) – 參見模組初始化文件。預設為 2

  • scale_grad_by_freq (bool, 可選) – 參見模組初始化文件。預設為 False

  • sparse (bool, 可選) – 參見模組初始化文件。

示例

>>> # 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 開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源