如何在Python中使用预训练的CNN模型

时间:2019-11-16 11:51:45

标签: python matlab tensorflow keras deep-learning

因此,基本上我正在尝试使用预先训练的VGG CNN模型。我已经从以下网站下载了模型:

http://www.vlfeat.org/matconvnet/pretrained/

给了我一个image-vgg-m-2048.mat文件。但是该指南为我提供了如何使用MatconvNet库在Matlab中使用它。我想在python中实现相同的功能。我正在为此使用Keras。

我写了以下代码:

from keras.applications.vgg16 import VGG16
model = VGG16(weights = "imagenet")

当我尝试放置weights = "image-vgg-m-2408.mat"时 它给了我一个例外。

有人可以帮我吗,如何使用mat文件模型,python中的权重以使用此预先训练的模型?

1 个答案:

答案 0 :(得分:0)

基本上,如果您指定了任何weights而不是imagenet,它将仅使用keras model.load_weights来加载它,我猜image-vgg-m-2408.mat不是一个有效的keras可以直接在这里加载。

https://github.com/keras-team/keras-applications/blob/master/keras_applications/vgg16.py#L197

if weights == 'imagenet':
    if include_top:
        weights_path = keras_utils.get_file(
            'vgg16_weights_tf_dim_ordering_tf_kernels.h5',
            WEIGHTS_PATH,
            cache_subdir='models',
            file_hash='64373286793e3c8b2b4e3219cbf3544b')
    else:
        weights_path = keras_utils.get_file(
            'vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
            WEIGHTS_PATH_NO_TOP,
            cache_subdir='models',
            file_hash='6d6bbae143d832006294945121d1f1fc')
    model.load_weights(weights_path)
    if backend.backend() == 'theano':
        keras_utils.convert_all_kernels_in_model(model)
elif weights is not None:
    model.load_weights(weights)

默认情况下,keras将使用imagenet作为默认权重,并且输出类号将为1000。但是,如果该模型没有其他有效权重,则仍可以通过一种可能的方式利用imagenet权重: >

  • 您可以将include_top设置为False,并直接使用VGG16 Conv输出(没有最后的3个FC层)。
model = VGG16(include_top=False, weights = "imagenet")

https://github.com/keras-team/keras-applications/blob/master/keras_applications/vgg16.py#L43

    include_top: whether to include the 3 fully-connected
        layers at the top of the network.
    weights: one of `None` (random initialization),
          'imagenet' (pre-training on ImageNet),
          or the path to the weights file to be loaded.
    classes: optional number of classes to classify images
        into, only to be specified if `include_top` is True, and
        if no `weights` argument is specified.