Keras - 如何为每个Input-Neuron构建共享的Embedding()层

Ano*_*der 8 python deep-learning keras tensorflow

我想在keras中创建一个深度神经网络,其中输入层的每个元素在被馈送到更深层之前使用相同的共享嵌入()层进行"编码".

每个输入都是一个定义对象类型的数字,网络应该学习一个嵌入,它封装了"这个对象是什么"的内部表示.

因此,如果输入层具有X维度,并且嵌入具有Y维度,则第一隐藏层应该由X*Y神经元(每个嵌入的输入神经元)组成.

这是一个小图像,应该显示我想要创建的网络架构,其中每个输入元素使用3D嵌入进行编码

我怎样才能做到这一点?

Nas*_*Ben 12

from keras.layers import Input, Embedding

first_input = Input(shape = (your_shape_tuple) )
second_input = Input(shape = (your_shape_tuple) )
...

embedding_layer = Embedding(embedding_size)

first_input_encoded = embedding_layer(first_input)
second_input_encoded = embedding_layer(second_input)
...

Rest of the model....
Run Code Online (Sandbox Code Playgroud)

emnedding_layer将具有共享权重.如果您有大量输入,则可以以图层列表的形式执行此操作.

如果您想要的是改变输入的张量,那么这样做的方法是:

from keras.layers import Input, Embedding

# If your inputs are all fed in one numpy array :
input_layer = Input(shape = (num_input_indices,) )

# the output of this layer will be a 2D tensor of shape (num_input_indices, embedding_size)
embedded_input = Embedding(embedding_size)(input_layer)
Run Code Online (Sandbox Code Playgroud)

这是你在找什么?