我们从Python开源项目中,提取了以下4个代码示例,用于说明如何使用keras.applications()。
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)))
def get_preprocess_input_fn(model_name): print 'get_preprocess_input_fn({})'.format(model_name) return getattr(keras.applications, model_name).preprocess_input
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
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,))