Exemple #1
0
def save_bioimaging_bottleneck(glob_variables):
    model = ResNet152V2(include_top=False, weights='imagenet')

    datagen = ImageDataGenerator(rescale=1. / 255)

    generator = datagen.flow_from_directory(
        glob_variables['bioimaging_patch_images_data_dir'] +
        str(glob_variables['img_width']),
        target_size=(glob_variables['img_width'],
                     glob_variables['img_height']),
        batch_size=glob_variables['batch_size'],
        class_mode=None,
        shuffle=False)

    nb_validation_samples = len(generator.filenames)

    predict_size_validation = int(
        math.ceil(nb_validation_samples / glob_variables['batch_size']))

    bottleneck_features_validation = model.predict(generator,
                                                   predict_size_validation)

    np.save(
        'bioimaging/bottleneck_features_validation_bioimaging_' +
        glob_variables['model'] + '_' + str(glob_variables['img_width']) +
        '.npy', bottleneck_features_validation)
Exemple #2
0
def evaluation(args):
    path_img_val = '../datasets/ilsvrc2012/images/val/'
    path_val_info = '../datasets/ilsvrc2012/images/val.txt'

    if args.model == 'vgg16':
        model = VGG16(weights='imagenet')
        model.summary()
    elif args.model == 'resnet152':
        model = ResNet152(weights='imagenet')
        model.summary()
    elif args.model == 'resnet152v2':
        model = ResNet152V2(weights='imagenet')
        model.summary()
    elif args.model == 'inceptionresnetv2':
        model = InceptionResNetV2(weights='imagenet')
        model.summary()
    elif args.model == 'densenet201':
        model = DenseNet201(weights='imagenet')
        model.summary()
    elif args.model == 'nasnetlarge':
        model = NASNetLarge(weights='imagenet')
        model.summary()

    name, label = load_header_imagenet(load_file(path_val_info))
    pred = list()
    for i, n in enumerate(name):
        x = preprocessing_imagenet(path_img_val + n, args)
        pred.append(np.argmax(model.predict(x), axis=1)[0])
        if i % 1000 == 0:
            print(n)

    correct = len([p for p, l in zip(pred, label) if p == l])
    print('Accuracy of the IMAGENET dataset using model %s: %.4f' %
          (args.model, correct / len(label)))
Exemple #3
0
def apply_Feature_Extractor_model(params):
    """
    Apply a previously trained model.
    :param params: Hyperparameters
    :return:
    """
    model = None
    if params['MODEL_TYPE'] == 'InceptionV3':
        model = InceptionV3(weights='imagenet', include_top=False)
    elif params['MODEL_TYPE'] == 'NASNetLarge':
        model = NASNetLarge(weights='imagenet', include_top=False)
    elif params['MODEL_TYPE'] == 'ResNet152':
        model = ResNet152V2(weights='imagenet', include_top=False)

    print(model.summary())
    base_path = params['DATA_ROOT_PATH']

    for s in params['EXTRACT_ON_SETS']:
        if params['SPLIT_OUTPUT']:
            path_general = params['STORE_PATH'] + '/' + params.get(
                'MODEL_TYPE', 'features') + '/' + s + '/'
            if not os.path.isdir(
                    path_general):  # create dir if it doesn't exist
                os.makedirs(path_general)
        list_filepath = base_path + '/' + params['IMG_FILES'][s]
        image_list = file2list(list_filepath)
        eta = -1
        start_time = time.time()
        n_images = len(image_list)
        for n_sample, imname in list(enumerate(image_list)):
            if params['MODEL_TYPE'] == 'InceptionV3':
                features = inceptionV3(model, imname)
            elif params['MODEL_TYPE'] == 'NASNetLarge':
                features = nasNetLarge(model, imname)
            elif params['MODEL_TYPE'] == 'ResNet152':
                features = resNet152(model, imname)

            # Keras puts the spatial dimensions at the start. We may want to put them at the end
            if params.get('SPATIAL_LAST', True):
                features = features.transpose(0, 3, 1, 2)

            filepath = path_general + imname.split(
                '/')[-1][:-4] + '.npy' if imname.split(
                    '/')[-1][-4:] == '.jpg' or imname.split('/')[-1][
                        -4:] == '.png' else path_general + imname.split(
                            '/')[-1] + '.npy'
            numpy2file(filepath, features, permission='wb', split=False)
            sys.stdout.write('\r')
            sys.stdout.write("\t Processed %d/%d  -  ETA: %ds " %
                             (n_sample, n_images, int(eta)))
            sys.stdout.flush()
            eta = (n_images - n_sample) * (time.time() - start_time) / max(
                n_sample, 1)
    print("Features saved in", path_general)
Exemple #4
0
 def load_models(self):
     """
     Instantiates models and loads the weights.
     **MUST LOAD BEFORE RUNNING MODELS**
     """
     input_tensor = Input(shape=(self.dim_size, self.dim_size, 3))
     self.resnet = ResNet152V2(input_tensor=input_tensor, weights=None, classes=7)
     self.resnet.load_weights('weights_resnet224.h5', by_name=False)
     self.inception = InceptionV3(input_tensor=input_tensor, weights=None, classes=7)
     self.inception.load_weights('weights_inception224.h5', by_name=False)
     self.inceptionresnet = InceptionResNetV2(input_tensor=input_tensor, weights=None, classes=7)
     self.inceptionresnet.load_weights('weights_inceptionresnet224.h5', by_name=False)
Exemple #5
0
def output_make(input_path, label_path, target):
    with tf.device('/cpu:0'):
        base_model = ResNet152V2(weights=None,
                                 include_top=False,
                                 input_shape=(224, 224, 1))
        x = base_model.output
        x = GlobalAveragePooling2D()(x)
        x = Dropout(0.3)(x)
        predictions = Dense(5, activation='softmax')(x)

        resnet_model = Model(inputs=base_model.input, outputs=predictions)
        # resnet_hist = compile_and_train(resnet_model, num_epochs)
        resnet_model.load_weights('./PredictHouseholdIncome_pradeep4444.hdf5')
        sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
        resnet_model.compile(loss='categorical_crossentropy',
                             optimizer=sgd,
                             metrics=['accuracy'])

        X = make_img(input_path)
        X = normalize_X(X)

        pickle_path = os.path.join(input_path, 'processed_pickles')
        make_pickle(X, 'pickled_image_array', pickle_path)
        X = read_pickle('pickled_image_array', pickle_path)
        y_preds = resnet_model.predict(X)
        try:
            y_OHE = make_label_array(label_path, target)
            y_preds = resnet_aug.predict(X_test)
            matrix = confusion_matrix(y_OHE.argmax(axis=1),
                                      y_preds.argmax(axis=1))

            y_pred_bool = np.argmax(y_preds, axis=1)
            y_test_bool = np.argmax(y_OHE, axis=1)
            class_report = classification_report(y_test_bool, y_pred_bool)
            with open('output.txt', 'w') as op_handle:
                op_handle.write('raw predictions:\n')
                op_handle.write(str(y_preds))
                op_handle.write('\n')

                op_handle.write('confusion martix:\n')
                op_handle.write(str(matrix))
                op_handle.write('\n')

                op_handle.write('classification report:\n')
                op_handle.write(str(class_report))
                op_handle.write('\n')

        except:
            pass
 def load_models(self):
     input_tensor = Input(shape=(self.dim_size, self.dim_size, 3))
     self.resnet = ResNet152V2(input_tensor=input_tensor,
                               weights=None,
                               classes=7)
     self.resnet.load_weights('weights_resnet224.h5', by_name=False)
     self.inception = InceptionV3(input_tensor=input_tensor,
                                  weights=None,
                                  classes=7)
     self.inception.load_weights('weights_inception224.h5', by_name=False)
     self.inceptionresnet = InceptionResNetV2(input_tensor=input_tensor,
                                              weights=None,
                                              classes=7)
     self.inceptionresnet.load_weights('weights_inceptionresnet224.h5',
                                       by_name=False)
Exemple #7
0
def ResNet152V2model(no_classes, shape):
    """
        Deep CNN 50 layers
    """
    base_model = ResNet152V2(include_top=False,
                             weights='imagenet',
                             input_shape=shape)
    # Freeze the base_model
    base_model.trainable = False
    inputs = Input(shape=shape)
    x = base_model(inputs, training=False)
    x = GlobalAveragePooling2D()(x)
    x = Dense(1024, activation='relu', name='predictions')(x)
    #x = Dropout(0.2)(x)
    predictions = Dense(no_classes, activation='softmax')(x)
    model = Model(inputs, outputs=predictions)
    return model
Exemple #8
0
def predict_single(glob_variables):
    model = None

    if glob_variables['model'] == 'Xception':
        model = Xception(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'NASNetLarge':
        model = NASNetLarge(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'DenseNet201':
        model = DenseNet201(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'VGG16':
        model = VGG16(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'VGG19':
        model = VGG19(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'InceptionV3':
        model = InceptionV3(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'InceptionResNetV2':
        model = InceptionResNetV2(include_top=False, weights='imagenet')

    elif glob_variables['model'] == 'ResNet152V2':
        model = ResNet152V2(include_top=False, weights='imagenet')

    datagen = ImageDataGenerator(rescale=1. / 255)

    generator = datagen.flow_from_directory(
        'predict_single/',
        target_size=(glob_variables['img_width'],
                     glob_variables['img_height']),
        batch_size=glob_variables['batch_size'],
        class_mode=None,
        shuffle=False)

    nb_validation_samples = len(generator.filenames)

    predict_size_validation = int(
        math.ceil(nb_validation_samples / glob_variables['batch_size']))

    bottleneck_features_validation = model.predict(generator,
                                                   predict_size_validation)

    return bottleneck_features_validation
def load_model(dim_size):
    input_tensor = Input(shape=(dim_size, dim_size, 3))
    global model
    model = ResNet152V2(input_tensor=input_tensor, weights=None, classes=7)

    if path.exists(weights):
        model.load_weights(weights, by_name=False)

    #for layer in model.layers[:551]:
    #   layer.trainable = False
    #for layer in model.layers[551:]:
    #   layer.trainable = True
    for layer in model.layers:
        layer.trainable = True

    model.compile(optimizer=SGD(lr=0.01, momentum=0.9),
                  loss='categorical_crossentropy',
                  metrics=["accuracy"])
Exemple #10
0
        search = OptimizationSearch(
            np.load('data/vgg19_%s_correct.npy' % SAMPLE, allow_pickle=True),
            filter,
            model,
            vgg19_preprocess_input
        )
        results, scores = search.perform_search(iterations=ITERATIONS)
        save_filter_search_scores(filter, results, scores, 'log/fourier_uniform_filter_vgg19_%s_search.csv' % SAMPLE)

    if NETWORK == 'densenet':
        model = DenseNet201(weights='imagenet')
        search = OptimizationSearch(
            np.load('data/densenet201_%s_correct.npy' % SAMPLE, allow_pickle=True),
            filter,
            model,
            densenet_preprocess_input
        )
        results, scores = search.perform_search(iterations=ITERATIONS)
        save_filter_search_scores(filter, results, scores, 'log/fourier_uniform_filter_densenet201_%s_search.csv' % SAMPLE)

    if NETWORK == 'resnet':
        model = ResNet152V2(weights='imagenet')
        search = OptimizationSearch(
            np.load('data/resnet152v2_%s_correct.npy' % SAMPLE, allow_pickle=True),
            filter,
            model,
            resnet_preprocess_input
        )
        results, scores = search.perform_search(iterations=ITERATIONS)
        save_filter_search_scores(filter, results, scores, 'log/fourier_uniform_filter_resnet152v2_%s_search.csv' % SAMPLE)
Exemple #11
0
from keras.applications.resnet_v2 import ResNet152V2
from keras.preprocessing import image
from keras.applications.resnet_v2 import preprocess_input
from keras.layers import Input
from util import map_scores
import numpy as np
import tensorflow as tf

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.keras.backend.set_session(tf.Session(config=config))

dim_size = 112
input_tensor = Input(shape=(dim_size, dim_size, 3))

model = ResNet152V2(input_tensor=input_tensor, weights=None, classes=7)
model.load_weights('resnet_weights.h5', by_name=False)

img_path = 'test_imgs/keratosis2.jpg'
img = image.load_img(img_path, target_size=(dim_size, dim_size))
x = image.img_to_array(img)
x = x / 255.0
x = np.expand_dims(x, axis=0)
#x = preprocess_input(x)

preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', map_scores(preds, 3)[0])
def chosen_model(choice):
    global base_model
    if choice == 19:
        model_exist()
    else:
        while (1):
            print()
            print(
                'Transfer Learning? - Will use pre-trained model with imagenet weights'
            )
            print('y')
            print('n')
            weights_wanted = input()
            if weights_wanted.upper() != 'Y' and weights_wanted.upper() != 'N':
                print('ERROR: Please enter a valid choice')
            else:
                break
        if choice == 1:
            print('Selected Model = Xception')
            if weights_wanted.upper() == 'Y':
                base_model = Xception(weights='imagenet', include_top=False)
            else:
                base_model = Xception(weights=None, include_top=False)
        if choice == 2:
            print('Selected Model = VGG16')
            if weights_wanted.upper() == 'Y':
                base_model = VGG16(weights='imagenet', include_top=False)
            else:
                base_model = VGG16(weights=None, include_top=False)
        if choice == 3:
            print('Selected Model = VGG19')
            if weights_wanted.upper() == 'Y':
                base_model = VGG19(weights='imagenet', include_top=False)
            else:
                base_model = VGG19(weights=None, include_top=False)
        if choice == 4:
            print('Selected Model = ResNet50')
            if weights_wanted.upper() == 'Y':
                base_model = ResNet50(weights='imagenet', include_top=False)
            else:
                base_model = ResNet50(weights=None, include_top=False)
        if choice == 5:
            print('Selected Model = ResNet101')
            if weights_wanted.upper() == 'Y':
                base_model = ResNet101(weights='imagenet', include_top=False)
            else:
                base_model = ResNet101(weights=None, include_top=False)
        if choice == 6:
            print('Selected Model = ResNet152')
            if weights_wanted.upper() == 'Y':
                base_model = ResNet152(weights='imagenet', include_top=False)
            else:
                base_model = ResNet152(weights=None, include_top=False)
        if choice == 7:
            print('Selected Model = ResNet50V2')
            if weights_wanted.upper() == 'Y':
                base_model = ResNet50V2(weights='imagenet', include_top=False)
            else:
                base_model = ResNet50V2(weights=None, include_top=False)
        if choice == 8:
            print('Selected Model = ResNet101V2')
            if weights_wanted.upper() == 'Y':
                base_model = ResNet101V2(weights='imagenet', include_top=False)
            else:
                base_model = ResNet101V2(weights=None, include_top=False)
        if choice == 9:
            print('Selected Model = ResNet152V2')
            if weights_wanted.upper() == 'Y':
                base_model = ResNet152V2(weights='imagenet', include_top=False)
            else:
                base_model = ResNet152V2(weights=None, include_top=False)
        if choice == 10:
            print('Selected Model = InceptionV3')
            if weights_wanted.upper() == 'Y':
                base_model = InceptionV3(weights='imagenet', include_top=False)
            else:
                base_model = InceptionV3(weights=None, include_top=False)
        if choice == 11:
            print('Selected Model = InceptionResNetV2')
            if weights_wanted.upper() == 'Y':
                base_model = InceptionResNetV2(weights='imagenet',
                                               include_top=False)
            else:
                base_model = InceptionResNetV2(weights=None, include_top=False)
        if choice == 12:
            print('Selected Model = MobileNet')
            if weights_wanted.upper() == 'Y':
                base_model = MobileNet(weights='imagenet', include_top=False)
            else:
                base_model = MobileNet(weights=None, include_top=False)
        if choice == 13:
            print('Selected Model = MobileNetV2')
            if weights_wanted.upper() == 'Y':
                base_model = MobileNetV2(weights='imagenet', include_top=False)
            else:
                base_model = MobileNetV2(weights=None, include_top=False)
        if choice == 14:
            print('Selected Model = DenseNet121')
            if weights_wanted.upper() == 'Y':
                base_model = DenseNet121(weights='imagenet', include_top=False)
            else:
                base_model = DenseNet121(weights=None, include_top=False)
        if choice == 15:
            print('Selected Model = DenseNet169')
            if weights_wanted.upper() == 'Y':
                base_model = DenseNet169(weights='imagenet', include_top=False)
            else:
                base_model = DenseNet169(weights=None, include_top=False)
        if choice == 16:
            print('Selected Model = DenseNet201')
            if weights_wanted.upper() == 'Y':
                base_model = DenseNet201(weights='imagenet', include_top=False)
            else:
                base_model = DenseNet201(weights=None, include_top=False)
        if choice == 17:
            print('Selected Model = NASNetLarge')
            if weights_wanted.upper() == 'Y':
                base_model = NASNetLarge(weights='imagenet', include_top=False)
            else:
                base_model = NASNetLarge(weights=None, include_top=False)
        if choice == 18:
            print('Selected Model = NASNetMobile')
            if weights_wanted.upper() == 'Y':
                base_model = NASNetMobile(weights='imagenet',
                                          include_top=False)
            else:
                base_model = NASNetMobile(weights=None, include_top=False)

        CLASSES = len(os.listdir('data/train'))
        print('Number of Classes = {}'.format(CLASSES))

        x = base_model.output
        x = GlobalAveragePooling2D(name='avg_pool')(x)
        x = Dropout(0.4)(x)
        predictions = Dense(CLASSES, activation='softmax')(x)
        model = Model(inputs=base_model.input, outputs=predictions)

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

        model.compile(optimizer='rmsprop',
                      loss='categorical_crossentropy',
                      metrics=['accuracy'])
        training(model)
Exemple #13
0
input_shape = x_train[0].shape

# Define network

if extract_model == 'vgg16':
	from keras.applications.vgg16 import VGG16
	trained_model = VGG16(include_top=False, input_shape=input_shape)
elif extract_model == 'inceptionv3':
	from keras.applications.inception_v3 import InceptionV3
	trained_model = InceptionV3(include_top=False, input_shape=input_shape)
elif extract_model == 'xception':
	from keras.applications.xception import Xception
	trained_model = Xception(include_top=False, input_shape=input_shape)
elif extract_model == 'resnet152v2':
	from keras.applications.resnet_v2 import ResNet152V2
	trained_model = ResNet152V2(include_top=False, input_shape=input_shape)
elif extract_model == 'inception_resnetv2':
	from keras.applications.inception_resnet_v2 import InceptionResNetV2
	trained_model = InceptionResNetV2(include_top=False, input_shape=input_shape)

output = trained_model.layers[-1].output
output = GlobalMaxPooling2D()(output)
output = Dense(100, activation='relu')(output)
output = Dense(num_classes, activation='softmax')(output)
model = Model(input=trained_model.input, output=output)
model.summary()

model_path = Path('/dovilabfs/work/tommaria/gw/gravityspy/gpu/' + train_set + '/new/' + extract_model + '/' + opt_method + '/' + model_name)
weights_file = join(model_path, model_name + '.weights.best.hdf5')
if not os.path.exists(model_path):
    os.makedirs(model_path)
lr_reduction=ReduceLROnPlateau(monitor='val_loss',patience=5,
                               verbose=2,factor=.8)
estopping=EarlyStopping(monitor='val_loss',patience=30,verbose=2)
history=vgg19model.fit(pvx_train1,y_train1, 
                       validation_data=(pvx_valid1,y_valid1), 
                       epochs=800,batch_size=128,verbose=2, 
                       callbacks=[checkpointer,lr_reduction,estopping])

history_plot(history)
vgg19model.load_weights(fw)
vgg19model.evaluate(pvx_test1,y_test1)

from keras.applications.resnet_v2 import ResNet152V2,preprocess_input as preiRN
#vx_train1,vx_valid1,vx_test1=\
#preiRN(x_train1),preiRN(x_valid1),preiRN(x_test1)
RNbmodel=ResNet152V2(weights='imagenet',include_top=False)
pvx_train1=RNbmodel.predict(x_train1)
pvx_valid1=RNbmodel.predict(x_valid1)
pvx_test1=RNbmodel.predict(x_test1)
pvx_train1=pvx_train1.reshape(-1,1,1,pvx_train1.shape[3])
pvx_valid1=pvx_valid1.reshape(-1,1,1,pvx_valid1.shape[3])
pvx_test1=pvx_test1.reshape(-1,1,1,pvx_test1.shape[3])

sh=pvx_train1.shape[1:]
def RNmodel():
    model=Sequential()  
    model.add(GlobalAveragePooling2D(input_shape=sh))   
    model.add(Dense(2048))
    model.add(LeakyReLU(alpha=.02))
    model.add(Dropout(.25)) 
    model.add(Dense(512))
  bottle_neck = model.predict(preprocess_input(res1),verbose=1)
  prediction = int(np.argmax(model1.predict(bottle_neck),axis=1))
  ax.set_title("I think it is "+dog_names[prediction])

Breed("test/test2.jpg")

"""# Using ResNet152V2"""

from keras.applications.resnet_v2 import ResNet152V2
from keras.applications.resnet_v2 import preprocess_input
from keras.preprocessing import image
from keras.layers import Input,Conv2D,MaxPooling2D,Dense,Dropout,BatchNormalization
from keras.models import Sequential

input_ = Input(shape=(224,224,3))
model_2 = ResNet152V2(include_top=False,weights='imagenet',input_tensor=input_)
model_2.summary()
#I have cleared the output, because the model was too+++ deep and you would have to scroll for some time .

def createdatasets_resnet(dataset):
  data_set = np.zeros([dataset.shape[0],224,224,3])
  for i,image_arr in enumerate(dataset):
    img = cv2.imread(image_arr)
    res = cv2.resize(img, dsize=(224, 224), interpolation=cv2.INTER_CUBIC)
    data_set[i,:,:,:] = res
  return data_set

bottle_neck_train = model_2.predict(preprocess_input(createdatasets_resnet(train_files)),verbose=1)

bottle_neck_test =  model_2.predict(preprocess_input(createdatasets_resnet(test_files)),verbose=1)
def load_model(dim_size=224):
    input_tensor = Input(shape=(dim_size, dim_size, 3))
    model = ResNet152V2(input_tensor=input_tensor, weights=None, classes=7)
    model.load_weights('resnet_weights320.h5', by_name=False)
    return model
Exemple #17
0
from keras.applications.resnet_v2 import ResNet152V2
from keras.preprocessing import image
from keras.applications.resnet_v2 import preprocess_input, decode_predictions
from keras.layers import Input
import numpy as np
import tensorflow as tf

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.keras.backend.set_session(tf.Session(config=config))

dim_size = 224
input_tensor = Input(shape=(dim_size, dim_size, 3))

model = ResNet152V2(input_tensor=input_tensor, weights='imagenet')
#model = ResNet152V2(input_tensor=input_tensor, weights=None, classes=7)
#model.load_weights('resnet_weights.h5', by_name=False)

img_path = 'tiger.jpg'
img = image.load_img(img_path, target_size=(dim_size, dim_size))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

preds = model.predict(x)
# decode the results into a list of tuples (class, description, probability)
# (one such list for each sample in the batch)
print('Predicted:', decode_predictions(preds, top=5))
# Predicted: 
# [(u'n02504013', u'Indian_elephant', 0.82658225), 
# (u'n01871265', u'tusker', 0.1122357), 
plt.plot(history4.history['loss'])
plt.plot(history4.history['val_loss'])
plt.title('Inception Resnet model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper right')
plt.savefig('inception-resnet_loss')
plt.show()



"""## ResNet152V2"""

from keras.applications.resnet_v2 import ResNet152V2

resnet152 = ResNet152V2(include_top=False, weights='imagenet')

resnet152.summary()

x = resnet152.output
x = GlobalAveragePooling2D()(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.3)(x)
predictions = Dense(4, activation='softmax')(x)

model = Model(inputs=resnet152.input, outputs=predictions)

for layer in resnet152.layers:
    layer.trainable = False

model.compile(loss='categorical_crossentropy',
Exemple #19
0
def Build_Model_ResNet(px_train ,  pSessionParameters , pTrainingParameters ):
    
    from keras.applications.resnet import ResNet50
    from keras.applications.resnet import ResNet101
    from keras.applications.resnet import ResNet152
    
    from keras.applications.resnet_v2 import ResNet50V2
    from keras.applications.resnet_v2 import ResNet101V2
    from keras.applications.resnet_v2 import ResNet152V2
    

    
    from keras.layers import Input
       
    # Builds a new ResNet model
    ''' 
    Input parameters:
      px_train: training data to be used to set the input shape of the model
      pModelBuildParameters: Dict of Parameters to define how the model is built.

    Return parameters: model

    '''    
    BatchNormFlag = pSessionParameters['BatchNorm']     
 
    NoClasses = pSessionParameters['ModelBuildParameters']['NoClasses']
    Activation = pSessionParameters['ModelBuildParameters']['Activation']
    IncludeTopFlag = pSessionParameters['ModelBuildParameters']['IncludeTop']
    Model = pSessionParameters['ModelBuildParameters']['Model']
    Version = pSessionParameters['ModelBuildParameters']['Version'] 
    
    if IncludeTopFlag:
        if Version==1:
            if 'ResNet50' in Model:                
                conv_base = ResNet50(input_shape=(px_train.shape[1:]), weights=None, include_top=True , classes = NoClasses, pooling='avg')           
            elif 'ResNet101' in Model:
                conv_base = ResNet101(input_shape=(px_train.shape[1:]), weights=None, include_top=True , classes = NoClasses, pooling='avg')           
            elif 'ResNet152' in Model:
                conv_base = ResNet152(input_shape=(px_train.shape[1:]), weights=None, include_top=True , classes = NoClasses, pooling='avg')           
        else: # Version 2
            if 'ResNet50' in Model:                
                conv_base = ResNet50V2(input_shape=(px_train.shape[1:]), weights=None, include_top=True , classes = NoClasses, pooling='avg')           
            elif 'ResNet101' in Model:
                conv_base = ResNet101V2(input_shape=(px_train.shape[1:]), weights=None, include_top=True , classes = NoClasses, pooling='avg')           
            elif 'ResNet152' in Model:
                conv_base = ResNet152V2(input_shape=(px_train.shape[1:]), weights=None, include_top=True , classes = NoClasses, pooling='avg')           
                        
        model = models.Sequential()
        model.add(conv_base)    
    else:
        if Version==1:
            if 'ResNet50' in Model:                
                conv_base = ResNet50(input_shape=(px_train.shape[1:]), weights=None, include_top=False , classes = NoClasses, pooling='avg')           
            elif 'ResNet101' in Model:
                conv_base = ResNet101(input_shape=(px_train.shape[1:]), weights=None, include_top=False , classes = NoClasses, pooling='avg')           
            elif 'ResNet152' in Model:
                conv_base = ResNet152(input_shape=(px_train.shape[1:]), weights=None, include_top=False , classes = NoClasses, pooling='avg')           
        else: # Version 2
            if 'ResNet50' in Model:                
                conv_base = ResNet50V2(input_shape=(px_train.shape[1:]), weights=None, include_top=False , classes = NoClasses, pooling='avg')           
            elif 'ResNet101' in Model:
                conv_base = ResNet101V2(input_shape=(px_train.shape[1:]), weights=None, include_top=False , classes = NoClasses, pooling='avg')           
            elif 'ResNet152' in Model:
                conv_base = ResNet152V2(input_shape=(px_train.shape[1:]), weights=None, include_top=False , classes = NoClasses, pooling='avg')           
                
        model = models.Sequential()
        model.add(conv_base)    

        # Add Dense Layers and Dropout and BatchNorm layers based on ModelBuildParameters
        model = Build_Model_AddLayers(model , pSessionParameters )
        model.add(layers.Dense(NoClasses, activation=Activation, name='dense_class'))        
    
    
    return model