Python keras 模块,applications() 实例源码

我们从Python开源项目中,提取了以下4个代码示例,用于说明如何使用keras.applications()

项目:emu    作者:mlosch    | 项目源码 | 文件源码
def _load_model_config(model_cfg, model_weights):
        if type(model_cfg) == str:
            if not os.path.exists(model_cfg):
                try:
                    class_ = getattr(applications, model_cfg)
                    return class_(weights=model_weights)
                except AttributeError:
                    available_mdls = [attr for attr in dir(applications) if callable(getattr(applications, attr))]
                    raise ValueError('Could not load pretrained model with key {}. '
                                     'Available models: {}'.format(model_cfg, ', '.join(available_mdls)))

            with open(model_cfg, 'r') as fileh:
                try:
                    return model_from_json(fileh)
                except ValueError:
                    pass

                try:
                    return model_from_yaml(fileh)
                except ValueError:
                    pass

            raise ValueError('Could not load model from configuration file {}. '
                             'Make sure the path is correct and the file format is yaml or json.'.format(model_cfg))
        elif type(model_cfg) == dict:
            return Model.from_config(model_cfg)
        elif type(model_cfg) == list:
            return Sequential.from_config(model_cfg)

        raise ValueError('Could not load model from configuration object of type {}.'.format(type(model_cfg)))
项目:kaggle_amazon    作者:asanakoy    | 项目源码 | 文件源码
def get_preprocess_input_fn(model_name):
    print 'get_preprocess_input_fn({})'.format(model_name)
    return getattr(keras.applications, model_name).preprocess_input
项目:face_detection    作者:PuchatekwSzortach    | 项目源码 | 文件源码
def get_pretrained_vgg_model(image_shape):
    """
    Builds a model based on pretrained VGG net
    :param image_shape: image shape
    :return: keras model
    """

    expected_image_shape = (64, 64, 3)

    if image_shape != expected_image_shape:

        message = "Input image is specified to be {}, but this model is designed to work with inputs of shape {}"\
            .format(image_shape, expected_image_shape)

        raise ValueError(message)

    input_layer = keras.layers.Input(shape=image_shape)

    x = keras.applications.VGG16(include_top=False, weights='imagenet')(input_layer)
    x = keras.layers.Convolution2D(1, 2, 2, activation='sigmoid', name='final_convolution')(x)
    x = keras.layers.Flatten()(x)

    model = keras.models.Model(input=input_layer, output=x)

    adam = keras.optimizers.Adam(lr=0.0001)
    model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['accuracy'])

    return model
项目:pencroft    作者:lukeyeager    | 项目源码 | 文件源码
def train(source, use_keras_loader=False, nb_worker=1, pickle_safe=False,
          use_resnet50=False):
    start_time = time.time()

    if use_keras_loader:
        preprocessor = keras.preprocessing.image.ImageDataGenerator()
        generator = preprocessor.flow_from_directory(
            source,
            target_size=(224, 224),
            color_mode='rgb',
        )
        count = generator.nb_sample
        num_classes = generator.nb_class
    else:
        loader = PencroftLoader(source)
        if nb_worker > 1:
            if pickle_safe:
                loader.loader.make_mp_safe()
            else:
                loader.loader.make_thread_safe()
        generator = loader.generator()
        count = len(loader)
        num_classes = loader.num_classes()

    if use_resnet50:
        pretrained_model = keras.applications.resnet50.ResNet50(
            input_shape=(224, 224, 3),
            include_top=False)
        x = pretrained_model.output
        x = keras.layers.Flatten()(x)
        x = keras.layers.Dense(num_classes)(x)
        model = keras.models.Model(input=pretrained_model.input,
                                   output=x)
    else:
        model = keras.models.Sequential([
            keras.layers.Flatten(input_shape=(224, 224, 3)),
            keras.layers.Dense(num_classes),
        ])

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

    model.fit_generator(
        generator, count, 1,
        nb_worker=nb_worker,
        pickle_safe=pickle_safe,
    )
    print('Finished in %f seconds.' % (time.time() - start_time,))