コード例 #1
0
def build_model():
    """
    Loads the MobileNetV2 model for keras. Adds new dense and dropout layers to the output.
    :return: the model
    """
    input_tensor = Input(shape=(target_size, target_size, 3))
    base_model = MobileNetV2(
        include_top=False,
        weights='imagenet',
        input_tensor=input_tensor,
        input_shape=(target_size, target_size, 3),
        pooling='avg')

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

    op = Dense(256, activation='relu')(base_model.output)
    op = Dropout(.25)(op)

    ##
    # softmax: calculates a probability for every possible class.
    #
    # activation='softmax': return the highest probability;
    # for example, if 'Coat' is the highest probability then the result would be
    # something like [0,0,0,0,1,0,0,0,0,0] with 1 in index 5 indicate 'Coat' in our case.
    ##
    output_tensor = Dense(4, activation='softmax')(op)

    model = Model(inputs=input_tensor, outputs=output_tensor)

    return model
コード例 #2
0
 def __init__(self):
     self.input_size = 96
     base = MobileNetV2(input_shape=(96, 96, 3), include_top=False, weights=os.path.dirname(os.path.abspath(__file__))+'/weight/mobilenetv2/mobilenet_v2_weights_tf_dim_ordering_tf_kernels_1.0_96_no_top.h5')
     top_layer = GlobalAveragePooling2D()(base.output)
     gender_layer = Dense(2, activation='softmax', name='gender_prediction')(top_layer)
     age_layer = Dense(101, activation='softmax', name='age_prediction')(top_layer)
     super().__init__(inputs=base.input, outputs=[gender_layer, age_layer], name='AgenderNetMobileNetV2')
コード例 #3
0
def create_tf_facedetection_mobilenetv2(size, alpha):
    input_tensor = Input(shape=(size, size, 3))
    output_tensor = MobileNetV2(weights=None,
                                include_top=False,
                                input_tensor=input_tensor,
                                alpha=alpha).output
    output_tensor = ZeroPadding2D()(output_tensor)
    output_tensor = Conv2D(kernel_size=(3, 3), filters=5)(output_tensor)

    return Model(inputs=input_tensor, outputs=output_tensor)
コード例 #4
0
def load_mobilenetv2_224_075_detector(path):
    input_tensor = Input(shape=(224, 224, 3))
    output_tensor = MobileNetV2(weights=None,
                                include_top=False,
                                input_tensor=input_tensor,
                                alpha=0.75).output
    output_tensor = ZeroPadding2D()(output_tensor)
    output_tensor = Conv2D(kernel_size=(3, 3), filters=5)(output_tensor)

    model = Model(inputs=input_tensor, outputs=output_tensor)
    model.load_weights(path)

    return model
コード例 #5
0
def make_model():
    # create base model
    base_model = MobileNetV2(include_top=False, weights="imagenet", input_shape=(224, 224, 3))

    # create main model
    inputs = keras.Input(shape=(224, 224, 3))
    x = base_model(inputs, training=False)
    # Add some new fully connected layers to
    x = GlobalAveragePooling2D()(x)
    x = Dropout(0.2)(x)
    x = Dense(num_classes, activation='softmax')(x)

    models = Model(inputs=inputs, outputs=x, name="Plant_Disease_MobileNet")
    return models
コード例 #6
0
    def __init__(self, model, info):
        self.info = info

        possible_model = {
            "Small": self.getSmallModel(),
            "MobileNetV2": MobileNetV2(),
            "Resnet50": ResNet50(weights=None, classes=self.info.features['label'].num_classes),
            "Resnet200": ResNet152V2(weights=None, include_top=False),
            "VGG": VGG16(weights=None, include_top=False, classes=self.info.features['label'].num_classes),
            "DenseNet": DenseNet121(),
            "Cifarnet": self.cifarnet(),
            "Inception": InceptionV3(),
            "CNN": self.getCNN()
        }

        assert model in possible_model.keys(), "Selected model not available"
        self.model = possible_model[model]
コード例 #7
0
ファイル: model.py プロジェクト: sr-airtc/BasicESRGAN
 def get_model(self, model_name, weights):
     if model_name == 'InceptionV3':
         from tensorflow.python.keras.applications.inception_v3 import InceptionV3
         base_model = InceptionV3(weights=weights, include_top=False)
     elif model_name == 'NASNetLarge':
         from tensorflow.python.keras.applications.nasnet import NASNetLarge
         base_model = NASNetLarge(weights=weights, include_top=False)
     elif model_name == 'DenseNet201':
         from tensorflow.python.keras.applications.densenet import DenseNet201
         base_model = DenseNet201(weights=weights, include_top=False)
     elif model_name == 'Xception':
         from tensorflow.python.keras.applications.xception import Xception
         base_model = Xception(weights=weights, include_top=False)
     elif model_name == 'VGG16':
         from tensorflow.python.keras.applications.vgg16 import VGG16
         base_model = VGG16(weights=weights, include_top=False)
     elif model_name == 'VGG19':
         from tensorflow.python.keras.applications.vgg19 import VGG19
         base_model = VGG19(weights=weights, include_top=False)
     elif model_name == 'NASNetMobile':
         from tensorflow.python.keras.applications.nasnet import NASNetMobile
         base_model = NASNetMobile(weights=weights, include_top=False)
     elif model_name == 'MobileNetV2':
         from tensorflow.python.keras.applications.mobilenet_v2 import MobileNetV2
         base_model = MobileNetV2(weights=weights, include_top=False)
     elif model_name == 'ResNet50':
         from tensorflow.python.keras.applications.resnet50 import ResNet50
         base_model = ResNet50(weights=weights, include_top=False)
     elif model_name == 'InceptionResNetV2':
         from tensorflow.python.keras.applications.inception_resnet_v2 import InceptionResNetV2
         base_model = InceptionResNetV2(weights=weights, include_top=False, )
     else:
         raise KeyError('Unknown network.')
     x = base_model.output
     x = GlobalAveragePooling2D()(x)
     x = Dense(512, activation='relu')(x)
     predictions = Dense(1, activation='sigmoid')(x)
     model = Model(inputs=base_model.input, outputs=predictions)
     return model
コード例 #8
0
ファイル: siamese_model.py プロジェクト: mx0551/IQA
 def get_model(self, model_name, weights='imagenet'):
     if model_name == 'InceptionV3':
         from tensorflow.python.keras.applications.inception_v3 import InceptionV3
         base_model = InceptionV3(weights=weights, include_top=False)
     elif model_name == 'NASNetLarge':
         from tensorflow.python.keras.applications.nasnet import NASNetLarge
         base_model = NASNetLarge(weights=weights, include_top=False)
     elif model_name == 'DenseNet201':
         from tensorflow.python.keras.applications.densenet import DenseNet201
         base_model = DenseNet201(weights=weights, include_top=False)
     elif model_name == 'Xception':
         from tensorflow.python.keras.applications.xception import Xception
         base_model = Xception(weights=weights, include_top=False)
     elif model_name == 'VGG19':
         from tensorflow.python.keras.applications.vgg19 import VGG19
         base_model = VGG19(weights=weights, include_top=False)
     elif model_name == 'NASNetMobile':
         from tensorflow.python.keras.applications.nasnet import NASNetMobile
         base_model = NASNetMobile(weights=weights, include_top=False)
     elif model_name == 'MobileNetV2':
         from tensorflow.python.keras.applications.mobilenet_v2 import MobileNetV2
         base_model = MobileNetV2(weights=weights, include_top=False)
     elif model_name == 'ResNet50':
         from tensorflow.python.keras.applications.resnet50 import ResNet50
         base_model = ResNet50(weights=weights, include_top=False)
     elif model_name == 'InceptionResNetV2':
         from tensorflow.python.keras.applications.inception_resnet_v2 import InceptionResNetV2
         base_model = InceptionResNetV2(weights=weights, include_top=False)
     else:
         raise KeyError('Unknown network.')
     x = base_model.output
     x = GlobalAveragePooling2D()(x)
     # x = Dense(1024, activation='relu')(x)
     output = Dense(1, activation='sigmoid')(x)
     # output = SiameseLossLayer(self.batch_size, self.num_distort, self.num_level)(x)
     model = Model(inputs=base_model.input, outputs=output)
     self.name = model_name
     return model
def pre_trained_model():
    print("Building model with", "MobileNetV2")
    model = Sequential()

    model.add(MobileNetV2(include_top=False, pooling='avg',
                          weights="imagenet"))
    model.add(Flatten())
    model.add(BatchNormalization())
    model.add(Dense(2048, activation='relu'))
    model.add(BatchNormalization())
    model.add(Dense(1024, activation='relu'))
    model.add(BatchNormalization())
    model.add(Dense(len(labels), activation='softmax'))

    model.layers[0].trainable = False

    opt = tf.keras.optimizers.Adam(1e-4)
    opt = tf.train.experimental.enable_mixed_precision_graph_rewrite(opt)
    model.compile(optimizer=opt,
                  loss='categorical_crossentropy',
                  metrics=['acc'])

    return model
コード例 #10
0
from tensorflow.python.keras.applications.inception_v3 import decode_predictions as decodeInception

from helpers import classify_image, read_labels, set_input_tensor
import tensorflow as tf
###############################################################################################################3

#Δήλωση
app = FastAPI()

#Δήλωση μοντέλων μηχανικής μάθησης και οι αντίστοιχες ρυθμίσεις τους
modelRes = ResNet50(weights='imagenet')
modelVGG = VGG16(weights='imagenet', include_top=True)
modelEfficient = EfficientNetB0(include_top=True, weights='imagenet')
modelEfficientB7 = EfficientNetB7(include_top=True, weights='imagenet')
modelNasNet = NASNetLarge(include_top=True, weights='imagenet')
modelMobileNet = MobileNetV2(weights="imagenet", include_top=True)
modelXception = Xception(include_top=True, weights="imagenet")
modelInception = InceptionV3(include_top=True,
                             weights="imagenet",
                             classifier_activation="softmax")
modelInRes = InceptionResNetV2(weights="imagenet", include_top=True)

# Settings
MIN_CONFIDENCE = 0.1  # Το ελάχιστο δυνατό confidence που δέχόμαστε απο τα μοντέλα.

# Τα URLs που θα απαντάει το κάθε μοντέλο
IMAGE_URL2 = "/v1/vision/resNet"
IMAGE_URL3 = "/v1/vision/vggNet"
IMAGE_URL4 = "/v1/vision/efficientNet"
IMAGE_URL5 = "/v1/vision/nasNet"
IMAGE_URL6 = "/v1/vision/mobileNet2"
コード例 #11
0
                       output=base_model.get_layer('custom').output)
     image_size = (299, 299)
 elif model_name == "inceptionresnetv2":
     base_model = InceptionResNetV2(include_top=include_top,
                                    weights=weights,
                                    input_tensor=Input(shape=(299, 299, 3)))
     try:
         model = Model(base_model.input,
                       base_model.get_layer('custom').output)
     except:
         model = Model(input=base_model.input,
                       output=base_model.get_layer('custom').output)
     image_size = (299, 299)
 elif model_name == "mobilenet":
     base_model = MobileNetV2(include_top=include_top,
                              weights=weights,
                              input_tensor=Input(shape=(224, 224, 3)),
                              input_shape=(224, 224, 3))
     try:
         model = Model(base_model.input,
                       base_model.get_layer('custom').output)
     except:
         model = Model(input=base_model.input,
                       output=base_model.get_layer('custom').output)
     image_size = (224, 224)
 elif model_name == "xception":
     base_model = Xception(weights=weights)
     try:
         model = Model(base_model.input,
                       base_model.get_layer('avg_pool').output)
     except:
         model = Model(input=base_model.input,
コード例 #12
0
# -*- coding: utf-8 -*-
"""
Created on Sat Apr  6 15:51:57 2019

@author: tak
"""
from tensorflow.python.keras.applications.mobilenet_v2 import MobileNetV2
from tensorflow.python.keras.applications.mobilenet_v2 import decode_predictions
from tensorflow.python.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.python.keras.preprocessing.image import load_img
from tensorflow.python.keras.preprocessing.image import img_to_array
import numpy as np

model = MobileNetV2()
model.summary()

model.save('mobilenetv2.h5')

img_dog = load_img('dog.jpg', target_size=(224, 224))
arr_dog = preprocess_input(img_to_array(img_dog))

arr_input = np.stack([arr_dog, ])

probs = model.predict(arr_input)
results = decode_predictions(probs)

print(results[0])

コード例 #13
0
ファイル: model.py プロジェクト: anhydrous99/EAST
    def __init__(self, input_size=512):
        scaled_input_size = input_size / 2
        input_image = Input(shape=(input_size, input_size, 3),
                            name='input_image')
        overly_small_text_region_training_mask = Input(
            shape=(input_size // 4, input_size // 4, 1),
            name='overly_small_text_region_training_mask')
        text_region_boundary_training_mask = Input(
            shape=(input_size // 4, input_size // 4, 1),
            name='text_region_boundary_training_mask')
        target_score_map = Input(shape=(input_size // 4, input_size // 4, 1),
                                 name='target_score_map')
        mobilenetv2 = MobileNetV2(input_tensor=input_image,
                                  input_shape=(input_size, input_size, 3),
                                  weights='imagenet',
                                  include_top=False,
                                  pooling=None)
        x = mobilenetv2.get_layer('out_relu').output

        x = Lambda(resize_bilinear,
                   output_shape=(input_size // 16, input_size // 16, 1280),
                   name='resize_1')(x)
        x = Reshape((input_size // 16, input_size // 16, 1280))(x)
        x = concatenate(
            [x, mobilenetv2.get_layer('block_13_expand_relu').output], axis=3)
        x = Conv2D(128, (1, 1),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)
        x = Conv2D(128, (3, 3),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)

        x = Lambda(resize_bilinear,
                   output_shape=(input_size // 8, input_size // 8, 128),
                   name='resize_2')(x)
        x = Reshape((input_size // 8, input_size // 8, 128))(x)
        x = concatenate(
            [x, mobilenetv2.get_layer('block_6_expand_relu').output], axis=3)
        x = Conv2D(64, (1, 1),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)
        x = Conv2D(64, (3, 3),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)

        x = Lambda(resize_bilinear,
                   output_shape=(input_size // 4, input_size // 4, 64),
                   name='resize_3')(x)
        x = Reshape((input_size // 4, input_size // 4, 64))(x)
        x = concatenate(
            [x, mobilenetv2.get_layer('block_3_expand_relu').output], axis=3)
        x = Conv2D(32, (1, 1),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)
        x = Conv2D(32, (3, 3),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)

        x = Conv2D(32, (3, 3),
                   padding='same',
                   kernel_regularizer=regularizers.l2(1e-5))(x)
        x = BatchNormalization(momentum=0.997,
                               epsilon=1e-5,
                               scale=True,
                               fused=False)(x)
        x = ReLU(6.)(x)

        pred_score_map = Conv2D(1, (1, 1),
                                activation=tf.nn.tanh,
                                name='pred_score_map')(x)
        pred_score_map = Lambda(lambda x: (x + 1) * 0.5)(pred_score_map)
        rbox_geo_map = Conv2D(4, (1, 1),
                              activation=tf.nn.tanh,
                              name='rbox_geo_map')(x)
        rbox_geo_map = Lambda(lambda x: (x + 1) * scaled_input_size)(
            rbox_geo_map)
        angle_map = Conv2D(1, (1, 1),
                           activation=tf.nn.tanh,
                           name='rbox_angle_map')(x)
        angle_map = Lambda(lambda x: 0.7853981633974483 * x)(angle_map)
        pred_geo_map = concatenate([rbox_geo_map, angle_map],
                                   axis=3,
                                   name='pred_geo_map')

        model = Model(inputs=[
            input_image, overly_small_text_region_training_mask,
            text_region_boundary_training_mask, target_score_map
        ],
                      outputs=[pred_score_map, pred_geo_map])

        self.model = model
        self.input_image = input_image
        self.overly_small_text_region_training_mask = overly_small_text_region_training_mask
        self.text_region_boundary_training_mask = text_region_boundary_training_mask
        self.target_score_map = target_score_map
        self.pred_score_map = pred_score_map
        self.pred_geo_map = pred_geo_map
コード例 #14
0
 def download_for_url(self, path: str, **kwargs):
     """
     Download the file at the given URL
     :param path:  the path to download
     :param kwargs:  various kwargs for customizing the underlying behavior of
     the model download and setup
     :return: the absolute path to the model
     """
     path_split = path.split('/')
     type = path_split[0]
     weights_file = path_split[1]
     include_top = 'no_top' in weights_file
     if type == 'vgg19':
         ret = VGG19(include_top=include_top, **kwargs)
     elif type == 'vgg16':
         ret = VGG16(include_top=include_top, **kwargs)
     elif type == 'resnet50':
         ret = ResNet50(include_top=include_top, **kwargs)
     elif type == 'resnet101':
         ret = ResNet101(include_top=include_top, **kwargs)
     elif type == 'resnet152':
         ret = ResNet152(include_top=include_top, **kwargs)
     elif type == 'resnet50v2':
         ret = ResNet50V2(include_top=include_top, **kwargs)
     elif type == 'resnet101v2':
         ret = ResNet101V2(include_top=include_top, **kwargs)
     elif type == 'resnet152v2':
         ret = ResNet152V2(include_top=include_top, **kwargs)
     elif type == 'densenet121':
         ret = DenseNet121(include_top=include_top)
     elif type == 'densenet169':
         ret = DenseNet169(include_top=include_top, **kwargs)
     elif type == 'densenet201':
         ret = DenseNet201(include_top=include_top, **kwargs)
     elif type == 'inceptionresnetv2':
         ret = InceptionResNetV2(include_top=include_top, **kwargs)
     elif type == 'efficientnetb0':
         ret = EfficientNetB0(include_top=include_top, **kwargs)
     elif type == 'efficientnetb1':
         ret = EfficientNetB1(include_top=include_top, **kwargs)
     elif type == 'efficientnetb2':
         ret = EfficientNetB2(include_top=include_top, **kwargs)
     elif type == 'efficientnetb3':
         ret = EfficientNetB3(include_top=include_top, **kwargs)
     elif type == 'efficientnetb4':
         ret = EfficientNetB4(include_top=include_top, **kwargs)
     elif type == 'efficientnetb5':
         ret = EfficientNetB5(include_top=include_top, **kwargs)
     elif type == 'efficientnetb6':
         ret = EfficientNetB6(include_top=include_top, **kwargs)
     elif type == 'efficientnetb7':
         efficient_net = EfficientNetB7(include_top=include_top, **kwargs)
     elif type == 'mobilenet':
         ret = MobileNet(include_top=include_top, **kwargs)
     elif type == 'mobilenetv2':
         ret = MobileNetV2(include_top=include_top)
     #  MobileNetV3() missing 2 required positional arguments: 'stack_fn' and 'last_point_ch'
     #elif type == 'mobilenetv3':
     #    mobile_net = MobileNetV3(include_top=include_top, **kwargs)
     elif type == 'inceptionv3':
         ret = InceptionV3(include_top=include_top, **kwargs)
     elif type == 'nasnet':
         ret = NASNetLarge(include_top=include_top, **kwargs)
     elif type == 'nasnet_mobile':
         ret = NASNetMobile(include_top=include_top, **kwargs)
     elif type == 'xception':
         ret = Xception(include_top=include_top, **kwargs)
     model_path = os.path.join(keras_path, weights_file)
     ret.save(model_path)
     return model_path
コード例 #15
0
    def train():
        print(Messages.TRAINER_START)

        data = []
        labels = []

        Trainer.insert_base_images()

        for person in an_connector.persons:
            for entry in database_connector.get(person.objectGUID):
                image = ImageUtility.bin_to_np_arr(entry['data'])
                data.append(image)
                labels.append(person.objectGUID)

        data = np.array(data, dtype='float32')
        labels = np.array(labels)

        lb = LabelBinarizer()
        labels = lb.fit_transform(labels)

        (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.25, random_state=42)

        # If SSL exception occurs, run `Install Certificates.command` inside Applications/Python X
        aug = ImageDataGenerator(rotation_range=20, zoom_range=0.15, width_shift_range=0.2, height_shift_range=0.2,
                                 shear_range=0.15, horizontal_flip=True, fill_mode='nearest')
        base_model = MobileNetV2(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)))

        head_model = base_model.output
        head_model = AveragePooling2D(pool_size=(7, 7))(head_model)
        head_model = Flatten(name='flatten')(head_model)
        head_model = Dense(128, activation='relu')(head_model)
        head_model = Dropout(0.5)(head_model)
        head_model = Dense(len(labels), activation='softmax')(head_model)

        model = Model(inputs=base_model.input, outputs=head_model)
        # print(model.summary())

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

        print('Compiling model ... \n')
        opt = Adam(lr=Trainer.INIT_LR, decay=Trainer.INIT_LR / Trainer.EPOCHS)
        model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

        # Needs depth of 3, received 1
        print('Training head ... \n')
        head = model.fit(x=aug.flow(trainX, trainY, batch_size=Trainer.BS), validation_data=(testX, testY),
                         steps_per_epoch=len(trainX) // Trainer.BS, epochs=Trainer.EPOCHS)

        print('Evaluating network ... \n')
        pred_idxs = model.predict(testX, batch_size=Trainer.BS)
        pred_idxs = np.argmax(pred_idxs, axis=1)

        # print(classification_report(testY.argmax(axis=1), pred_idxs, target_names=lb.classes_))

        print('Saving mask detector model ... \n')
        model.save('mask_detector.model', save_format='h5')

        plt.style.use('ggplot')
        plt.figure()
        plt.plot(np.arange(0, Trainer.EPOCHS), head.history['loss'], label='train_loss')
        plt.plot(np.arange(0, Trainer.EPOCHS), head.history['val_loss'], label='valuation_loss')
        plt.plot(np.arange(0, Trainer.EPOCHS), head.history['accuracy'], label='train_acc')
        plt.plot(np.arange(0, Trainer.EPOCHS), head.history['val_accuracy'], label='valuation_acc')
        plt.title('Training Loss and Accuracy')
        plt.xlabel('Epoch #')
        plt.ylabel('Loss/Accuracy')
        plt.legend(loc='lower left')
        plt.savefig('plot.png')

        print(Messages.TRAINER_FINISH)
コード例 #16
0
ファイル: fitOnBatch.py プロジェクト: 69kosh/streamPy
    def createModelMNV24(self, inputShape=(320, 320), outputShape=1):

        baseModel = MobileNetV2(include_top=False,
                                weights=None,
                                alpha=1,
                                input_shape=(inputShape[0], inputShape[1], 3))

        l1 = 0  #.001
        l2 = 0  #.001#.0001

        dropout = 0.25

        out1 = baseModel.get_layer('block_3_expand_relu').output

        out1 = Conv2D(128, (1, 1),
                      padding='valid',
                      activity_regularizer=regularizers.l1_l2(l1, l2))(out1)
        out1 = BatchNormalization()(out1)
        out1 = Activation('relu')(out1)

        out1 = MaxPooling2D((8, 8))(out1)
        out1 = Dropout(dropout)(out1)

        out2 = baseModel.get_layer('block_6_expand_relu').output

        out2 = Conv2D(128, (1, 1),
                      padding='valid',
                      activity_regularizer=regularizers.l1_l2(l1, l2))(out2)
        out2 = BatchNormalization()(out2)
        out2 = Activation('relu')(out2)

        out2 = MaxPooling2D((4, 4))(out2)
        out2 = Dropout(dropout)(out2)

        out3 = baseModel.get_layer('block_13_expand_relu').output

        out3 = Conv2D(256, (1, 1),
                      padding='valid',
                      activity_regularizer=regularizers.l1_l2(l1, l2))(out3)
        out3 = BatchNormalization()(out3)
        out3 = Activation('relu')(out3)

        out3 = MaxPooling2D((2, 2))(out3)
        out3 = Dropout(dropout)(out3)

        out4 = baseModel.get_layer('out_relu').output

        out4 = Conv2D(512, (1, 1),
                      padding='valid',
                      activity_regularizer=regularizers.l1_l2(l1, l2))(out4)
        out4 = BatchNormalization()(out4)
        out4 = Activation('relu')(out4)

        out4 = Dropout(dropout)(out4)

        out = Concatenate(axis=3)([out1, out2, out3, out4])

        #     out = Conv2D(512, (1, 1), padding='valid',
        #                   activity_regularizer=regularizers.l1_l2(l1, l2))(out)
        #     out = BatchNormalization()(out)
        #     out = Activation('relu')(out)
        #     out = Dropout(dropout)(out)

        out = Conv2D(256, (1, 1),
                     padding='valid',
                     activity_regularizer=regularizers.l1_l2(l1, l2))(out)
        out = BatchNormalization()(out)
        out = Activation('relu')(out)
        out = Dropout(dropout)(out)

        out = MaxPooling2D((2, 2))(out)
        out = Flatten()(out)
        #    out = GlobalMaxPool2D()(out)

        #     out = baseModel.output

        out = Dense(256, activity_regularizer=regularizers.l1_l2(l1, l2))(out)
        out = BatchNormalization()(out)
        out = Activation('relu')(out)
        out = Dropout(dropout)(out)

        out = Dense(256, activity_regularizer=regularizers.l1_l2(l1, l2))(out)
        out = BatchNormalization()(out)
        out = Activation('relu')(out)
        out = Dropout(dropout)(out)

        out = Dense(outputShape)(out)
        out = Activation('sigmoid')(out)

        model = Model(inputs=baseModel.input, outputs=out)

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

        model.summary()
        return model
コード例 #17
0
for x,y in zip(X,Y):
   for i in x:
      raw_data.append((i,label_dict[int(y-1)]))

data = []
sample_size = 1600  
counts = [0 for i in range(5)]
for i in raw_data:
  for label in range(5):
     if(i[1]==label_dict[label] and counts[label]<sample_size):
       data.append(i)
       counts[label] += 1
  

#Creating the Model by concatenating it with the pre-trained model
frozen_model = MobileNetV2(include_top=False, weights='imagenet')
x = frozen_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
x = Dropout(0.2)(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.2)(x)
x = Dense(128, activation='relu')(x)
x = Dense(16, activation='relu')(x)
predictions = Dense(5, activation='softmax')(x)
model = Model(inputs=frozen_model.input, outputs=predictions)


#Freezing the convolutional layers
for layer in frozen_model.layers:
    layer.trainable = False
コード例 #18
0
    log_dir, checkpoints = keras_helper.ask_what_to_do_with_logfiles(
        log_dir='logs/mobilenet/',
        ckpt="checkpoints/mobilenet/{epoch:02d}.ckpt")

    dg = keras_helper.DataGenerators(
        train_path="../../Dataset/sample_sizes/64_images/",
        test_path="../../Dataset/test/",
        enable_augmentation=True,
        preprocessing_fn=preprocess_input)
    train_generator, test_generator, tensorboard_generator = dg.create_data_generators(
        224)
    train_samples, test_samples = dg.get_samples()
    batch_size = dg.get_batch_size()

    model = keras_helper.create_model(
        MobileNetV2(input_shape=(224, 224, 3), include_top=False))
    model.compile(Adam(lr=0.0005),
                  loss="categorical_crossentropy",
                  metrics=["accuracy", keras_helper.top_3_acc])

    print(model.summary())

    tensorboard_callback = keras_callbacks.TensorBoardImage(log_dir=log_dir,
                                                            model=model,
                                                            DataGenerator=dg)
    checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(checkpoints,
                                                             period=20)

    model.fit_generator(train_generator,
                        steps_per_epoch=train_samples // batch_size,
                        epochs=100,