快捷方式

torch.nn.functional.embedding_bag

torch.nn.functional.embedding_bag(input, weight, offsets=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, mode='mean', sparse=False, per_sample_weights=None, include_last_offset=False, padding_idx=None)[source][source]

計算 embeddings 的 bags 的總和、平均值或最大值。

計算過程不會實例化中間 embeddings。 請參閱 torch.nn.EmbeddingBag 以獲得更多詳細資訊。

注意

當在 CUDA 裝置上給定 tensors 時,此操作可能會產生非確定性的梯度。 有關更多資訊,請參閱 再現性 (Reproducibility)

參數
  • input (LongTensor) – 包含 embedding 矩陣索引 bags 的 Tensor

  • weight (Tensor) – Embedding 矩陣,其行數等於最大可能索引 + 1,而列數等於 embedding 大小

  • offsets (LongTensor, optional) – 僅當 input 為 1D 時使用。 offsets 決定 input 中每個 bag (序列) 的起始索引位置。

  • max_norm (float, optional) – 如果給定,則每個範數大於 max_norm 的 embedding 向量將被重新標準化為具有範數 max_norm。 注意:這會就地修改 weight

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

  • scale_grad_by_freq (bool, optional) – 如果給定,這將通過小批量中單字的頻率的倒數來縮放梯度。 預設值為 False。 注意:當 mode="max" 時,不支援此選項。

  • mode (str, optional) – "sum""mean""max"。 指定減少 bag 的方式。 預設值: "mean"

  • sparse (bool, optional) – 如果 True,則 w.r.t. weight 的梯度將為稀疏 tensor。 有關稀疏梯度的更多詳細資訊,請參閱 torch.nn.Embedding 下的 Notes。 注意:當 mode="max" 時,不支援此選項。

  • per_sample_weights (Tensor, optional) – 一個 float/double 權重的 tensor,如果為 None 則表示所有權重都應視為 1。 如果指定,則 per_sample_weights 必須與 input 具有完全相同的形狀,並且如果 offsets 不是 None,則將被視為具有相同的 offsets

  • include_last_offset (bool, optional) – 如果 True,則 offsets 的大小等於 bags 的數量 + 1。 最後一個元素是 input 的大小,或是最後一個 bag (序列) 的結束索引位置。

  • padding_idx (int, optional) – 如果指定,則在 padding_idx 處的條目不會對梯度做出貢獻; 因此,在訓練期間不會更新 padding_idx 處的 embedding 向量,即它保持為固定的「pad」。 請注意,padding_idx 處的 embedding 向量會從 reduction 中排除。

回傳類型

Tensor

形狀
  • input (LongTensor) 和 offsets (LongTensor, optional)

    • 如果 input 是形狀為 (B, N) 的 2D,則它將被視為 B 個 bags (序列),每個 bags (序列) 具有固定的長度 N,並且這將回傳 B 個以取決於 mode 的方式聚合的值。 在這種情況下,offsets 會被忽略且需要為 None

    • 如果 input 是形狀為 (N) 的 1D,則它將被視為多個 bags (序列) 的串聯。 offsets 需要是包含 input 中每個 bag 的起始索引位置的 1D tensor。 因此,對於形狀為 (B)offsetsinput 將被視為具有 B 個 bags。 空 bags (即長度為 0) 將具有由零填充的回傳向量。

  • weight (Tensor):模組的可學習權重,形狀為 (num_embeddings, embedding_dim)

  • per_sample_weights (Tensor,可選)。 與 input 具有相同的形狀。

  • output:聚合的 embedding 值,形狀為 (B, embedding_dim)

範例

>>> # an Embedding module containing 10 tensors of size 3
>>> embedding_matrix = torch.rand(10, 3)
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9])
>>> offsets = torch.tensor([0, 4])
>>> F.embedding_bag(input, embedding_matrix, offsets)
tensor([[ 0.3397,  0.3552,  0.5545],
        [ 0.5893,  0.4386,  0.5882]])

>>> # example with padding_idx
>>> embedding_matrix = torch.rand(10, 3)
>>> input = torch.tensor([2, 2, 2, 2, 4, 3, 2, 9])
>>> offsets = torch.tensor([0, 4])
>>> F.embedding_bag(input, embedding_matrix, offsets, padding_idx=2, mode='sum')
tensor([[ 0.0000,  0.0000,  0.0000],
        [-0.7082,  3.2145, -2.6251]])

文件

取得 PyTorch 的完整開發者文件

檢視文件

教學

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

檢視教學

資源

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

檢視資源