Keras 中的嵌入层如何处理浮点输入值?

Use*_*er1 5 python keras tensorflow keras-layer tf.keras

x(64, 1)使用 随机创建的维度向量tf.random.uniform((BATCH_SIZE, 1)),其中BATCH_SIZE = 64.

随机初始化如下所示:

tf.Tensor(
[[0.76922464]
 [0.7928164 ]
 [0.91224647]
 [0.41210544]
 [0.33040464]
 [0.20977008]
 [0.96211743]
 [0.59516513]
 [0.67317   ]
 [0.7600033 ]
 [0.93105805]
 [0.55348516]
 [0.50683343]
 [0.7563635 ]
 [0.06255531]
 [0.93398154]
 [0.5622641 ]
 [0.9913852 ]
 [0.3019762 ]
 [0.519048  ]
 [0.57998526]
 [0.21162748]
 [0.9783536 ]
 [0.38307965]
 [0.6527189 ]
 [0.8094288 ]
 [0.97980523]
 [0.5955998 ]
 [0.7002481 ]
 [0.6879872 ]
 [0.50365186]
 [0.57166266]
 [0.97805905]
 [0.458856  ]
 [0.3485204 ]
 [0.29394794]
 [0.19313121]
 [0.29782188]
 [0.45194447]
 [0.49442303]
 [0.04192603]
 [0.26818407]
 [0.822567  ]
 [0.8573874 ]
 [0.15510845]
 [0.76052403]
 [0.4066763 ]
 [0.17861617]
 [0.458804  ]
 [0.25463438]
 [0.89405084]
 [0.854866  ]
 [0.9855745 ]
 [0.04673469]
 [0.6193329 ]
 [0.9060414 ]
 [0.17602026]
 [0.20119262]
 [0.08522642]
 [0.7849103 ]
 [0.34081244]
 [0.2556857 ]
 [0.75679326]
 [0.635311  ]], shape=(64, 1), dtype=float32)
Run Code Online (Sandbox Code Playgroud)

嵌入层定义为self.embedding = tf.keras.layers.Embedding(4934, 256)

x上面创建的 ,通过该嵌入层传递,如下所示:

x = self.embedding(x)

x这种嵌入产生的结果具有尺寸(64, 1, 256)。因此 64 个浮点值中的每一个x都有 256 维向量表示。

我的问题是: x最初是一个随机生成的浮点向量,每个向量的长度为1

根据定义,我将嵌入层理解为从单词到索引的映射,并且索引的向量表示的长度等于“嵌入维度”,在本例中为 256。因此映射到索引的单词也具有相同的向量表示。

x在我们的示例中只是随机浮点值的向量。嵌入层如何为这些浮点值提供 256 维向量表示?此列表中的任何浮点值都不代表单词。为什么它应该有嵌入?

它位于下面图像中的第 36 行(链接到代码页:Google colab 代码位置

代码图像

tod*_*day 2

将浮点值传递给Embedding图层不会引发错误,因为图层实现会自动将输入转换为整数(如果它不是整数)。您可以通过查看源代码中的相关部分来确认这种情况:

def call(self, inputs):
    dtype = K.dtype(inputs)
    if dtype != 'int32' and dtype != 'int64':
      inputs = math_ops.cast(inputs, 'int32')
Run Code Online (Sandbox Code Playgroud)