首页 > 解决方案 > 如何使用 keras 在输入特征子集之间共享权重

问题描述

在这个神经网络中,有 9 个输入特征:

  f1,f2,f3,f4,f5,f6,f7,f8,f9

我希望某些输入特征(但不是全部)在输入层和第一个隐藏层之间具有相同的权重。所有剩余的层将没有任何共享权重。

  f1,f2,f3 should share the same weights
  f4,f5,f6 should share the same weights
  f7 should not share weights with other features
  f8 should not share weights with other features
  f9 should not share weights with other features

我很确定我需要一维卷积,但不是在整个层上。我可能错过了它,但还没有看到这个用例记录在案。任何想法如何在 Keras 中做到这一点?

重新表述这个问题,在一组特征之间表达同等重要性的正确方法是什么?

在预测输出类别时,特征 ( f1, f2, f3) 具有同等重要性。在预测输出类别时,特征 ( f4, f5, f6) 也同样重要。

有三个可能的预测类别。特征f1f4是输出类 A 的证据。特征f2f5是 输出 的 证据classB. 特征f3f6是 输出 的 证据classC.

有没有办法通过在同等重要性特征之间共享参数来减少网络中的参数数量?

标签: pythonkerasneural-network

解决方案


相当于在密集层之前f1+f2+f3求和。f4+f5+f6

总和层的建议:

from keras.layers import Lambda
import keras.backend as K

def sumFeatures(x):
    f1_3 = x[:,:3]
    f4_6 = x[:,3:6]

    return K.concatenate(
        [
            K.sum(f1_3, axis=-1, keepdims=True),
            K.sum(f4_6, axis=-1, keepdims=True),
            x[:,6:]
        ], axis=-1)

顺序模型:

model.add(Lambda(sumFeatures))

功能型号:

outputTensor = Lambda(sumFeatures)(inputTensor)

推荐阅读