首页 文章

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

提问于
浏览
8

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

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

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

Here is a little image that should show the network architecture that I would like to create, where each input-element is encoded using a 3D-Embedding

我怎样才能做到这一点?

1 回答

  • 10
    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....
    

    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)
    

    这是你在找什么?

相关问题