我有一个CNN的Keras功能模型。我正在尝试实现三重损失功能。我发现了一些有关谁使用“合并”执行此操作的帖子,现已弃用,但我无法像使用合并那样使用“连接”。
原始代码如下:
def triplet_loss(x):
anchor, positive, negative = x
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1)
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), 0.05)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss
def build_model(img_x, img_y):
input_shape = Input(shape=(img_x, img_y, 3))
c0 = Conv2D(32, kernel_size=(3, 3), strides=(1, 1), activation='relu') (input_shape)
m0 = MaxPooling2D(pool_size=(2, 2), strides=(2, 2)) (c0)
f = Flatten()(m0)
d1 = Dense(4024, activation='relu')(f)
d2 = Dense(512, activation='sigmoid')(d1)
anchor = Input(shape=(128, 254, 3))
positive = Input(shape=(128, 254, 3))
negative = Input(shape=(128, 254, 3))
reid_model = Model(inputs=[input_shape], outputs=[d2])
anchor_embed = reid_model(anchor)
positive_embed = reid_model(positive)
negative_embed = reid_model(negative)
loss = merge([anchor_embed, positive_embed, negative_embed],
mode=triplet_loss, output_shape=(1,))
model = Model(inputs=[anchor, positive, negative], outputs=loss)
model.compile(optimizer='Adam', loss='mean_absolute_error')
return model
我使用loss = merge([anchor_embed, positive_embed, negative_embed], mode=triplet_loss, output_shape=(1,))
作为将函数triplet_loss
的输出转换为keras层输出的一种方法(如https://codepad.co/snippet/F1uVDD5N中所建议)。函数concatenate
没有参数“ mode”。他有什么方法可以适应我的代码,以将损失函数的结果作为Keras层输出?
答案 0 :(得分:1)
我终于找到了一种方法,通过添加lambda层来计算triplet_loss
函数的值,从而保持代码的原始体系结构。
def triplet_loss(x):
anchor, positive, negative = x
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1)
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), 0.05)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss
def build_model(img_x, img_y):
input_shape = Input(shape=(img_x, img_y, 3))
c0 = Conv2D(32, kernel_size=(3, 3), strides=(1, 1), activation='relu')
(input_shape)
m0 = MaxPooling2D(pool_size=(2, 2), strides=(2, 2)) (c0)
f = Flatten()(m0)
d1 = Dense(4024, activation='relu')(f)
d2 = Dense(512, activation='sigmoid')(d1)
anchor = Input(shape=(128, 254, 3))
positive = Input(shape=(128, 254, 3))
negative = Input(shape=(128, 254, 3))
reid_model = Model(inputs=[input_shape], outputs=[d2])
anchor_embed = reid_model(anchor)
positive_embed = reid_model(positive)
negative_embed = reid_model(negative)
merged_output = concatenate([anchor_embed, positive_embed,
negative_embed])
loss = Lambda(triplet_loss, (1,))(merged_output)
model = Model(inputs=[anchor, positive, negative], outputs=loss)
model.compile(optimizer='Adam', loss='mse',
metrics=["mae"])
return model