簡體   English   中英

了解 Keras MNIST 連體網絡並將其調整為三元組

[英]Understanding the Keras MNIST Siamese Network and adapting it for triples

我目前正在使用 Keras 在 Python 中調整這個連體網絡。 但是,我目前不明白損失是如何工作的(不是 function 本身,而是哪些參數在哪里傳遞)

好的,現在一步一步我認為這是如何工作的:

distance = Lambda(euclidean_distance,
              output_shape=eucl_dist_output_shape)([processed_a, processed_b])

這是兩個單獨網絡的輸出合並的行,自定義層應用以下功能:

def euclidean_distance(vects):
    x, y = vects
    sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
    return K.sqrt(K.maximum(sum_square, K.epsilon()))


def eucl_dist_output_shape(shapes):
    shape1, shape2 = shapes
    return (shape1[0], 1)

因此,當該層的輸入為 (128, 128) 時,output 將為 (128, 1)。 在最后一步中,損失計算如下:

def contrastive_loss(y_true, y_pred):
    '''Contrastive loss from Hadsell-et-al.'06
    http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
    '''
    margin = 1
    square_pred = K.square(y_pred)
    margin_square = K.square(K.maximum(margin - y_pred, 0))
    return K.mean(y_true * square_pred + (1 - y_true) * margin_square)

在這里,預測的 128D 向量與 128D 地面實況向量進行比較。

現在我將 Lambda 層更改為:

distance = Lambda(euclidean_distance,
                  output_shape=eucl_dist_output_shape)([processed_a, processed_b, processed_c])

所以我現在有三個具有以下適應功能的網絡(應該將三個輸出組合到一個 output,形狀為 (128, 3)):

def euclidean_distance(vects):
    return vects


def eucl_dist_output_shape(shapes):
    shape1, shape2, shape3 = shapes
    return (shape1, shape2, shape3)

然后是新的損失function:

def loss_desc_triplet(vects, margin=5):
    """Triplet loss.
    """
    d1, d2, d3 = vects
    d_pos = K.sqrt(K.sum(K.square(d1 - d2), axis=1))
    pair_dist_1_to_3 = K.sqrt(K.sum(K.square(d1 - d3), axis=1))
    d_neg = pair_dist_1_to_3

    return Activation.relu(d_pos - d_neg + margin)

但現在我得到這個錯誤:

文件“DeepLearningWithAugmentationWithTriplets.py”,第 233 行,在 output_shape=eucl_dist_output_shape)([processed_a, processes_b, processed_c])

文件“lib/python3.7/site-packages/keras/engine/base_layer.py”,第 497 行,調用參數=user_kwargs)

文件“lib/python3.7/site-packages/keras/engine/base_layer.py”,第 565 行,在 _add_inbound_node output_tensors[i]._keras_shape = output_shapes[i]

IndexError:列表索引超出范圍

但我不確定是什么原因造成的。

我通過連接輸出解決了這個問題:

merged_vector = concatenate([processed_a, processed_b, processed_c], axis=-1, name='merged_layer')

然后在我的損失 function 中分解向量:

d1 = y_pred[:,0:128]
d2 = y_pred[:,128:256]
d3 = y_pred[:,256:384]

不過,我不確定這是否是最好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM