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

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:整数。密集 Embedding 的维度。
  • 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)。要使用的初始 Embedding 值。
  • lora_rank:可选整数。如果设置,则层的正向传播将使用提供的秩实现 LoRA(低秩适配)。LoRA 将层的 Embedding 矩阵设置为不可训练,并将其替换为在原始矩阵上的一个增量,该增量通过乘以两个低秩可训练矩阵获得。这对于降低微调大型 Embedding 层时的计算成本非常有用。您还可以通过调用 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)