在 Keras 中实现后期融合

Dia*_*.95 5 python machine-learning deep-learning keras tensorflow

我正在研究带有图像和文本的多模式分类器。我已经成功开发了两个模型,一个是用于图像的 CNN,另一个是基于 BERT 的文本模型。两个模型的最后一层都是具有n 个单元和softmax激活的 Dense (其中 n 是类数)。Keras 提供了不同的合并层来组合这些模型的输出向量(https://keras.io/api/layers/merging_layers/),然后可以创建一个新的网络,但我的问题是:有没有更好的方法结合单个模型的决策?也许根据某种标准对向量内的值进行加权?目前我已经使用一个简单的串联层开发了我的模型,如下所示:

image_side = images_model(image_input)
text_side = text_model(text_input)
# Concatenation
merged = layers.Concatenate(name='Concatenation')([image_side, text_side])
merged = layers.Dense(128, activation = 'relu', name='Dense_128')(merged)
merged = layers.Dropout(0.2)(merged)
output = layers.Dense(nClasses, activation='softmax', name = "class")(merged)
Run Code Online (Sandbox Code Playgroud)

先感谢您!

Mar*_*ani 3

这里可以实现两个张量(模型输出)之间的加权平均值,其中权重可以自动学习。我还引入了权重总和必须为 1 的约束。为了实现这一点,我们必须简单地对权重应用 softmax。在下面的虚拟示例中,我将此方法与两个完全连接的分支的输出结合起来,但您可以在所有其他场景中管理它

这里是自定义层:

class WeightedAverage(Layer):

    def __init__(self, n_output):
        super(WeightedAverage, self).__init__()
        self.W = tf.Variable(initial_value=tf.random.uniform(shape=[1,1,n_output], minval=0, maxval=1),
            trainable=True) # (1,1,n_inputs)

    def call(self, inputs):

        # inputs is a list of tensor of shape [(n_batch, n_feat), ..., (n_batch, n_feat)]
        # expand last dim of each input passed [(n_batch, n_feat, 1), ..., (n_batch, n_feat, 1)]
        inputs = [tf.expand_dims(i, -1) for i in inputs]
        inputs = Concatenate(axis=-1)(inputs) # (n_batch, n_feat, n_inputs)
        weights = tf.nn.softmax(self.W, axis=-1) # (1,1,n_inputs)
        # weights sum up to one on last dim

        return tf.reduce_sum(weights*inputs, axis=-1) # (n_batch, n_feat)
Run Code Online (Sandbox Code Playgroud)

这是回归问题的完整示例:

inp1 = Input((100,))
inp2 = Input((100,))
x1 = Dense(32, activation='relu')(inp1)
x2 = Dense(32, activation='relu')(inp2)
x = [x1,x2]
W_Avg = WeightedAverage(n_output=len(x))(x)
out = Dense(1)(W_Avg)

m = Model([inp1,inp2], out)
m.compile('adam','mse')

n_sample = 1000
X1 = np.random.uniform(0,1, (n_sample,100))
X2 = np.random.uniform(0,1, (n_sample,100))
y = np.random.uniform(0,1, (n_sample,1))

m.fit([X1,X2], y, epochs=10)
Run Code Online (Sandbox Code Playgroud)

最后,您还可以通过以下方式可视化权重的值:

tf.nn.softmax(m.get_weights()[-3]).numpy()
Run Code Online (Sandbox Code Playgroud)

参考和其他示例:https ://towardsdatascience.com/neural-networks-ensemble-33f33bea7df3