Python keras.applications() Examples

The following are code examples for showing how to use keras.applications(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: perceptron-benchmark   Author: advboxes   File: densenet.py    Apache License 2.0 6 votes vote down vote up
def download_imagenet(self):
        """ Download pre-trained weights for the specified backbone name.
        This name is in the format {backbone}_weights_tf_dim_ordering_tf_
        kernels_notop
        where backbone is the densenet + number of layers (e.g. densenet121).
        For more info check the explanation from the keras densenet script 
        itself:
            https://github.com/keras-team/keras/blob/master/keras/applications
            /densenet.py
        """
        origin = 'https://github.com/fchollet/deep-learning-models/releases/'\
            'download/v0.8/'
        file_name = '{}_weights_tf_dim_ordering_tf_kernels_notop.h5'

        # load weights
        if keras.backend.image_data_format() == 'channels_first':
            raise ValueError(
                'Weights for "channels_first" format are not available.')

        weights_url = origin + file_name.format(self.backbone)
        return get_file(file_name.format(self.backbone),
                        weights_url, cache_subdir='models') 
Example 2
Project: OrgaQuant   Author: TKassis   File: densenet.py    MIT License 6 votes vote down vote up
def download_imagenet(self):
        """ Download pre-trained weights for the specified backbone name.
        This name is in the format {backbone}_weights_tf_dim_ordering_tf_kernels_notop
        where backbone is the densenet + number of layers (e.g. densenet121).
        For more info check the explanation from the keras densenet script itself:
            https://github.com/keras-team/keras/blob/master/keras/applications/densenet.py
        """
        origin    = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.8/'
        file_name = '{}_weights_tf_dim_ordering_tf_kernels_notop.h5'

        # load weights
        if keras.backend.image_data_format() == 'channels_first':
            raise ValueError('Weights for "channels_first" format are not available.')

        weights_url = origin + file_name.format(self.backbone)
        return get_file(file_name.format(self.backbone), weights_url, cache_subdir='models') 
Example 3
Project: lacmus-web-api   Author: lacmus-foundation   File: densenet.py    GNU General Public License v3.0 6 votes vote down vote up
def download_imagenet(self):
        """ Download pre-trained weights for the specified backbone name.
        This name is in the format {backbone}_weights_tf_dim_ordering_tf_kernels_notop
        where backbone is the densenet + number of layers (e.g. densenet121).
        For more info check the explanation from the keras densenet script itself:
            https://github.com/keras-team/keras/blob/master/keras/applications/densenet.py
        """
        origin    = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.8/'
        file_name = '{}_weights_tf_dim_ordering_tf_kernels_notop.h5'

        # load weights
        if keras.backend.image_data_format() == 'channels_first':
            raise ValueError('Weights for "channels_first" format are not available.')

        weights_url = origin + file_name.format(self.backbone)
        return get_file(file_name.format(self.backbone), weights_url, cache_subdir='models') 
Example 4
Project: keras-retinanet   Author: fizyr   File: densenet.py    Apache License 2.0 6 votes vote down vote up
def download_imagenet(self):
        """ Download pre-trained weights for the specified backbone name.
        This name is in the format {backbone}_weights_tf_dim_ordering_tf_kernels_notop
        where backbone is the densenet + number of layers (e.g. densenet121).
        For more info check the explanation from the keras densenet script itself:
            https://github.com/keras-team/keras/blob/master/keras/applications/densenet.py
        """
        origin    = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.8/'
        file_name = '{}_weights_tf_dim_ordering_tf_kernels_notop.h5'

        # load weights
        if keras.backend.image_data_format() == 'channels_first':
            raise ValueError('Weights for "channels_first" format are not available.')

        weights_url = origin + file_name.format(self.backbone)
        return get_file(file_name.format(self.backbone), weights_url, cache_subdir='models') 
Example 5
Project: Maix-LogoClassifier   Author: andriyadi   File: mbnet_keras.py    MIT License 5 votes vote down vote up
def prepare_test_image(file):
    img_path = 'dataset/test/'
    img = image.load_img(img_path + file, target_size=(IMAGE_WIDTH, IMAGE_HEIGHT))
    img_array = image.img_to_array(img)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    return keras.applications.mobilenet.preprocess_input(img_array_expanded_dims) 
Example 6
Project: Maix-LogoClassifier   Author: andriyadi   File: test.py    MIT License 5 votes vote down vote up
def prepare_test_image(file):
    img_path = 'dataset/test/'
    img = image.load_img(img_path + file, target_size=(224, 224))
    img_array = image.img_to_array(img)
    image.save_img(img_path + file, img_array)
    # print("array shape:", img_array.shape)
    img_array_expanded_dims = np.expand_dims(img_array, axis=0)
    return keras.applications.mobilenet.preprocess_input(img_array_expanded_dims) 
Example 7
Project: emu   Author: mlosch   File: keras.py    MIT License 5 votes vote down vote up
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))) 
Example 8
Project: webapp-classify-MobileNet-ResNet   Author: kenNicholaus   File: classify.py    GNU General Public License v3.0 5 votes vote down vote up
def model_predict(img_path, model):
    img = image.load_img(img_path, target_size=(224, 224))

    # Preprocessing the image
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = keras.applications.mobilenet.preprocess_input(x)

    preds = model.predict(x)
    return preds 
Example 9
Project: webapp-classify-MobileNet-ResNet   Author: kenNicholaus   File: classify.py    GNU General Public License v3.0 5 votes vote down vote up
def model_predict1(img_path, model1):
    img = image.load_img(img_path, target_size=(224, 224))

    # Preprocessing the image
    y = image.img_to_array(img)
    #y = np.true_divide(y, 255)
    y = np.expand_dims(y, axis=0)

    # Be careful how your trained model deals with the input
    # otherwise, it won't make correct prediction!
    y = keras.applications.imagenet_utils.preprocess_input(y, mode='caffe' )

    preds1 = model.predict(y)
    return preds1 
Example 10
Project: transparent_latent_gan   Author: SummitKwan   File: cnn_face_attr_celeba.py    MIT License 5 votes vote down vote up
def create_cnn_model(size_output=None, tf_print=False):
    """
    create keras model with convolution layers of MobileNet and added fully connected layers on to top
    :param size_output: number of nodes in the output layer
    :param tf_print:    True/False to print
    :return: keras model object
    """

    if size_output is None:
        # get number of attrubutes, needed for defining the final layer size of network
        df_attr = pd.read_csv(path_celeba_att, sep='\s+', header=1, index_col=0)
        size_output = df_attr.shape[1]

    # Load the convolutional layers of pretrained model: mobilenet
    base_model = keras.applications.mobilenet.MobileNet(include_top=False, input_shape=(128,128,3),
                                                          alpha=1, depth_multiplier=1,
                                                          dropout=0.001, weights="imagenet",
                                                          input_tensor=None, pooling=None)

    # add fully connected layers
    fc0 = base_model.output
    fc0_pool = layers.GlobalAveragePooling2D(data_format='channels_last', name='fc0_pool')(fc0)
    fc1 = layers.Dense(256, activation='relu', name='fc1_dense')(fc0_pool)
    fc2 = layers.Dense(size_output, activation='tanh', name='fc2_dense')(fc1)

    model = keras.models.Model(inputs=base_model.input, outputs=fc2)

    # freeze the early layers
    for layer in base_model.layers:
        layer.trainable = False

    model.compile(optimizer='sgd', loss='mean_squared_error')

    if tf_print:
        print('use convolution layers of MobileNet, add fully connected layers')
        print(model.summary())

    return model 
Example 11
Project: panotti   Author: drscotthawley   File: models.py    MIT License 5 votes vote down vote up
def imageModels(X, nb_classes, weights=None):
    # Note these all require exactly 3 input channels.
    from keras.applications import Xception, VGG16
    from keras.applications.inception_v3 import InceptionV3
    from keras.applications.nasnet import NASNetLarge, NASNetMobile
    from keras.applications.inception_resnet_v2 import InceptionResNetV2
    from keras.utils.generic_utils import CustomObjectScope
    from keras.applications.mobilenet import MobileNet, DepthwiseConv2D

    weights = 'imagenet'    # Could resize images to, e.g. 224 x 224 and then use weights='imagenet'.
                            # Need to use --mels=224 --dur=2.6s with preprocess_data.py   and --tile with train_network.

    input_shape = X.shape[1:]
    print("input_shape = ",input_shape)
    if False and (3 != input_shape[0]):   # then we're going to add a front end that gives us 3 channels
        front_end = Input(shape=input_shape)
        front_end = Conv2D(3, (3,3), padding='valid', input_shape=input_shape, activation='relu')(front_end)
        input_shape = (X.shape[1], X.shape[2], 3)    # and now we'll set input_shape as the rest of the network wants
    else:
        front_end = Input(shape=input_shape)
    #base_model = NASNetMobile(input_shape=input_shape, weights=weights, include_top=False, input_tensor=front_end)
    with CustomObjectScope({'relu6': keras.applications.mobilenet.relu6, 'DepthwiseConv2D': keras.applications.mobilenet.DepthwiseConv2D}):
        base_model = MobileNet(input_shape=input_shape, weights=weights, include_top=False, input_tensor=front_end, dropout=0.6)
    #base_model = Xception(input_shape=X[0].shape, weights=weights, include_top=False, input_tensor=front_end)

    top_model = Sequential()        # top_model gets tacked on to pretrained model
    top_model.add(Flatten(input_shape=base_model.output_shape[1:]))
    top_model.add(Dense(128))            # 128 is 'arbitrary' for now
    top_model.add(Dense(nb_classes,name='FinalOutput'))      # Final output layer

    #top_model.load_weights('bootlneck_fc_model.h5')
    model = Model(inputs= base_model.input, outputs= top_model(base_model.output))
    return model


# Used for when you want to use weights from a previously-trained model,
# with a different set/number of output classes 
Example 12
Project: pencroft   Author: lukeyeager   File: main.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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,))