如何通过自己的数据集进行resnet50模型的转移学习?

时间:2020-02-18 04:34:11

标签: python tensorflow machine-learning keras deep-learning

我正在尝试使用具有vggface权重的keras和resnet50模型构建人脸验证系统。我尝试通过以下步骤来实现此目的:

  • 给定两个图像,我首先使用mtcnn作为嵌入物找出人脸
  • 然后,我计算两个向量嵌入之间的余弦距离。距离从0到1开始。...(请注意 两个相同的面孔的距离越小)

使用resnet50的预训练模型,我得到了很好的结果。但是由于该模型主要是根据欧洲数据进行训练的,所以我想对印度次要内容进行面部验证,因此我不能依靠它。我想在我自己的数据集上训练它们。我有10000个班级,每个班级包含2张图片。通过图像增强,我可以从这两个图像中为每个班级创建10-15幅图像。

这是我用于培训的示例代码

base_model = VGGFace(model='resnet50',include_top=False,input_shape=(224, 224, 3))
base_model.layers.pop()
base_model.summary()
for layer in base_model.layers:
    layer.trainable = False


y=base_model.input
x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1024,activation='relu')(x) #we add dense layers so that the model can learn more complex functions and classify for better results.
x=Dense(1024,activation='relu')(x) #dense layer 2
x=Dense(512,activation='relu')(x) #dense layer 3
preds=Dense(8322,activation='softmax')(x) #final layer with softmax activation

model=Model(inputs=base_model.input,outputs=preds)


model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])

model.summary()
train_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies

train_generator=train_datagen.flow_from_directory('/Users/imac/Desktop/Fayed/Facematching/testenv/facenet/Dataset/train', # this is where you specify the path to the main data folder
                                                 target_size=(224,224),
                                                 color_mode='rgb',
                                                 batch_size=32,
                                                 class_mode='categorical',
                                                 shuffle=True)
step_size_train=train_generator.n/train_generator.batch_size


model.fit_generator(generator=train_generator,
                   steps_per_epoch=step_size_train,
                   epochs=10)
model.save('directory')

就所关心的代码而言,我了解的是我禁用了最后一层,然后添加了4层训练它们并将它们存储在分区中。

i然后使用

加载模型
model=load_model('directory of my saved model')
model.summary()
yhat = model.predict(samples)
我预测两个图像的嵌入,然后计算余弦距离。但是问题在于,我训练有素的模型会使预测变得更糟。对于同一个人的两个图像,预训练模型给出的距离为0.3,而我的训练模型给出的距离为1.0。尽管在训练过程中,损失随每个时期的减少而降低,但准确性却在提高,但这并不能反映在我的预测输出中。我想增加预训练模型的预测结果。

如何使用自己的数据实现?

NB:我在机器学习方面相对较新,对模型层了解不多

1 个答案:

答案 0 :(得分:1)

我建议对这么多的班级使用三联或暹罗。使用MTCNN提取人脸,然后使用facenet体系结构生成512维嵌入矢量,然后使用TSNE绘图将其可视化。每个面孔都会被分配一个小的嵌入簇。通过此链接,Keras可以生成人脸嵌入:Link

然后,在数据集中尝试使用Triplets半硬和硬损失将它们聚类为10000个类。这可能会有所帮助。浏览有关三重音损失的详细博客:Triplets。通过某些存储库的代码:Code