使用预训练模型

    应用程序

    Keras应用程序是深度学习模型,可与预先训练的权重一起使用。这些模型可用于预测、特征提取和微调。

    权重在实例化模型时自动下载。它们储存在~ / .keras /模型/

    以下图像分类模型(在ImageNet上训练权重)是可用的:

    所有这些架构都与所有后端(TensorFlow、Theano和CNTK)兼容,在实例化模型时,将根据Keras配置文件中设置的图像数据格式来构建~ / .keras / keras.json.例如,如果你设置了image_data_format = channels_last,那么从这个存储库中加载的任何模型都将根据TensorFlow数据格式约定“高-宽-深”来构建。

    • Keras < 2.2.0Xception模型只适用于TensorFlow,因为它依赖于SeparableConvolution层。
    • Keras < 2.1.5MobileNet模型只适用于TensorFlow,因为它依赖于DepthwiseConvolution层。

    用法示例

    用ResNet50分类ImageNet类

    #实例化模型模型< -application_resnet50重量=“imagenet”#加载图像img_path < -“elephant.jpg”img < -image_load(img_pathtarget_size =c224224))x < -image_to_array(img)#确保我们有一个4d张量,在批处理维度中有单个元素,#对输入进行预处理,使用resnet50进行预测x < -array_reshape(x,c1昏暗的(x)))x < -imagenet_preprocess_input(x)#做出预测,然后解码并打印出来仅仅< -模型% > %预测(x)imagenet_decode_predictions(仅仅,顶级=3.) [[1]]
    class_name class_description score 1 n02504013印度大象0.90117526 2 n01871265象牙0.08774310 3 n02504458非洲大象0.01046011

    利用VGG16提取特征

    模型< -application_vgg16重量=“imagenet”include_top =img_path < -“elephant.jpg”img < -image_load(img_pathtarget_size =c224224))x < -image_to_array(img)x < -array_reshape(x,c1昏暗的(x)))x < -imagenet_preprocess_input(x)< -特点模型% > %预测(x)

    使用VGG19从任意中间层提取特征

    base_model < -application_vgg19重量=“imagenet”模型< -keras_model输入=base_model输入,输出=get_layer(base_model“block4_pool”输出)img_path < -“elephant.jpg”img < -image_load(img_pathtarget_size =c224224))x < -image_to_array(img)x < -array_reshape(x,c1昏暗的(x)))x < -imagenet_preprocess_input(x)block4_pool_features < -模型% > %预测(x)

    在一组新的类上对InceptionV3进行微调

    #创建基础预训练模型base_model < -application_inception_v3重量=“imagenet”include_top =#添加我们的自定义图层预测< -base_model输出% > %layer_global_average_pooling_2d()% > %layer_dense单位=1024激活=“relu”% > %layer_dense单位=200激活=“softmax”#这是我们要训练的模型模型< -keras_model输入=base_model输入,输出=预测)# first:只训练顶层(随机初始化)#即冻结所有卷积的InceptionV3层freeze_weights(base_model)#编译模型(应该在将图层设置为不可训练后进行)模型% > %编译优化器=“rmsprop”损失=“categorical_crossentropy”#在新数据上训练模型几个epoch模型% > %fit_generator(…)#在这一点上,顶层训练得很好,我们可以开始微调#卷积层从初始V3。我们将冻结底部的N层#和训练剩余的顶层。#让我们可视化图层名称和图层索引,看看有多少层#我们应该冻结:层< -base_model(我1长度(层)(我,层[[我]]的名字,\ n#我们选择训练前2个初始块,即我们将冻结#前172层,并解冻其余的:freeze_weights(base_model从=1=172unfreeze_weights(base_model从=173为了使这些修改生效,我们需要重新编译模型#我们使用学习率低的SGD模型% > %编译优化器=optimizer_sgdlr =0.0001动量=0.9),损失=“categorical_crossentropy”#我们再次训练我们的模型(这次微调前2个初始块#顶部密集的层模型% > %fit_generator(…)

    在自定义输入张量上构建InceptionV3

    #这也可以是一个不同的Keras模型或层的输出input_tensor < -layer_input形状=c2242243.))模型< -application_inception_V3input_tensor =input_tensor,重量=“imagenet”include_top =真正的

    附加的例子

    VGG16模型是深的梦想Keras示例脚本。