【发布时间】:2021-01-12 13:30:45
【问题描述】:
我正在为这个 Kaggle 比赛开发一个基于三元组损失的模型。
简短说明 - 在本次比赛中,我们面临挑战,通过分析包含来自研究机构和公共贡献者的 25,000 多张图像的数据库,构建一种算法来识别图像中的个体鲸鱼。
https://www.kaggle.com/c/humpback-whale-identification?rvi=1
我决定使用连体网络架构并对其进行训练,以便为我提供编码,然后我可以使用这些编码来计算两张鲸鱼图片之间的距离。如果此距离低于特定阈值,则两张图片属于同一条鲸鱼,如果此距离大于此阈值,则它们不是同一条鲸鱼。
这是我使用的 Triplet 损失函数(从 Andrew 的深度学习专业中学习),但我还对编码进行了归一化,以使损失函数在不同模型中更易于解释(更容易确定边距和分割点)(如果有意义的话) .(首先,在没有标准化的情况下尝试了它,当它不起作用时,我尝试了标准化。)我也尝试过更改 alpha(边距)并将其从 0.2 更改为 0.6。
from tensorflow.nn import l2_normalize as norm_l2
def triplet_loss(y_true, y_pred, alpha = 0.3):
"""
Arguments:
y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
y_pred -- python list containing three objects:
anchor -- the encodings for the anchor images, of shape (None, 128)
positive -- the encodings for the positive images, of shape (None, 128)
negative -- the encodings for the negative images, of shape (None, 128)
Returns:
loss -- real number, value of the loss
"""
anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
anchor, positive, negative = norm_l2(anchor), norm_l2(positive), norm_l2(negative)
# Step 1: Compute the (encoding) distance between the anchor and the positive
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,positive)), axis = -1)
# Step 2: Compute the (encoding) distance between the anchor and the negative
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,negative)), axis = -1)
# Step 3: subtract the two previous distances and add alpha.
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), alpha)
# Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples.
loss = tf.reduce_sum(tf.maximum(basic_loss, 0.0))
return loss
这是我尝试过的模型架构之一的示例。到目前为止,我已经尝试过使用预训练的 Facenet、ResNet、DenseNet 和 Xception。我试过在每个中冻结不同数量的层。
R = tf.keras.applications.ResNet50(include_top=False, weights = 'imagenet', input_shape=(224,224,3))
lr = 0.0001
optimizer = Adam(learning_rate=lr)
R.compile(optimizer=optimizer, loss = triplet_loss)
for layer in R.layers[0:30]:
layer.trainable = False
em_Rmodel = Sequential([
R,
GlobalAveragePooling2D(),
#tf.keras.layers.GlobalMaxPooling2D(),
Dense(512, activation='relu'),
bn(),
Dense(256, activation = 'sigmoid'),
Dense(128, activation = 'sigmoid')
])
def make_tripletModel(model):
#I was manually changing the input shape to fit the default shape of pretrained networks
A = Input(shape = (224, 224, 3), name='anchor')
P = Input(shape = (224, 224, 3), name = 'anchorPositive')
N = Input(shape = (224, 224, 3), name = 'anchorNegative')
enc_A = model(A)
enc_P = model(P)
enc_N = model(N)
tripletModel = Model(inputs=[A, P, N], outputs=[enc_A, enc_P, enc_N])
return tripletModel
tripletModel = make_tripletModel(em_Rmodel)
我一直在使用半硬三元组进行训练,并且一直在适当地扩充数据以生成更多训练图像。
这是我用于训练的批处理生成器。 crop_batch 是一种裁剪图像以仅显示鲸鱼尾巴的函数,使用它可以识别鲸鱼。它使用 DenseNet 训练了 1000 多张带有鲸鱼尾巴的图像和围绕它的边界框。工作是否足够好。
def batch_generator_RN(batch_size = batch_size, ishape = (256, 256, 3), model_input_shape = (224, 224, 3)):
triplet_generator = get_triplets()
y_val = np.zeros((batch_size, 2, 1))
anchors = np.zeros((batch_size, ishape[0], ishape[1], ishape[2]))
positives = np.zeros((batch_size, ishape[0], ishape[1], ishape[2]))
negatives = np.zeros((batch_size, ishape[0], ishape[1], ishape[2]))
while True:
for i in range(batch_size):
anchors[i], positives[i], negatives[i] = next(triplet_generator)
anc = crop_batch(anchors, batch_size= batch_size, img_shape=model_input_shape)
pos = crop_batch(positives, batch_size= batch_size, img_shape=model_input_shape)
neg = crop_batch(negatives, batch_size= batch_size, img_shape=model_input_shape)
x_data = {'anchor': anc,
'anchorPositive': pos,
'anchorNegative': neg
}
yield (x_data, [y_val, y_val, y_val])
最后,总的来说,这就是我尝试训练这些模型的方式。我试过降低和提高学习率,batch_size = 16。
lr = 0.0001
optimizer = Adam(learning_rate=lr)
tripletModel.compile(optimizer = optimizer, loss = triplet_loss)
es = EarlyStopping(monitor='loss', patience=20, min_delta=0.05, restore_best_weights=True)
#mc = ModelCheckpoint('Rmodel.h5', monitor='loss', save_best_only=True, save_weights_only=True)
rlr = ReduceLROnPlateau(monitor='loss',min_delta=0.05,factor = 0.1,patience = 5, verbose = 1, min_lr = 0)
gen = batch_generator(batch_size)
tripletModel.fit(gen, steps_per_epoch=64, epochs = 40, callbacks=[es, rlr])
所以在训练了所有这些模型之后,在某些模型中,triplet loss 确实会下降一段时间,但随后会趋于平稳,基本上没有学到任何有意义的东西(这基本上意味着仅通过查看两个嵌入之间的距离我无法计算如果它们是同一条鲸鱼,就出来。)。在其他模型中,在第一个或第二个 epoch 之后,权重会立即收敛,根本不会改变,也不会学到任何东西。
我已经尝试了非常广泛的学习率,我很确定这不是问题。
请告诉我是否应该添加所有代码文件以便您更好地理解问题。我还没有这样做的原因是因为我还没有清理它,但如果需要,我很乐意这样做。谢谢。
【问题讨论】:
标签: tensorflow keras deep-learning face-recognition conv-neural-network