Python keras.applications.resnet50.ResNet50() Examples

The following are 30 code examples for showing how to use keras.applications.resnet50.ResNet50(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module keras.applications.resnet50 , or try the search function .

Example 1
Project: spark-deep-learning   Author: databricks   File: keras_applications.py    License: Apache License 2.0 6 votes vote down vote up
def _imagenet_preprocess_input(x, input_shape):
    """
    For ResNet50, VGG models. For InceptionV3 and Xception it's okay to use the
    keras version (e.g. InceptionV3.preprocess_input) as the code path they hit
    works okay with tf.Tensor inputs. The following was translated to tf ops from
    https://github.com/fchollet/keras/blob/fb4a0849cf4dc2965af86510f02ec46abab1a6a4/keras/applications/imagenet_utils.py#L52
    It's a possibility to change the implementation in keras to look like the
    following and modified to work with BGR images (standard in Spark), but not doing it for now.
    """
    # assuming 'BGR'
    # Zero-center by mean pixel
    mean = np.ones(input_shape + (3,), dtype=np.float32)
    mean[..., 0] = 103.939
    mean[..., 1] = 116.779
    mean[..., 2] = 123.68
    return x - mean 
Example 2
Project: lost   Author: l3p-cv   File: cluster_resnet.py    License: MIT License 6 votes vote down vote up
def main(self):
        self.logger.info('Will load keras model')
        model = ResNet50(weights='imagenet')
        self.logger.info('Keras model loaded')
        feature_list = []
        img_path_list = []
        for raw_file in self.inp.raw_files:
            media_path = raw_file.path
            file_list = os.listdir(media_path)
            total = float(len(file_list))
            for index, img_file in enumerate(file_list):
                img_path = os.path.join(media_path, img_file)
                img_path_list.append(img_path)
                img = image.load_img(img_path, target_size=(224, 224))
                x = keras_image.img_to_array(img)
                x = np.expand_dims(x, axis=0)
                x = preprocess_input(x)
                # extract features
                scores = model.predict(x)
                sim_class = np.argmax(scores)
                print('Scores {}\nSimClass: {}'.format(scores, sim_class))
                self.outp.request_annos(img_path, img_sim_class=sim_class)
                self.logger.info('Requested annotation for: {} (cluster: {})'.format(img_path, sim_class))
                self.update_progress(index*100/total) 
Example 3
Project: Intelligent-Projects-Using-Python   Author: PacktPublishing   File: TransferLearning.py    License: MIT License 6 votes vote down vote up
def inception_pseudo(self,dim=224,freeze_layers=30,full_freeze='N'):
		model = InceptionV3(weights='imagenet',include_top=False)
		x = model.output
		x = GlobalAveragePooling2D()(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		out = Dense(5,activation='softmax')(x)
		model_final = Model(input = model.input,outputs=out)
		if full_freeze != 'N':
			for layer in model.layers[0:freeze_layers]:
				layer.trainable = False
		return model_final

	# ResNet50 Model for transfer Learning 
Example 4
Project: Intelligent-Projects-Using-Python   Author: PacktPublishing   File: TransferLearning.py    License: MIT License 6 votes vote down vote up
def resnet_pseudo(self,dim=224,freeze_layers=10,full_freeze='N'):
		model = ResNet50(weights='imagenet',include_top=False)
		x = model.output
		x = GlobalAveragePooling2D()(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		out = Dense(5,activation='softmax')(x)
		model_final = Model(input = model.input,outputs=out)
		if full_freeze != 'N':
			for layer in model.layers[0:freeze_layers]:
				layer.trainable = False
		return model_final

	# VGG16 Model for transfer Learning 
Example 5
Project: Intelligent-Projects-Using-Python   Author: PacktPublishing   File: TransferLearning_reg.py    License: MIT License 6 votes vote down vote up
def inception_pseudo(self,dim=224,freeze_layers=30,full_freeze='N'):
		model = InceptionV3(weights='imagenet',include_top=False)
		x = model.output
		x = GlobalAveragePooling2D()(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		out = Dense(1)(x)
		model_final = Model(input = model.input,outputs=out)
		if full_freeze != 'N':
			for layer in model.layers[0:freeze_layers]:
				layer.trainable = False
		return model_final

	# ResNet50 Model for transfer Learning 
Example 6
Project: Intelligent-Projects-Using-Python   Author: PacktPublishing   File: TransferLearning_reg.py    License: MIT License 6 votes vote down vote up
def resnet_pseudo(self,dim=224,freeze_layers=10,full_freeze='N'):
		model = ResNet50(weights='imagenet',include_top=False)
		x = model.output
		x = GlobalAveragePooling2D()(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		x = Dense(512, activation='relu')(x)
		x = Dropout(0.5)(x)
		out = Dense(1)(x)
		model_final = Model(input = model.input,outputs=out)
		if full_freeze != 'N':
			for layer in model.layers[0:freeze_layers]:
				layer.trainable = False
		return model_final

	# VGG16 Model for transfer Learning 
Example 7
Project: Intelligent-Projects-Using-Python   Author: PacktPublishing   File: TransferLearning_ffd.py    License: MIT License 6 votes vote down vote up
def resnet_pseudo(self,dim=224,freeze_layers=10,full_freeze='N'):
        model = ResNet50(weights='imagenet',include_top=False)
        x = model.output
        x = GlobalAveragePooling2D()(x)
        x = Dense(512, activation='relu')(x)
        x = Dropout(0.5)(x)
        x = Dense(512, activation='relu')(x)
        x = Dropout(0.5)(x)
        out = Dense(5,activation='softmax')(x)
        model_final = Model(input = model.input,outputs=out)
        if full_freeze != 'N':
            for layer in model.layers[0:freeze_layers]:
                layer.trainable = False
        return model_final

# VGG16 Model for transfer Learning 
Example 8
Project: maskrcnn   Author: shtamura   File: frcnn.py    License: MIT License 6 votes vote down vote up
def _model_backbone_headless(self):
        if self.config.backbone_nn_type == 'vgg':
            model = VGG16(weights='imagenet', include_top=False)
            # 畳み込み層の後のプーリング層を除く
            # https://github.com/keras-team/keras/issues/2371
            # https://github.com/keras-team/keras/issues/6229
            # http://forums.fast.ai/t/how-to-finetune-with-new-keras-api/2328/9
            model.layers.pop()
        else:
            model = ResNet50(weights='imagenet', include_top=False)
        # VGGの重みは学習対象外
        for layer in model.layers:
            layer.trainable = False
        output = model.layers[-1].output
        _input = model.input
        return _input, output 
Example 9
Project: deeposlandia   Author: Oslandia   File: feature_detection.py    License: MIT License 6 votes vote down vote up
def resnet(self):
        """Build the structure of a convolutional neural network from input
        image data to the last hidden layer on a similar manner than ResNet

        See: He, Zhang, Ren, Sun. Deep Residual Learning for Image
        Recognition. ArXiv technical report, 2015.

        Returns
        -------
        tensor
            (batch_size, nb_labels)-shaped output predictions, that have to be
        compared with ground-truth values
        """
        resnet_model = resnet50.ResNet50(
            include_top=False, input_tensor=self.X
        )
        y = self.flatten(resnet_model.output)
        return self.output_layer(y, depth=self.nb_labels) 
Example 10
Project: face_age_gender   Author: CVxTz   File: baseline_age.py    License: MIT License 6 votes vote down vote up
def get_model(n_classes=1):

    base_model = ResNet50(weights='imagenet', include_top=False)

    #for layer in base_model.layers:
    #    layer.trainable = False

    x = base_model.output
    x = GlobalMaxPooling2D()(x)
    x = Dropout(0.5)(x)
    x = Dense(100, activation="relu")(x)
    x = Dropout(0.5)(x)
    if n_classes == 1:
        x = Dense(n_classes, activation="sigmoid")(x)
    else:
        x = Dense(n_classes, activation="softmax")(x)

    base_model = Model(base_model.input, x, name="base_model")
    if n_classes == 1:
        base_model.compile(loss="binary_crossentropy", metrics=['acc'], optimizer="adam")
    else:
        base_model.compile(loss="sparse_categorical_crossentropy", metrics=['acc'], optimizer="adam")

    return base_model 
Example 11
Project: face_age_gender   Author: CVxTz   File: baseline_gender.py    License: MIT License 6 votes vote down vote up
def get_model(n_classes=1):

    base_model = ResNet50(weights='imagenet', include_top=False)

    #for layer in base_model.layers:
    #    layer.trainable = False

    x = base_model.output
    x = GlobalMaxPooling2D()(x)
    x = Dropout(0.5)(x)
    x = Dense(100, activation="relu")(x)
    x = Dropout(0.5)(x)
    if n_classes == 1:
        x = Dense(n_classes, activation="sigmoid")(x)
    else:
        x = Dense(n_classes, activation="softmax")(x)

    base_model = Model(base_model.input, x, name="base_model")
    if n_classes == 1:
        base_model.compile(loss="binary_crossentropy", metrics=['acc'], optimizer="adam")
    else:
        base_model.compile(loss="sparse_categorical_crossentropy", metrics=['acc'], optimizer="adam")

    return base_model 
Example 12
Project: SmooFaceEngine   Author: wotchin   File: cnn_models.py    License: Apache License 2.0 6 votes vote down vote up
def ResNet50(input_shape, num_classes):
    # wrap ResNet50 from keras, because ResNet50 is so deep.
    from keras.applications.resnet50 import ResNet50
    input_tensor = Input(shape=input_shape, name="input")
    x = ResNet50(include_top=False,
                 weights=None,
                 input_tensor=input_tensor,
                 input_shape=None,
                 pooling="avg",
                 classes=num_classes)
    x = Dense(units=2048, name="feature")(x.output)
    return Model(inputs=input_tensor, outputs=x)


# implement ResNet's block.
# I implement two classes block:
# one is basic block, the other is bottleneck block. 
Example 13
Project: EmoPy   Author: thoughtworksarts   File: neuralnets.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_base_model(self):
        """
        :return: base model from Keras based on user-supplied model name
        """
        if self.model_name == 'inception_v3':
            return InceptionV3(weights='imagenet', include_top=False)
        elif self.model_name == 'xception':
            return Xception(weights='imagenet', include_top=False)
        elif self.model_name == 'vgg16':
            return VGG16(weights='imagenet', include_top=False)
        elif self.model_name == 'vgg19':
            return VGG19(weights='imagenet', include_top=False)
        elif self.model_name == 'resnet50':
            return ResNet50(weights='imagenet', include_top=False)
        else:
            raise ValueError('Cannot find base model %s' % self.model_name) 
Example 14
Project: lunania-ai   Author: mrm-xiefan   File: fcn.py    License: MIT License 6 votes vote down vote up
def createResNetModel():
    
    input_shape = (config.img_height, config.img_width, 3)

    input_img = Input(shape=input_shape, name='input_1')

    model = ResNet50(include_top=False, input_tensor=input_img)
    x = model.layers[-2].output

    # FC layer
    x = Cropping2D(cropping=((0, 1), (0, 1)), name='cropping2d_2')(x)
    h_grid = int(round(config.img_height / 100))
    w_grid = int(round(config.img_width / 100))
    x = Conv2DTranspose(config.classes, (64, 64),
        #output_shape=(None, h_grid * 102, w_grid * 102, config.classes),
        strides=(34, 34),
        padding='same',
        name='deconvolution2d_1')(x)
    x = Cropping2D(cropping=((h_grid, h_grid), (w_grid, w_grid)), name='cropping2d_1')(x)

    x = Reshape((config.img_width * config.img_height, config.classes), name='reshape_1')(x)
    out = Activation("softmax", name='activation_fc')(x)
    model = Model(model.layers[0].input, out)

    return model 
Example 15
Project: Pix2Depth   Author: gautam678   File: cnn_architecture.py    License: GNU General Public License v3.0 6 votes vote down vote up
def model_3():

    input_layer = Input(shape=(224,224,3))
    from keras.layers import Conv2DTranspose as DeConv
    resnet = ResNet50(include_top=False, weights="imagenet")
    resnet.trainable = False

    res_features = resnet(input_layer)

    conv = DeConv(1024, padding="valid", activation="relu", kernel_size=3)(res_features)
    conv = UpSampling2D((2,2))(conv)
    conv = DeConv(512, padding="valid", activation="relu", kernel_size=5)(conv)
    conv = UpSampling2D((2,2))(conv)
    conv = DeConv(128, padding="valid", activation="relu", kernel_size=5)(conv)
    conv = UpSampling2D((2,2))(conv)
    conv = DeConv(32, padding="valid", activation="relu", kernel_size=5)(conv)
    conv = UpSampling2D((2,2))(conv)
    conv = DeConv(8, padding="valid", activation="relu", kernel_size=5)(conv)
    conv = UpSampling2D((2,2))(conv)
    conv = DeConv(4, padding="valid", activation="relu", kernel_size=5)(conv)
    conv = DeConv(1, padding="valid", activation="sigmoid", kernel_size=5)(conv)

    model = Model(inputs=input_layer, outputs=conv)
    return model 
Example 16
Project: eye-in-the-sky   Author: manideep2510   File: pspnet.py    License: Apache License 2.0 5 votes vote down vote up
def resnet(x, input_shape):
    
    # Decreases the dimensions of the input image by a factor of 32
    x = ResNet50(include_top=False, weights=None, input_tensor=x, input_shape=(512,512,3)).output
    
    # Upsampling by 2
    x = UpSampling2D(size = (2,2))(x)
    ##x = BatchNormalization()(x)
    
    # Again Upsampling by 2 so that we get an output feature map of size 1/8th of the initial image
    x = UpSampling2D(size = (2,2))(x)
    ##res = BatchNormalization()(x)
    x = UpSampling2D(size = (2,2))(x)
    return x 
Example 17
Project: eye-in-the-sky   Author: manideep2510   File: pspnet.py    License: Apache License 2.0 5 votes vote down vote up
def PSPNet(n_classes = 3, input_shape = (128, 128, 4)):
    
    # Input to the model
    inputs = Input(input_shape)
    
    '''in_shape = inputs.shape
    out_shape = (in_shape[1], in_shape[2], 3)'''
    
    # Converting 4 channel input to a 3 channel map using Encoder-Decoder network 
    # to give it as a input to ResNet50 with pretrained weights
    res_input = encoder_decoder(inputs)            
    
    res_input_shape = K.int_shape(res_input)
    res_input_shape = (res_input_shape[1],res_input_shape[2],res_input_shape[3])
    
    # Passing the 3 channel map into ResNet50 followed by 2 upsampling layers 
    # to get a output of shape exactly 1/8th of the input map shape
    res = resnet(res_input, input_shape = res_input_shape)                        
    
    # Pyramid Pooling Module
    ppmodule_out = pyramid_pooling_module(res)                
    
    # Final Conv layers and output
    x = Conv2D(512, 3, activation = 'relu', padding='same')(ppmodule_out)
    x = BatchNormalization()(x)
    x = Dropout(0.5)(x)
    
    x = Conv2D(n_classes, 1)(x)
    #x = interpolation(x, shape = (input_shape[0], input_shape[1]))
    x = Lambda(interpolation, arguments={'shape': (input_shape[0], input_shape[1])})(x)
    out = Activation('softmax')(x)
    
    model = Model(inputs = inputs, outputs = out)
    
    adam = Adam(lr = 0.00001)
    
    model.compile(optimizer = adam, loss = 'categorical_crossentropy', metrics = ['accuracy'])
    
    model.summary()
    return model 
Example 18
Project: spark-deep-learning   Author: databricks   File: keras_applications.py    License: Apache License 2.0 5 votes vote down vote up
def model(self, preprocessed, featurize):
        # Model provided by Keras. All cotributions by Keras are provided subject to the
        # MIT license located at https://github.com/fchollet/keras/blob/master/LICENSE
        # and subject to the below additional copyrights and licenses.
        #
        # The MIT License (MIT)
        #
        # Copyright (c) 2016 Shaoqing Ren
        #
        # Permission is hereby granted, free of charge, to any person obtaining a copy
        # of this software and associated documentation files (the "Software"), to deal
        # in the Software without restriction, including without limitation the rights
        # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        # copies of the Software, and to permit persons to whom the Software is
        # furnished to do so, subject to the following conditions:
        #
        # The above copyright notice and this permission notice shall be included in all
        # copies or substantial portions of the Software.
        #
        # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        # SOFTWARE.
        return resnet50.ResNet50(input_tensor=preprocessed, weights="imagenet",
                                 include_top=(not featurize)) 
Example 19
Project: spark-deep-learning   Author: databricks   File: keras_applications.py    License: Apache License 2.0 5 votes vote down vote up
def _testKerasModel(self, include_top):
        # New Keras model changed the sturecture of ResNet50, we need to add avg for to compare
        # the result. We need to change the DeepImageFeaturizer for the new Model definition in
        # Keras
        return resnet50.ResNet50(weights="imagenet", include_top=include_top, pooling='avg') 
Example 20
Project: videofeatures   Author: jonasrothfuss   File: CNNFeatures.py    License: MIT License 5 votes vote down vote up
def __init__(self):
    self.base_model = resnet50.ResNet50()
    self.model = Model(inputs=self.base_model.input, outputs=self.base_model.get_layer('avg_pool').output) 
Example 21
Project: head-detection-using-yolo   Author: pranoyr   File: backend.py    License: MIT License 5 votes vote down vote up
def __init__(self, input_size):
        resnet50 = ResNet50(input_shape=(input_size, input_size, 3), include_top=False)
        resnet50.layers.pop() # remove the average pooling layer
        #resnet50.load_weights(RESNET50_BACKEND_PATH)

        self.feature_extractor = Model(resnet50.layers[0].input, resnet50.layers[-1].output) 
Example 22
Project: lost   Author: l3p-cv   File: cluster_resnet.py    License: MIT License 5 votes vote down vote up
def main(self):
        self.logger.info('Will load keras model')
        model = ResNet50(weights='imagenet')
        self.logger.info('Keras model loaded')
        feature_list = []
        img_path_list = []
        # Request only MIA annotations for annotations of first stage
        # that have been annotated in current iteration cycle.
        img_annos = list(filter(lambda x: x.iteration == self.iteration, 
            self.inp.img_annos))
        total = len(img_annos)
        for index, img_anno in enumerate(img_annos):
            annos = img_anno.to_vec('anno.data')
            if annos:
                types = img_anno.to_vec('anno.dtype')
                img = skimage.io.imread(self.get_abs_path(img_anno.img_path))
                crops, anno_boxes = anno_helper.crop_boxes(annos, types, 
                    img, context=0.01)
                sim_classes = []
                for crop in crops:
                    # img = image.load_img(img_path, target_size=(224, 224))
                    crop_img = image.img_to_array(image.array_to_img(crop, scale=False).resize((224,224)))
                    x = keras_image.img_to_array(crop_img)
                    x = np.expand_dims(x, axis=0)
                    x = preprocess_input(x)
                    # extract features
                    scores = model.predict(x)
                    sim_classes.append(np.argmax(scores))
                self.outp.request_annos(img_anno.img_path, 
                    annos=annos, anno_types=types, anno_sim_classes=sim_classes)
                self.logger.info('Requested annotation for: {}\n{}\n{}'.format(img_anno.img_path, types, sim_classes))
                self.update_progress(index*100/total) 
Example 23
Project: lost   Author: l3p-cv   File: cluster_kmeans.py    License: MIT License 5 votes vote down vote up
def main(self):
        n_cluster = int(self.get_arg('n-clusters'))
        self.logger.info('Will load keras model')
        base_model = ResNet50(weights='imagenet')
        self.logger.info('Keras model loaded')
        layer_code = 'avg_pool'
        # base_model.summary()
        model = Model(inputs=base_model.input, outputs=base_model.get_layer(layer_code).output)
        feature_list = []
        img_path_list = []
        self.logger.info('Will compute CNN features')
        for raw_file in self.inp.raw_files:
            media_path = raw_file.path
            media_path = raw_file.path
            file_list = os.listdir(media_path)
            total = float(len(file_list))
            for index, img_file in enumerate(file_list):
                img_path = os.path.join(media_path, img_file)
                img_path_list.append(img_path)
                img = image.load_img(img_path, target_size=(224, 224))
                x = keras_image.img_to_array(img)
                x = np.expand_dims(x, axis=0)
                x = preprocess_input(x)
                # extract features
                features = model.predict(x)
                feature_list.append(features[0].flatten())
                self.update_progress(index*70/total)
        self.logger.info('Computed CNN feature!')
        self.logger.info('Start KMeans clustering')
        kmeans = KMeans(n_clusters=n_cluster, random_state=0).fit(feature_list)
        self.logger.info('Clustering completed!')
        counter = 0
        for sim_class, img_path in zip(kmeans.labels_, img_path_list):
            self.outp.request_annos(img_path, img_sim_class=sim_class)
            self.logger.info('Requested annotation for: {} (cluster: {})'.format(img_path, sim_class))
            counter += 1
            self.update_progress(70 + (counter*30/len(img_path_list))) 
Example 24
Project: Aesthetic_attributes_maps   Author: gautamMalu   File: models.py    License: MIT License 5 votes vote down vote up
def model1(weights_path=None):
    '''
    Basic ResNet-FT for baseline comparisions.
    Creates a model by for all aesthetic attributes along
    with overall aesthetic score, by finetuning resnet50
    :param weights_path: path of the weight file
    :return: Keras model instance
    '''
    _input = Input(shape=(299, 299, 3))
    resnet = ResNet50(include_top=False, weights='imagenet', input_tensor=_input)

    last_layer_output = GlobalAveragePooling2D()(resnet.get_layer('activation_49').output)

    # output of model
    outputs = []
    attrs = ['BalacingElements', 'ColorHarmony', 'Content', 'DoF',
             'Light', 'MotionBlur', 'Object', 'RuleOfThirds', 'VividColor']
    for attribute in attrs:
        outputs.append(Dense(1, init='glorot_uniform', activation='tanh', name=attribute)(last_layer_output))

    non_negative_attrs = ['Repetition', 'Symmetry', 'score']
    for attribute in non_negative_attrs:
        outputs.append(Dense(1, init='glorot_uniform', activation='sigmoid', name=attribute)(last_layer_output))

    model = Model(input=_input, output=outputs)
    if weights_path:
        model.load_weights(weights_path)
    return model 
Example 25
Project: autowebcompat   Author: marco-c   File: network.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def create_resnet50_network(input_shape, weights):
    base_model = ResNet50(input_shape=input_shape, weights=weights)
    return Model(inputs=base_model.input, outputs=base_model.get_layer('flatten_1').output) 
Example 26
def get_model_pretrain(arch):
    modlrate = 1
    if   "VGG16" in arch:       base_model = vgg16.VGG16
    elif "VGG19" in arch:       base_model = vgg19.VGG19
    elif "RESNET50" in arch:    base_model = resnet50.ResNet50
    elif "DENSENET121" in arch: base_model = densenet.DenseNet121
    elif "MOBILENET" in arch:
        base_model = mobilenet.MobileNet
        modlrate = 10
    else: print("model not avaiable"); exit()
    base_model = base_model(weights='imagenet', include_top=False)
    return base_model, modlrate 
Example 27
Project: kale   Author: kubeflow-kale   File: extract_bottleneck_features.py    License: Apache License 2.0 5 votes vote down vote up
def extract_Resnet50(tensor):
	from keras.applications.resnet50 import ResNet50, preprocess_input
	return ResNet50(weights='imagenet', include_top=False).predict(preprocess_input(tensor)) 
Example 28
Project: CarND-Transfer-Learning-Lab   Author: udacity   File: run_bottleneck.py    License: MIT License 5 votes vote down vote up
def create_model():
    input_tensor = Input(shape=(h, w, ch))
    if FLAGS.network == 'vgg':
        model = VGG16(input_tensor=input_tensor, include_top=False)
        x = model.output
        x = AveragePooling2D((7, 7))(x)
        model = Model(model.input, x)
    elif FLAGS.network == 'inception':
        model = InceptionV3(input_tensor=input_tensor, include_top=False)
        x = model.output
        x = AveragePooling2D((8, 8), strides=(8, 8))(x)
        model = Model(model.input, x)
    else:
        model = ResNet50(input_tensor=input_tensor, include_top=False)
    return model 
Example 29
Project: transfer   Author: matthew-sochor-zz   File: resnet50.py    License: MIT License 5 votes vote down vote up
def get_resnet_model(img_dim):
    array_input = Input(shape=(img_dim, img_dim, 3))
    resnet = ResNet50(include_top=False,
                     weights='imagenet',
                     input_tensor=array_input,
                     pooling='avg')
    return resnet 
Example 30
Project: keras-transfer-learning-for-oxford102   Author: Arsey   File: resnet50.py    License: MIT License 5 votes vote down vote up
def _create(self):
        base_model = KerasResNet50(include_top=False, input_tensor=self.get_input_tensor())
        self.make_net_layers_non_trainable(base_model)

        x = base_model.output
        x = Flatten()(x)
        x = Dropout(0.5)(x)
        # we could achieve almost the same accuracy without this layer, buy this one helps later
        # for novelty detection part and brings much more useful features.
        x = Dense(self.noveltyDetectionLayerSize, activation='elu', name=self.noveltyDetectionLayerName)(x)
        x = Dropout(0.5)(x)
        predictions = Dense(len(config.classes), activation='softmax', name='predictions')(x)

        self.model = Model(input=base_model.input, output=predictions)