【问题标题】:Merge specific input coordinates in Keras合并 Keras 中的特定输入坐标
【发布时间】:2019-03-01 10:27:58
【问题描述】:

我有一个序列模型的大输入向量(1000 个特征)。该模型主要是一个密集的网络。 我知道特征 1-50 在坐标方面与特征 51-100 高度相关(1 与 51、2 与 52 等),我想利用这一点。

有没有办法在我现有的模型中添加一个层来反映这一点? (将输入 1 和 51 连接到神经元、2 和 52 等)

或者也许唯一的选择是将输入结构更改为 50 个张量(1x2)和一个包含 900 个特征的大向量? (我想避免这种情况,因为这意味着重写我的功能准备代码)

【问题讨论】:

    标签: python-3.x tensorflow keras deep-learning keras-layer


    【解决方案1】:

    我认为第一个密集层会发现这种关系,当然如果你正确定义和训练模型。但是,如果您想分别处理前 100 个特征,另一种方法是使用 Keras functional API 并定义两个输入层,一个用于前 100 个特征,另一个用于其余 900 个特征:

    input_100 = Input(shape=(100,))
    input_900 = Input(shape=(900,))
    

    现在您可以分别处理每一项。例如,您可以定义两个单独的 Dense 层连接到每个层,然后合并它们的输出:

    dense_100 = Dense(50, activation='relu')(input_100)
    dense_900 = Dense(200, activation='relu')(input_900)
    
    concat = concatenate([dense_100, dense_900])
    
    # define the rest of your model ...
    
    model = Model(inputs=[input_100, input_900], outputs=[the_outputs_of_model])
    

    当然,您需要单独输入输入层。为此,您可以轻松地对训练数据进行切片:

    model.fit([X_train[:,:100], X_train[:,100:]], y_train, ...)
    

    更新:如果您特别希望特征 1 和 51、2 和 52 等具有单独的神经元(至少,我无法评论它的效率没有对数据进行实验),您可以使用LocallyConnected1D 层与内核大小和没有。过滤器为 1(即,它与在每两个相关特征上应用单独的 Dense 层具有相同的行为):

    input_50_2 = Input(shape=(50,2))
    
    local_out = LocallyConnected1D(1, 1, activation='relu')(input_50_2)
    local_reshaped = Reshape((50,))(local_out)  # need this for merging since local_out has shape of (None, 50, 1)
    # or use the following:
    # local_reshaped = Flatten()(local_out)
    
    concat = concatenation([local_reshaped, dense_900])
    
    # define the rest of your model...
    
    X_train_50_2 = np.transpose(X_train[:,:100].reshape((2, 50)))
    
    model.fit([X_train_50_2, X_train[:,100:]], y_train, ...)
    

    【讨论】:

    • 这是一个不错的建议。唯一的问题是所有前 100 个输入都是“网格化的”。我希望输入 1 和 51 有一个单独的神经元,2 和 52 等。是否可以使用张量而不是平面输入到密集层来做到这一点?如果不是密集层,那么可能是一个简单的 2D 卷积层?
    • 或者更确切地说是LocallyConnected1D。
    • @Eran 我根据您的具体要求添加了更新。
    • @Eran 是的,绝对的。
    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2022-09-19
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多