使用FaceNet创建三重态损失模型时遇到问题

时间:2018-12-20 14:19:27

标签: python keras

我正在尝试使用FacenetModel实现三重态损失模型。我使用了Coursera作业中提供的Facenet实现。

每当编译模型时,都会出现此错误:

  

ValueError:没有为“ FaceRecoModel”提供数据。需要每个键中的数据:['FaceRecoModel','FaceRecoModel','FaceRecoModel']

我的代码:

loading

预先训练的Facenet模型摘要:

  

FRmodel.summary():https://codeshare.io/arxmev

     

my_model.summary():https://codeshare.io/arx3N6

1 个答案:

答案 0 :(得分:0)

在Coursera的论坛上找到了解决方案。这有点棘手。我必须使用Lambda在keras层包装器中添加三重损失的欧氏距离。根据文档:

  

将任意表达式包装为Layer对象。

新实施:

`

    def triplet_loss_v2(y_true, y_pred):
        positive, negative = y_pred[:,0,0], y_pred[:,1,0]
        margin = K.constant(0.2)
        loss = K.mean(K.maximum(K.constant(0), positive - negative + margin))
        return loss # shape = [1]

    def euclidean_distance(vects):
        x, y = vects   # shape = [batch_size, 2, 1]
        dist = K.sqrt(K.maximum(K.sum(K.square(x - y), axis=1, keepdims=True), K.epsilon()))
        return dist   # shape = [batch_size, 1]

    FRmodel = faceRecoModel(input_shape=(3, 96, 96))
    load_weights_from_FaceNet(FRmodel)

    for layer in FRmodel.layers[0: 80]:
        layer.trainable  =  False

    input_shape=(3, 96, 96)
    anchor = Input(shape=input_shape, name = 'anchor')
    anchorPositive = Input(shape=input_shape, name = 'anchorPositive')
    anchorNegative = Input(shape=input_shape, name = 'anchorNegative')

    anchorCode = FRmodel(anchor)
    anchorPosCode = FRmodel(anchorPositive)
    anchorNegCode = FRmodel(anchorNegative)

    positive_dist = Lambda(euclidean_distance, name='pos_dist')([anchorCode, anchorPosCode])
    negative_dist = Lambda(euclidean_distance, name='neg_dist')([anchorCode, anchorNegCode])
    stacked_dists = Lambda(lambda vects: K.stack(vects, axis=1), name='stacked_dists')([positive_dist, negative_dist]) # shape = [batch_size, 2, 1]

    tripletModel = Model([anchor, anchorPositive, anchorNegative], stacked_dists, name='triple_siamese')
    tripletModel.compile(optimizer = 'adadelta', loss = triplet_loss_v2, metrics = None)

    gen = batch_generator(64)
    tripletModel.fit_generator(gen, epochs=1,steps_per_epoch=5)`