Keras 3 API 文档 / 层 API / 核心层 / Embedding 层

嵌入层

[源代码]

Embedding

keras.layers.Embedding(
    input_dim,
    output_dim,
    embeddings_initializer="uniform",
    embeddings_regularizer=None,
    embeddings_constraint=None,
    mask_zero=False,
    weights=None,
    lora_rank=None,
    lora_alpha=None,
    **kwargs
)

将非负整数(索引)转换为固定大小的密集向量。

例如:[[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]

此层只能用于固定范围内的非负整数输入。

示例

>>> model = keras.Sequential()
>>> model.add(keras.layers.Embedding(1000, 64))
>>> # The model will take as input an integer matrix of size (batch,
>>> # input_length), and the largest integer (i.e. word index) in the input
>>> # should be no larger than 999 (vocabulary size).
>>> # Now model.output_shape is (None, 10, 64), where `None` is the batch
>>> # dimension.
>>> input_array = np.random.randint(1000, size=(32, 10))
>>> model.compile('rmsprop', 'mse')
>>> output_array = model.predict(input_array)
>>> print(output_array.shape)
(32, 10, 64)

参数

  • input_dim:整数。词汇表的大小,即最大整数索引 + 1。
  • output_dim:整数。稠密嵌入的维度。
  • embeddings_initializerembeddings 矩阵的初始化器(参见 keras.initializers)。
  • embeddings_regularizer:应用于 embeddings 矩阵的正则化函数(参见 keras.regularizers)。
  • embeddings_constraint:应用于 embeddings 矩阵的约束函数(参见 keras.constraints)。
  • mask_zero: 布尔值,输入值 0 是否为特殊“填充”值,应被屏蔽掉。在使用可能接受可变长度输入的循环层时,这很有用。如果设置为 True,则模型中所有后续层都需要支持掩码,否则将引发异常。如果 mask_zero 被设置为 True,因此,词汇表中无法使用索引 0(input_dim 应等于词汇表大小 + 1)。
  • weights: 可选浮点数矩阵,大小为 (input_dim, output_dim)。用于初始嵌入值的矩阵。
  • lora_rank: 可选整数。如果设置,该层的正向传播将实现具有给定秩的 LoRA(低秩自适应)。LoRA 将该层的嵌入矩阵设置为不可训练,并用原始矩阵上的一个增量替换它,该增量通过乘以两个较低秩的可训练矩阵获得。这有助于降低微调大型嵌入层的计算成本。您也可以通过调用 layer.enable_lora(rank) 来在现有的 Embedding 层上启用 LoRA。
  • lora_alpha: 可选整数。如果设置,此参数会在正向传播期间缩放低秩自适应增量(通过乘以两个较低秩的可训练矩阵计算得出)。增量将乘以 lora_alpha / lora_rank,这使您可以独立于 lora_rank 微调 LoRA 调整的强度。

输入形状

2D 张量,形状为:(batch_size, input_length)

输出形状

3D 张量,形状为:(batch_size, input_length, output_dim)