training_data = training_data_generator.flow_from_directory(
    "/content/drive/My Drive/Colabbar Tags Data/Images",
    batch_size=32,
    target_size=(300, 300),
    subset="training",
    class_mode='categorical')
validation_data = training_data_generator.flow_from_directory(
    "/content/drive/My Drive/Colabbar Tags Data/Images",
    batch_size=32,
    target_size=(300, 300),
    subset="validation",
    class_mode='categorical')

#Model definition
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=(5, 5), activation="relu", input_shape=(300, 300, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=32, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=64, kernel_size=(5, 5), activation="relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters=64, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
def puigcerver_octconv(input_size, d_model):
    """
    Octave CNN by khinggan, architecture is same as puigcerver
    """

    alpha = 0.25
    input_data = Input(name="input", shape=input_size)
    high = input_data
    low = tf.keras.layers.AveragePooling2D(2)(input_data)

    high, low = OctConv2D(filters=16, alpha=alpha)([high, low])
    high = BatchNormalization()(high)
    low = BatchNormalization()(low)
    high = LeakyReLU(alpha=0.01)(high)
    low = LeakyReLU(alpha=0.01)(low)
    high = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                        padding="valid")(high)
    low = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding="valid")(low)

    high, low = OctConv2D(filters=32, alpha=alpha)([high, low])
    high = BatchNormalization()(high)
    low = BatchNormalization()(low)
    high = LeakyReLU(alpha=0.01)(high)
    low = LeakyReLU(alpha=0.01)(low)
    high = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                        padding="valid")(high)
    low = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding="valid")(low)

    high = Dropout(rate=0.2)(high)
    low = Dropout(rate=0.2)(low)
    high = Conv2D(filters=48,
                  kernel_size=(3, 3),
                  strides=(1, 1),
                  padding="same")(high)
    low = Conv2D(filters=48,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(low)
    high = BatchNormalization()(high)
    low = BatchNormalization()(low)
    high = LeakyReLU(alpha=0.01)(high)
    low = LeakyReLU(alpha=0.01)(low)
    high = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                        padding="valid")(high)
    low = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding="valid")(low)

    high = Dropout(rate=0.2)(high)
    low = Dropout(rate=0.2)(low)
    high = Conv2D(filters=64,
                  kernel_size=(3, 3),
                  strides=(1, 1),
                  padding="same")(high)
    low = Conv2D(filters=64,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(low)
    high = BatchNormalization()(high)
    low = BatchNormalization()(low)
    high = LeakyReLU(alpha=0.01)(high)
    low = LeakyReLU(alpha=0.01)(low)

    high = Dropout(rate=0.2)(high)
    low = Dropout(rate=0.2)(low)
    high = Conv2D(filters=80,
                  kernel_size=(3, 3),
                  strides=(1, 1),
                  padding="same")(high)
    low = Conv2D(filters=80,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(low)
    high = BatchNormalization()(high)
    low = BatchNormalization()(low)
    high = LeakyReLU(alpha=0.01)(high)
    low = LeakyReLU(alpha=0.01)(low)

    x = _create_octconv_last_block([high, low], 80, alpha)

    shape = x.get_shape()
    blstm = Reshape((shape[1], shape[2] * shape[3]))(x)

    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)

    blstm = Dropout(rate=0.5)(blstm)
    output_data = Dense(units=d_model, activation="softmax")(blstm)

    return (input_data, output_data)
Exemple #3
0
from keras.layers.normalization import BatchNormalization

#Specifying input image shape

image_shape = (227, 227, 3)

#instantiating an empty model

np.random.seed(1000)

#Ceating the AlexNet DNN

model = Sequential([
    Conv2D(filters=96,
           kernel_size=(11, 11),
           strides=(4, 4),
           input_shape=(image_shape),
           activation="relu",
           padding='valid'),
    MaxPooling2D(pool_size=(3, 3), padding='valid', strides=(2, 2)),
    Conv2D(256, (5, 5), strides=(1, 1), padding='same', activation="relu"),
    MaxPooling2D(pool_size=(3, 3), strides=(2, 2)),
    Conv2D(384, (3, 3), strides=(1, 1), padding='same', activation="relu"),
    Conv2D(384, (3, 3), strides=(1, 1), padding='same', activation="relu"),
    Conv2D(256, (3, 3), strides=(1, 1), padding='same', activation="relu"),
    MaxPooling2D(pool_size=(3, 3), strides=(2, 2)),
    Flatten(),
    Dense(units=4096, activation="relu"),
    Dropout(rate=0.5),
    Dense(units=4096, activation="relu"),
    Dropout(rate=0.5),
    Dense(units=1000, activation="softmax"),
Exemple #4
0
import numpy as np
import cv2
import os
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

tf_model = Sequential()

tf_model.add(
    Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48, 48, 1)))
tf_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
tf_model.add(MaxPooling2D(pool_size=(2, 2)))
tf_model.add(Dropout(0.25))

tf_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
tf_model.add(MaxPooling2D(pool_size=(2, 2)))
tf_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
tf_model.add(MaxPooling2D(pool_size=(2, 2)))
tf_model.add(Dropout(0.25))

tf_model.add(Flatten())
tf_model.add(Dense(1024, activation='relu'))
tf_model.add(Dropout(0.5))
tf_model.add(Dense(7, activation='softmax'))

tf_model.load_weights('ai_data/model.h5')
facecasc = cv2.CascadeClassifier('ai_data/haarcascade_frontalface_default.xml')
def puigcerver(input_size, d_model):
    """
    Convolucional Recurrent Neural Network by Puigcerver et al.

    Reference:
        Joan Puigcerver.
        Are multidimensional recurrent layers really necessary for handwritten text recognition?
        In: Document Analysis and Recognition (ICDAR), 2017 14th
        IAPR International Conference on, vol. 1, pp. 67–72. IEEE (2017)

        Carlos Mocholí Calvo and Enrique Vidal Ruiz.
        Development and experimentation of a deep learning system for convolutional and recurrent neural networks
        Escola Tècnica Superior d’Enginyeria Informàtica, Universitat Politècnica de València, 2018
    """

    input_data = Input(name="input", shape=input_size)

    cnn = Conv2D(filters=16,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(input_data)
    cnn = BatchNormalization()(cnn)
    cnn = LeakyReLU(alpha=0.01)(cnn)
    cnn = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding="valid")(cnn)

    cnn = Conv2D(filters=32,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(cnn)
    cnn = BatchNormalization()(cnn)
    cnn = LeakyReLU(alpha=0.01)(cnn)
    cnn = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding="valid")(cnn)

    cnn = Dropout(rate=0.2)(cnn)
    cnn = Conv2D(filters=48,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(cnn)
    cnn = BatchNormalization()(cnn)
    cnn = LeakyReLU(alpha=0.01)(cnn)
    cnn = MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding="valid")(cnn)

    cnn = Dropout(rate=0.2)(cnn)
    cnn = Conv2D(filters=64,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(cnn)
    cnn = BatchNormalization()(cnn)
    cnn = LeakyReLU(alpha=0.01)(cnn)

    cnn = Dropout(rate=0.2)(cnn)
    cnn = Conv2D(filters=80,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same")(cnn)
    cnn = BatchNormalization()(cnn)
    cnn = LeakyReLU(alpha=0.01)(cnn)

    shape = cnn.get_shape()
    blstm = Reshape((shape[1], shape[2] * shape[3]))(cnn)

    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)
    blstm = Bidirectional(LSTM(units=256, return_sequences=True,
                               dropout=0.5))(blstm)

    blstm = Dropout(rate=0.5)(blstm)
    output_data = Dense(units=d_model, activation="softmax")(blstm)

    return (input_data, output_data)
# Creating the Test set
valid_set = test_datagen.flow_from_directory('images/validation',
                                            target_size = (48,48),
                                            batch_size = 32,
                                            color_mode='grayscale',
                                            class_mode = 'categorical')

# number of possible label values
n = 7
#print(dir(trainig_set))

# Initialising the CNN
model = Sequential()

# 1 - Convolution
model.add(Conv2D(32,(3,3), padding='same', input_shape=(48, 48,1)))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

# 2nd Convolution layer
model.add(Conv2D(64,(5,5), padding='same'))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

# 3rd Convolution layer
model.add(Conv2D(128,(3,3), padding='same'))
model.add(Activation('relu'))
Exemple #7
0
 def build(self, input_shapes):
     self.conv = Conv2D(filters=1,
                        kernel_size=self.size,
                        strides=1,
                        padding='same')
Exemple #8
0
def DeepSTN(
    H=32,
    W=32,
    channel=2,  #H-map_height W-map_width channel-map_channel
    c=3,
    p=1,
    t=1,  #c-closeness p-period t-trend
    pre_F=64,
    conv_F=64,
    R_N=2,  #pre_F-prepare_conv_featrue conv_F-resnet_conv_featrue R_N-resnet_number
    is_plus=True,  #use ResPlus or mornal convolution
    is_plus_efficient=False,  #use the efficient version of ResPlus
    plus=8,
    rate=2,  #rate-pooling_rate
    is_pt=True,  #use PoI and Time or not
    P_N=9,
    T_F=31,
    PT_F=9,
    T=24,  #P_N-poi_number T_F-time_feature PT_F-poi_time_feature T-T_times/day 
    drop=0,
    is_summary=True,  #show detail
    lr=0.0002,
    kernel1=1,  #kernel1 decides whether early-fusion uses conv_unit0 or conv_unit1, 1 recommended
    isPT_F=1
):  #isPT_F decides whether PT_model uses one more Conv after multiplying PoI and Time, 1 recommended

    all_channel = channel * (c + p + t)

    cut0 = int(0)
    cut1 = int(cut0 + channel * c)
    cut2 = int(cut1 + channel * p)
    cut3 = int(cut2 + channel * t)

    cpt_input = Input(shape=(H, W, all_channel))

    c_input = Lambda(cpt_slice, arguments={'h1': cut0, 'h2': cut1})(cpt_input)
    p_input = Lambda(cpt_slice, arguments={'h1': cut1, 'h2': cut2})(cpt_input)
    t_input = Lambda(cpt_slice, arguments={'h1': cut2, 'h2': cut3})(cpt_input)
    c_out1 = Conv2D(filters=pre_F, kernel_size=(1, 1), padding="same")(c_input)
    p_out1 = Conv2D(filters=pre_F, kernel_size=(1, 1), padding="same")(p_input)
    t_out1 = Conv2D(filters=pre_F, kernel_size=(1, 1), padding="same")(t_input)
    # print(t_out1.shape)
    if is_pt:
        poi_in = Input(shape=(P_N, H, W))
        # T_times/day + 7days/week
        time_in = Input(shape=(T + 7, H, W))

        PT_model = PT_trans('PT_trans', P_N, PT_F, T, T_F, H, W, isPT_F)

        poi_time = PT_model([poi_in, time_in])

        cpt_con1 = Concatenate(axis=-1)([c_out1, p_out1, t_out1, poi_time])
        # print("="*10)
        # print(c_out1.shape,p_out1.shape,t_out1.shape,poi_time.shape)
        # print(cpt_con1.shape)
        if kernel1:
            cpt = conv_unit1(pre_F * 3 + PT_F * isPT_F + P_N * (not isPT_F),
                             conv_F, drop, H, W)(cpt_con1)
        else:
            cpt = conv_unit0(pre_F * 3 + PT_F * isPT_F + P_N * (not isPT_F),
                             conv_F, drop, H, W)(cpt_con1)

    else:
        cpt_con1 = Concatenate(axis=1)([c_out1, p_out1, t_out1])
        if kernel1:
            cpt = conv_unit1(pre_F * 3, conv_F, drop, H, W)(cpt_con1)
        else:
            cpt = conv_unit0(pre_F * 3, conv_F, drop, H, W)(cpt_con1)

    if is_plus:
        if is_plus_efficient:
            for i in range(R_N):
                cpt = Res_plus_E('Res_plus_' + str(i + 1), conv_F, plus, rate,
                                 drop, H, W)(cpt)
        else:
            for i in range(R_N):
                cpt = Res_plus('Res_plus_' + str(i + 1), conv_F, plus, rate,
                               drop, H, W)(cpt)

    else:
        for i in range(R_N):
            cpt = Res_normal('Res_normal_' + str(i + 1), conv_F, drop, H,
                             W)(cpt)

    cpt_conv2 = Activation('relu')(cpt)
    cpt_out2 = BatchNormalization()(cpt_conv2)
    cpt_conv1 = Dropout(drop)(cpt_out2)
    cpt_conv1 = Conv2D(filters=channel, kernel_size=(1, 1),
                       padding="same")(cpt_conv1)
    cpt_out1 = Activation('tanh')(cpt_conv1)

    if is_pt:
        DeepSTN_model = Model(inputs=[cpt_input, poi_in, time_in],
                              outputs=cpt_out1)
    else:
        DeepSTN_model = Model(inputs=cpt_input, outputs=cpt_out1)

    DeepSTN_model.compile(loss='mse', optimizer='Adam', metrics=['mae'])

    DeepSTN_model.summary()

    return DeepSTN_model
Exemple #9
0
def build_model(img_shape: Tuple[int, int, int], num_classes: int,
                optimizer: tf.keras.optimizers.Optimizer, learning_rate: float,
                filter_block1: int, kernel_size_block1: int,
                filter_block2: int, kernel_size_block2: int,
                filter_block3: int, kernel_size_block3: int,
                dense_layer_size: int,
                kernel_initializer: tf.keras.initializers.Initializer,
                activation_cls: tf.keras.layers.Activation,
                dropout_rate: float, use_batch_normalization: bool,
                use_dense: bool, use_global_pooling: bool) -> Model:
    input_img = Input(shape=img_shape)

    x = Conv2D(filters=filter_block1,
               kernel_size=kernel_size_block1,
               padding="same",
               kernel_initializer=kernel_initializer,
               name="heatmap1")(input_img)
    if use_batch_normalization:
        x = BatchNormalization()(x)
    x = activation_cls(x)
    x = Conv2D(filters=filter_block1,
               kernel_size=kernel_size_block1,
               padding="same",
               kernel_initializer=kernel_initializer)(x)
    if use_batch_normalization:
        x = BatchNormalization()(x)
    if dropout_rate:
        x = Dropout(rate=dropout_rate)(x)
    x = activation_cls(x)
    x = MaxPool2D()(x)

    x = Conv2D(filters=filter_block2,
               kernel_size=kernel_size_block2,
               padding="same",
               kernel_initializer=kernel_initializer)(x)
    if use_batch_normalization:
        x = BatchNormalization()(x)
    x = activation_cls(x)
    x = Conv2D(filters=filter_block2,
               kernel_size=kernel_size_block2,
               padding="same",
               kernel_initializer=kernel_initializer)(x)
    if use_batch_normalization:
        x = BatchNormalization()(x)
    if dropout_rate:
        x = Dropout(rate=dropout_rate)(x)
    x = activation_cls(x)
    x = MaxPool2D()(x)

    x = Conv2D(filters=filter_block3,
               kernel_size=kernel_size_block3,
               padding="same",
               kernel_initializer=kernel_initializer)(x)
    if use_batch_normalization:
        x = BatchNormalization()(x)
    x = activation_cls(x)
    x = Conv2D(filters=filter_block3,
               kernel_size=kernel_size_block3,
               padding="same",
               kernel_initializer=kernel_initializer)(x)
    if use_batch_normalization:
        x = BatchNormalization()(x)
    if dropout_rate:
        x = Dropout(rate=dropout_rate)(x)
    x = activation_cls(x)
    x = MaxPool2D()(x)

    if use_global_pooling:
        x = GlobalAveragePooling2D()(x)
    else:
        x = Flatten()(x)
    if use_dense:
        x = Dense(units=dense_layer_size,
                  kernel_initializer=kernel_initializer)(x)
        if use_batch_normalization:
            x = BatchNormalization()(x)
        x = activation_cls(x)
    x = Dense(units=num_classes, kernel_initializer=kernel_initializer)(x)
    y_pred = Activation("softmax")(x)

    model = Model(inputs=[input_img], outputs=[y_pred])

    opt = optimizer(learning_rate=learning_rate)

    model.compile(loss="categorical_crossentropy",
                  optimizer=opt,
                  metrics=["accuracy"])

    return model
Exemple #10
0
input_shape = (32, 32, 3)

# downsampling to get image to same input size as model
img_array = resize(img_array, input_shape, anti_aliasing=True)
img_array = img_array.reshape(
    (1, img_array.shape[0], img_array.shape[1], img_array.shape[2]))

# the model is called modelo_ar

activator = 'relu'
optimizer = 'adam'

modelo_ar = Sequential()
modelo_ar.add(
    Conv2D(32, (3, 3),
           activation=activator,
           padding='same',
           input_shape=input_shape))
modelo_ar.add(Conv2D(32, (3, 3), activation=activator, padding='same'))
modelo_ar.add(Conv2D(32, (3, 3), activation=activator, padding='same'))
modelo_ar.add(MaxPooling2D((2, 2)))
modelo_ar.add(Dropout(0.2))
modelo_ar.add(Conv2D(64, (3, 3), activation=activator, padding='same'))
modelo_ar.add(Conv2D(64, (3, 3), activation=activator, padding='same'))
modelo_ar.add(Conv2D(64, (3, 3), activation=activator, padding='same'))
modelo_ar.add(MaxPooling2D((2, 2)))
modelo_ar.add(Dropout(0.2))
modelo_ar.add(Conv2D(128, (3, 3), activation=activator, padding='same'))
modelo_ar.add(Conv2D(128, (3, 3), activation=activator, padding='same'))
modelo_ar.add(MaxPooling2D((2, 2)))
modelo_ar.add(Flatten())
modelo_ar.add(Dense(128, activation=activator))
Exemple #11
0
    def load_vgg19(self):
        """

         Returns: Create a Model Template of VGG19 with hyperspectral input shape (as defined in init)

         """

        ## adapted from https://stackoverflow.com/questions/53251827/pretrained-tensorflow-model-rgb-rgby-channel-extension
        ## set up vgg19 template with hyperspectral input vector

        x = Conv2D(64, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block1_conv1')(self.hs_inputs)
        x = Conv2D(64, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block1_conv2')(x)
        x = MaxPooling2D(pool_size=(2, 2), name='block1_pool')(x)

        # block 2
        x = Conv2D(128, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block2_conv1')(x)
        x = Conv2D(128, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block2_conv2')(x)
        x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                         name='block2_pool')(x)

        # block 3
        x = Conv2D(256, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block3_conv1')(x)
        x = Conv2D(256, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block3_conv2')(x)
        x = Conv2D(256, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block3_conv3')(x)
        x = Conv2D(256, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block3_conv4')(x)
        x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                         name='block3_pool')(x)

        # block 4
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block4_conv1')(x)
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block4_conv2')(x)
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block4_conv3')(x)
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block4_conv4')(x)
        x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                         name='block4_pool')(x)

        # block 5
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block5_conv1')(x)
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block5_conv2')(x)
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block5_conv3')(x)
        x = Conv2D(512, (3, 3),
                   padding='same',
                   activation='relu',
                   kernel_initializer='zeros',
                   name='block5_conv4')(x)
        x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2),
                         name='block5_pool')(x)

        x = layers.Flatten(name='flatten')(x)
        x = layers.Dense(128, activation='relu')(x)
        x = layers.Dense(128, activation='relu')(x)
        x = layers.Dense(1)(x)

        vgg_template = models.Model(inputs=self.hs_inputs, outputs=x)

        if self.channels > 3:
            layers_to_modify = ['conv1_conv'
                                ]  # Turns out the only layer that changes
        # shape due to 4th to 13th channel is the first convolution layer.
        else:
            layers_to_modify = []
        for layer in self.pretrained_model.layers:  # pretrained Model and template have the same
            # layers, so it doesn't matter which to
            # iterate over.

            if layer.get_weights(
            ):  # Skip input, pooling and no weights layers

                target_layer = vgg_template.get_layer(name=layer.name)
                # print(target_layer.get_weights())
                if layer.name in layers_to_modify:

                    kernels = layer.get_weights()[0]
                    biases = layer.get_weights()[1]
                    kernels_extra_channel = np.concatenate(
                        (kernels, kernels[:, :, -3:, :], kernels[:, :, -3:, :],
                         kernels[:, :, -3:, :], kernels[:, :, -1:, :]),
                        axis=-2)  # For channels_last

                    target_layer.set_weights([kernels_extra_channel, biases])

                else:
                    target_layer.set_weights(layer.get_weights())

        return vgg_template
Exemple #12
0
    name_arr = name.split("_")
    image_category_list.append(name_arr[1])

y_train = np.asarray(image_category_list)
y_train = utils.to_categorical(y_train, 11)
x_train = load_images_to_np_array(image_file_list)
# print(x_train[0])
# plt.imshow(x_train[(len(x_train) - 4)])
# plt.show()

# losses = {'category_output': 'categorical_crossentropy', 'counter_output': 'mse'}

# strategy = tf.distribute.MirroredStrategy()
# with strategy.scope():
i = Input(shape=x_train[0].shape)
nq_network = Conv2D(35, (3, 3), activation='relu', padding='same')(i)
nq_network = BatchNormalization()(nq_network)
nq_network = MaxPooling2D((2, 2))(nq_network)
nq_network = Conv2D(70, (3, 3), activation='relu', padding='same')(nq_network)
nq_network = BatchNormalization()(nq_network)
nq_network = MaxPooling2D((2, 2))(nq_network)
nq_network = Conv2D(100, (3, 3), activation='relu', padding='same')(nq_network)
nq_network = BatchNormalization()(nq_network)
nq_network = MaxPooling2D((2, 2))(nq_network)

nq_network = Flatten()(nq_network)
nq_network = Dropout(0.2)(nq_network)
nq_network = Dense(50, activation='relu')(nq_network)
nq_network = Dropout(0.1)(nq_network)
nq_network = Dense(11, activation='softmax')(nq_network)
Exemple #13
0
def unet(flags_obj, n_filters=64):
  # Contracting Path (encoding)
  inputs = Input(flags_obj.input_size)
  conv1 = Conv2D(n_filters,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(inputs)
  conv1 = Conv2D(n_filters,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv1)
  pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)

  conv2 = Conv2D(n_filters * 2,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(pool1)
  conv2 = Conv2D(n_filters * 2,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv2)
  pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)

  conv3 = Conv2D(n_filters * 4,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(pool2)
  conv3 = Conv2D(n_filters * 4,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv3)
  pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)

  conv4 = Conv2D(n_filters * 8,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(pool3)
  conv4 = Conv2D(n_filters * 8,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv4)
  drop4 = Dropout(0.3)(conv4)
  pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)

  conv5 = Conv2D(n_filters * 16,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(pool4)
  conv5 = Conv2D(n_filters * 16,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv5)
  drop5 = Dropout(0.3)(conv5)

  # Expansive Path (decoding)
  up6 = Conv2DTranspose(n_filters * 8, (3, 3), strides=(2, 2),
                        padding='same')(drop5)
  merge6 = concatenate([up6, drop4], axis=3)
  conv6 = Conv2D(n_filters * 8,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(merge6)
  conv6 = Conv2D(n_filters * 8,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv6)

  up7 = Conv2DTranspose(n_filters * 4, (3, 3), strides=(2, 2),
                        padding='same')(conv6)
  merge7 = concatenate([up7, conv3], axis=3)
  conv7 = Conv2D(n_filters * 4,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(merge7)
  conv7 = Conv2D(n_filters * 4,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv7)

  up8 = Conv2DTranspose(n_filters * 2, (3, 3), strides=(2, 2),
                        padding='same')(conv7)
  merge8 = concatenate([up8, conv2], axis=3)
  conv8 = Conv2D(n_filters * 2,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(merge8)
  conv8 = Conv2D(n_filters * 2,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv8)

  up9 = Conv2DTranspose(n_filters, (3, 3), strides=(2, 2),
                        padding='same')(conv8)
  merge9 = concatenate([up9, conv1], axis=3)
  conv9 = Conv2D(n_filters,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(merge9)
  conv9 = Conv2D(n_filters,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv9)
  conv9 = Conv2D(2,
                 3,
                 activation='relu',
                 padding='same',
                 kernel_initializer='he_normal')(conv9)

  conv10 = Conv2D(1, 1, activation='sigmoid')(conv9)

  model = tf.keras.Model(inputs=inputs, outputs=conv10)

  return model
from tensorflow.keras.layers import Conv2D, MaxPooling2D

Name = "Cats_VS_Dogs_64X2_{}".format(int(time.time()))
tensorboard = TensorBoard(log_dir='logs\{}'.format(Name))

pickle_in = open("x_pickle", "rb")
X = pickle.load(pickle_in)

pickle_in = open("y_pickle", "rb")
y = pickle.load(pickle_in)

X = X / 255.0
X = np.array(X)
y = np.array(y)
model = Sequential()
model.add(Conv2D(64, (3, 3), input_shape=X.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation("relu"))

model.add(Dense(1))
model.add(Activation("sigmoid"))

model.compile(loss="binary_crossentropy",
Exemple #15
0
import pickle
from tensorflow.keras.layers import Dense,Dropout,Conv2D,MaxPool2D,Flatten
from tensorflow.keras.models import Sequential
import numpy as np

pickle_in = open(" X.pickle","rb")
X=pickle.load(pickle_in)
pickle_in.close()

pickle_in1 = open("Y.pickle","rb")
Y=pickle.load(pickle_in1)
pickle_in.close()

X=X/255.0

model=Sequential()

model.add(Conv2D(64,(3,3),input_shape=X.shape[1:],activation='relu'))
model.add(MaxPool2D(pool_size=(2,2)))

model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPool2D(pool_size=(2,2)))

model.add(Flatten())

model.add(Dense(64,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

Y=np.array(Y)
model.fit(X,Y,batch_size=32,epochs=3,validation_split=0.3)
Exemple #16
0
def resnet_v1_eembc(input_shape=[32, 32, 3],
                    num_classes=10,
                    num_filters=[16, 32, 64],
                    kernel_sizes=[3, 1],
                    strides=[1, 2],
                    l1p=1e-4,
                    l2p=0):

    # Input layer, change kernel size to 7x7 and strides to 2 for an official resnet
    inputs = Input(shape=input_shape)
    x = Conv2D(num_filters[0],
               kernel_size=kernel_sizes[0],
               strides=strides[0],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(inputs)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)

    # First stack
    # Weight layers
    y = Conv2D(num_filters[0],
               kernel_size=kernel_sizes[0],
               strides=strides[0],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(x)
    y = BatchNormalization()(y)
    y = Activation('relu')(y)
    y = Conv2D(num_filters[0],
               kernel_size=kernel_sizes[0],
               strides=strides[0],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(y)
    y = BatchNormalization()(y)

    # Overall residual, connect weight layer and identity paths
    x = Add()([x, y])
    x = Activation('relu')(x)

    # Second stack
    # Weight layers
    y = Conv2D(num_filters[1],
               kernel_size=kernel_sizes[0],
               strides=strides[1],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(x)
    y = BatchNormalization()(y)
    y = Activation('relu')(y)
    y = Conv2D(num_filters[1],
               kernel_size=kernel_sizes[0],
               strides=strides[0],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(y)
    y = BatchNormalization()(y)

    # Adjust for change in dimension due to stride in identity
    x = Conv2D(num_filters[1],
               kernel_size=kernel_sizes[1],
               strides=strides[1],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(x)

    # Overall residual, connect weight layer and identity paths
    x = Add()([x, y])
    x = Activation('relu')(x)

    # Third stack
    # Weight layers
    y = Conv2D(num_filters[2],
               kernel_size=kernel_sizes[0],
               strides=strides[1],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(x)
    y = BatchNormalization()(y)
    y = Activation('relu')(y)
    y = Conv2D(num_filters[2],
               kernel_size=kernel_sizes[0],
               strides=strides[0],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(y)
    y = BatchNormalization()(y)

    # Adjust for change in dimension due to stride in identity
    x = Conv2D(num_filters[2],
               kernel_size=kernel_sizes[1],
               strides=strides[1],
               padding='same',
               kernel_initializer='he_normal',
               kernel_regularizer=l1_l2(l1=l1p, l2=l2p))(x)

    # Overall residual, connect weight layer and identity paths
    x = Add()([x, y])
    x = Activation('relu')(x)

    # Final classification layer.
    pool_size = int(np.amin(x.shape[1:3]))
    x = AveragePooling2D(pool_size=pool_size)(x)
    y = Flatten()(x)
    outputs = Dense(num_classes,
                    activation='softmax',
                    kernel_initializer='he_normal')(y)

    # Instantiate model.
    model = Model(inputs=inputs, outputs=outputs)
    return model
def mini_XCEPTION(input_shape, num_classes, l2_regularization=0.01):
    regularization = l2(l2_regularization)

    # base
    img_input = Input(input_shape)
    x = Conv2D(8, (3, 3),
               strides=(1, 1),
               kernel_regularizer=regularization,
               use_bias=False)(img_input)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = Conv2D(8, (3, 3),
               strides=(1, 1),
               kernel_regularizer=regularization,
               use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)

    # module 1
    residual = Conv2D(16, (1, 1),
                      strides=(2, 2),
                      padding='same',
                      use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(16, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(16, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 2
    residual = Conv2D(32, (1, 1),
                      strides=(2, 2),
                      padding='same',
                      use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(32, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(32, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 3
    residual = Conv2D(64, (1, 1),
                      strides=(2, 2),
                      padding='same',
                      use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(64, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(64, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    # module 4
    residual = Conv2D(128, (1, 1),
                      strides=(2, 2),
                      padding='same',
                      use_bias=False)(x)
    residual = BatchNormalization()(residual)

    x = SeparableConv2D(128, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    x = SeparableConv2D(128, (3, 3),
                        padding='same',
                        kernel_regularizer=regularization,
                        use_bias=False)(x)
    x = BatchNormalization()(x)

    x = MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x)
    x = layers.add([x, residual])

    x = Conv2D(
        num_classes,
        (3, 3),
        # kernel_regularizer=regularization,
        padding='same')(x)
    x = GlobalAveragePooling2D()(x)
    output = Dense(30)(x)

    model = Model(img_input, output)
    return model
Exemple #18
0
    def build_net(self, dev):
         with tf.variable_scope('a3c') and tf.device(dev):
            screenInput = Input(
                shape=(U.screen_channel(), self.ssize, self.ssize),
                name='screenInput',
            )

            permutedScreenInput = Permute((2,3,1))(screenInput)
            conv1 = Conv2D(16, kernel_size=5, strides=(1,1), padding='same',name='conv1')(permutedScreenInput)
            conv2 = Conv2D(32, kernel_size=3, strides=(1,1), padding='same',name='conv2')(conv1)

            infoInput = Input(
                shape=(self.isize,),
                name='infoInput',
            )

            customInput = Input(
                shape=(self.custom_input_size,),
                name='customInput',
            )

            nonSpatialInput = Concatenate(name='nonSpatialInputConcat')([infoInput, customInput])

            broadcasted = Lambda(self.broadcast,name='broadcasting')(nonSpatialInput)

            combinedSpatialNonSpatial = Concatenate(name='combinedConcat')([broadcasted, conv2])

            conv3 = Conv2D(1, kernel_size=1, strides=(1,1), padding='same',name='conv3')(combinedSpatialNonSpatial)

            flatConv3 = Flatten(name='flatConv3')(conv3)

            lstmInput = Lambda(self.expand_dims, name='lstmInput')(flatConv3)

            self.NUM_LSTM = 100

            hStateInput = Input(
                shape=(self.NUM_LSTM,),
                name='hStateInput'
            )

            cStateInput = Input(
                shape=(self.NUM_LSTM,),
                name='cStateInput'
            )

            lstm, hStates, cStates = LSTM(self.NUM_LSTM, return_state=True)(lstmInput, initial_state=[hStateInput, cStateInput])

            fc1 = Dense(256, activation='relu',name='dense1')(lstm)
            fc2 = Dense(1, activation='linear',name='fc2')(fc1)
            value = Lambda(self.Squeeze,name='value')(fc2)
            policy = Dense(self.isize, activation='softmax',name='policy')(fc1)


            broadcastLstm = Lambda(self.broadcast, name='breadcastLstm')(lstm)

            spatialLstm = Concatenate(name='spatialLstm')([conv3, broadcastLstm])

            conv4 = Conv2D(1,kernel_size=1, strides=(1,1), padding='same',name='conv4')(spatialLstm)
            flatConv4 = Flatten(name='flattenedConv3')(conv4)
            spatialPolicy = Softmax(name='spatialPolicy')(flatConv4)

            conv5 = Conv2D(1, kernel_size=1, strides=(1,1), padding='same',name='conv5')(spatialLstm)
            flatConv5 = Flatten(name='flattenedConv5')(conv5)
            bestRoach = Softmax(name='bestRoach')(flatConv5)

            self.model = Model(
                inputs=[screenInput, infoInput, customInput, hStateInput, cStateInput],
                outputs=[value, policy, spatialPolicy, hStates, cStates, bestRoach]
            )
            self.model._make_predict_function()
Exemple #19
0
    def __init__(self, latent_code_garms_sz, latent_code_betas_sz, name=None):
        super(SingleImageNet, self).__init__(name=name)

        # Define layers
        if IMG_SIZE >= 1000:
            self.conv1 = Conv2D(8, (3, 3),
                                kernel_initializer='he_normal',
                                padding='same',
                                activation='relu')
            self.conv1_1 = Conv2D(16, (3, 3),
                                  strides=(2, 2),
                                  kernel_initializer='he_normal',
                                  padding='same',
                                  activation='relu')
        else:
            self.conv1 = Conv2D(8, (3, 3),
                                activation='relu',
                                kernel_initializer='he_normal',
                                padding='same')
            self.conv1_1 = Conv2D(16, (3, 3),
                                  activation='relu',
                                  kernel_initializer='he_normal',
                                  padding='same')

        self.conv2 = Conv2D(
            16,
            (3, 3),  # strides=(2, 2),
            kernel_initializer='he_normal',
            padding='same',
            activation='relu')
        self.conv2_1 = Conv2D(
            32,
            (3, 3),  # strides=(2, 2),
            kernel_initializer='he_normal',
            padding='same',
            activation='relu')

        self.conv3 = Conv2D(
            16,
            (3, 3),  # strides=(2, 2),
            kernel_initializer='he_normal',
            padding='same',
            activation='relu')
        self.conv3_1 = Conv2D(
            32,
            (3, 3),  # strides=(2, 2),
            kernel_initializer='he_normal',
            padding='same',
            activation='relu')
        sz = 16
        self.conv4 = Conv2D(
            sz,
            (3, 3),  # strides=(2, 2),
            kernel_initializer='he_normal',
            padding='same',
            activation='relu')
        self.conv4_1 = Conv2D(
            sz,
            (3, 3),  # strides=(2, 2),
            kernel_initializer='he_normal',
            padding='same',
            activation='relu')

        self.conv5 = Conv2D(sz, (3, 3),
                            kernel_initializer='he_normal',
                            padding='same',
                            activation='relu')
        self.conv5_1 = Conv2D(sz, (3, 3),
                              kernel_initializer='he_normal',
                              padding='same',
                              activation='relu')

        self.conv6 = Conv2D(sz, (3, 3),
                            kernel_initializer='he_normal',
                            padding='same',
                            activation='relu')
        self.conv6_1 = Conv2D(sz, (3, 3),
                              kernel_initializer='he_normal',
                              padding='same',
                              activation='relu')
        self.conv7 = Conv2D(sz, (3, 3),
                            kernel_initializer='he_normal',
                            padding='same',
                            activation='relu')
        self.conv7_1 = Conv2D(sz, (3, 3),
                              kernel_initializer='he_normal',
                              padding='same',
                              activation='relu')

        self.split_shape = Lambda(lambda z: z[..., :int(sz / 2)])
        self.split_garms = Lambda(lambda z: z[..., int(sz / 2):])

        self.flatten = Flatten()

        self.dg = Dense(latent_code_garms_sz,
                        kernel_initializer='he_normal',
                        activation='relu')
        self.db = Dense(latent_code_betas_sz,
                        kernel_initializer='he_normal',
                        activation='relu')

        self.dg2 = Dense(int(latent_code_garms_sz / 2),
                         kernel_initializer='he_normal',
                         activation='relu')
        self.db2 = Dense(latent_code_betas_sz,
                         kernel_initializer='he_normal',
                         activation='relu')

        self.dg3 = Dense(int(latent_code_garms_sz / 2),
                         kernel_initializer='he_normal',
                         activation='relu')
        self.db3 = Dense(latent_code_betas_sz,
                         kernel_initializer='he_normal',
                         activation='relu')

        self.latent_code_garms = Dense(int(latent_code_garms_sz / 2),
                                       kernel_initializer='he_normal',
                                       name='latent_garms',
                                       activation='relu')
        self.latent_code_shape = Dense(latent_code_betas_sz,
                                       kernel_initializer='he_normal',
                                       name='latent_shape',
                                       activation='relu')

        self.concat = Concatenate()
def fully_convolutional_resnet50(
    input_shape,
    num_classes=1000,
    pretrained_resnet=True,
    use_bias=True,
):
    # init input layer
    img_input = Input(shape=input_shape)

    # define basic model pipeline
    x = ZeroPadding2D(padding=((3, 3), (3, 3)), name="conv1_pad")(img_input)
    x = Conv2D(64, 7, strides=2, use_bias=use_bias, name="conv1_conv")(x)
    x = BatchNormalization(axis=3, epsilon=1.001e-5, name="conv1_bn")(x)
    x = Activation("relu", name="conv1_relu")(x)

    x = ZeroPadding2D(padding=((1, 1), (1, 1)), name="pool1_pad")(x)
    x = MaxPooling2D(3, strides=2, name="pool1_pool")(x)

    # the sequence of stacked residual blocks
    x = stack1(x, 64, 3, stride1=1, name="conv2")
    x = stack1(x, 128, 4, name="conv3")
    x = stack1(x, 256, 6, name="conv4")
    x = stack1(x, 512, 3, name="conv5")

    # add avg pooling layer after feature extraction layers
    x = AveragePooling2D(pool_size=7)(x)

    # add final convolutional layer
    conv_layer_final = Conv2D(
        filters=num_classes,
        kernel_size=1,
        use_bias=use_bias,
        name="last_conv",
    )(x)

    # configure fully convolutional ResNet50 model
    model = training.Model(img_input, x)

    # load model weights
    if pretrained_resnet:
        model_name = "resnet50"
        # configure full file name
        file_name = model_name + "_weights_tf_dim_ordering_tf_kernels_notop.h5"
        # get the file hash from TF WEIGHTS_HASHES
        file_hash = WEIGHTS_HASHES[model_name][1]
        weights_path = data_utils.get_file(
            file_name,
            BASE_WEIGHTS_PATH + file_name,
            cache_subdir="models",
            file_hash=file_hash,
        )

        model.load_weights(weights_path)

    # form final model
    model = training.Model(inputs=model.input, outputs=[conv_layer_final])

    if pretrained_resnet:
        # get model with the dense layer for further FC weights extraction
        resnet50_extractor = ResNet50(
            include_top=True,
            weights="imagenet",
            classes=num_classes,
        )
        # set ResNet50 FC-layer weights to final convolutional layer
        set_conv_weights(model=model, feature_extractor=resnet50_extractor)
    return model
    image = cv2.imread(image_file)
    rgbimage = cv2.cvtColor(image, cv2.COLOR_RGBA2RGB)
    imgresize = resize_to_fit(rgbimage, 120, 120)
    images.append(imgresize / 255.0)

images = np.array(images)
data = pd.read_csv('recap.csv')
print(images.shape)
labels = np.array(data)
print(labels.shape)
images, labels = shuffle(images, labels)
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(images, labels, test_size=0.1)

model = Sequential()

model.add(Conv2D(16, (3, 3), activation='relu',))
model.add(BatchNormalization())
model.add(MaxPool2D(2, 2))
model.add(Dropout(.2))

model.add(Conv2D(32, (3, 3), activation='relu',))
model.add(BatchNormalization())
model.add(MaxPool2D(2, 2))
model.add(Dropout(.3))

model.add(Conv2D(64, (3, 3), activation='relu',))
model.add(BatchNormalization())
model.add(MaxPool2D(2, 2))
model.add(Dropout(.4))

model.add(Conv2D(128, (3, 3), activation='relu', ))
dropout_rate = 0.25
save_dir = os.path.join(os.getcwd(), "..", "saved_models")
save_dir = os.path.abspath(save_dir)
model_name = "dropout_rate_025.h5"
print(model_name)

(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = x_train / 255
x_test = x_test / 255
y_train = keras.utils.to_categorical(y_train, classes)
y_test = keras.utils.to_categorical(y_test, classes)

model = Sequential()
model.add(Conv2D(32, (3, 3), padding="SAME", input_shape=x_train.shape[1:]))
model.add(Activation("relu"))
model.add(Conv2D(32, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(dropout_rate))

model.add(Conv2D(64, (3, 3), padding="SAME"))
model.add(Activation("relu"))
model.add(Conv2D(64, (3, 3)))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(dropout_rate))

model.add(Flatten())
model.add(Dense(512))
def bluche(input_size, d_model):
    """
    Gated Convolucional Recurrent Neural Network by Bluche et al.

    Reference:
        Bluche, T., Messina, R.:
        Gated convolutional recurrent neural networks for multilingual handwriting recognition.
        In: Document Analysis and Recognition (ICDAR), 2017
        14th IAPR International Conference on, vol. 1, pp. 646–651, 2017.
        URL: https://ieeexplore.ieee.org/document/8270042
    """

    input_data = Input(name="input", shape=input_size)
    cnn = Reshape((input_size[0] // 2, input_size[1] // 2,
                   input_size[2] * 4))(input_data)

    cnn = Conv2D(filters=8,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same",
                 activation="tanh")(cnn)

    cnn = Conv2D(filters=16,
                 kernel_size=(2, 4),
                 strides=(2, 4),
                 padding="same",
                 activation="tanh")(cnn)
    cnn = GatedConv2D(filters=16,
                      kernel_size=(3, 3),
                      strides=(1, 1),
                      padding="same")(cnn)

    cnn = Conv2D(filters=32,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same",
                 activation="tanh")(cnn)
    cnn = GatedConv2D(filters=32,
                      kernel_size=(3, 3),
                      strides=(1, 1),
                      padding="same")(cnn)

    cnn = Conv2D(filters=64,
                 kernel_size=(2, 4),
                 strides=(2, 4),
                 padding="same",
                 activation="tanh")(cnn)
    cnn = GatedConv2D(filters=64,
                      kernel_size=(3, 3),
                      strides=(1, 1),
                      padding="same")(cnn)

    cnn = Conv2D(filters=128,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same",
                 activation="tanh")(cnn)
    cnn = MaxPooling2D(pool_size=(1, 4), strides=(1, 4), padding="valid")(cnn)

    shape = cnn.get_shape()
    blstm = Reshape((shape[1], shape[2] * shape[3]))(cnn)

    blstm = Bidirectional(LSTM(units=128, return_sequences=True))(blstm)
    blstm = Dense(units=128, activation="tanh")(blstm)

    blstm = Bidirectional(LSTM(units=128, return_sequences=True))(blstm)
    output_data = Dense(units=d_model, activation="softmax")(blstm)

    return (input_data, output_data)
Exemple #24
0
norm = BatchNormalization()(gru)
norm = Dropout(0.2)(norm)
reshape = Reshape((SEQ_LENGTH, norm.shape[-1] * frames_per_annotation))(norm)
speech_features = TimeDistributed(Dense(feature_vector_size,
                                        activation='relu'))(reshape)

## conv3d network for video model

img_x = 48
img_y = 48
ch_n = 1

video_input = Input(shape=(SEQ_LENGTH, img_x, img_y, ch_n), name='video_input')

layer = TimeDistributed(
    Conv2D(32, kernel_size=(3, 3), activation='relu',
           padding='same'))(video_input)
layer = TimeDistributed(BatchNormalization())(layer)
layer = TimeDistributed(
    Conv2D(32, kernel_size=(3, 3), activation='relu', padding='same'))(layer)
layer = TimeDistributed(BatchNormalization())(layer)
layer = TimeDistributed(MaxPooling2D(pool_size=(2, 2), padding='same'))(layer)

layer = TimeDistributed(
    Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))(layer)
layer = TimeDistributed(BatchNormalization())(layer)
layer = TimeDistributed(
    Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))(layer)
layer = TimeDistributed(BatchNormalization())(layer)
layer = TimeDistributed(MaxPooling2D(pool_size=(2, 2), padding='same'))(layer)
layer = TimeDistributed(Dropout(0.2))(layer)
def flor(input_size, d_model):
    """
    Gated Convolucional Recurrent Neural Network by Flor et al.
    """

    input_data = Input(name="input", shape=input_size)

    cnn = Conv2D(filters=16,
                 kernel_size=(3, 3),
                 strides=(1, 2),
                 padding="same",
                 kernel_initializer="he_uniform")(input_data)
    cnn = PReLU(shared_axes=[1, 2])(cnn)
    cnn = BatchNormalization(renorm=True)(cnn)
    cnn = FullGatedConv2D(filters=16, kernel_size=(3, 3), padding="same")(cnn)

    cnn = Conv2D(filters=32,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same",
                 kernel_initializer="he_uniform")(cnn)
    cnn = PReLU(shared_axes=[1, 2])(cnn)
    cnn = BatchNormalization(renorm=True)(cnn)
    cnn = FullGatedConv2D(filters=32, kernel_size=(3, 3), padding="same")(cnn)

    cnn = Conv2D(filters=40,
                 kernel_size=(2, 4),
                 strides=(2, 4),
                 padding="same",
                 kernel_initializer="he_uniform")(cnn)
    cnn = PReLU(shared_axes=[1, 2])(cnn)
    cnn = BatchNormalization(renorm=True)(cnn)
    cnn = FullGatedConv2D(filters=40,
                          kernel_size=(3, 3),
                          padding="same",
                          kernel_constraint=MaxNorm(4, [0, 1, 2]))(cnn)
    cnn = Dropout(rate=0.2)(cnn)

    cnn = Conv2D(filters=48,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same",
                 kernel_initializer="he_uniform")(cnn)
    cnn = PReLU(shared_axes=[1, 2])(cnn)
    cnn = BatchNormalization(renorm=True)(cnn)
    cnn = FullGatedConv2D(filters=48,
                          kernel_size=(3, 3),
                          padding="same",
                          kernel_constraint=MaxNorm(4, [0, 1, 2]))(cnn)
    cnn = Dropout(rate=0.2)(cnn)

    cnn = Conv2D(filters=56,
                 kernel_size=(2, 4),
                 strides=(2, 4),
                 padding="same",
                 kernel_initializer="he_uniform")(cnn)
    cnn = PReLU(shared_axes=[1, 2])(cnn)
    cnn = BatchNormalization(renorm=True)(cnn)
    cnn = FullGatedConv2D(filters=56,
                          kernel_size=(3, 3),
                          padding="same",
                          kernel_constraint=MaxNorm(4, [0, 1, 2]))(cnn)
    cnn = Dropout(rate=0.2)(cnn)

    cnn = Conv2D(filters=64,
                 kernel_size=(3, 3),
                 strides=(1, 1),
                 padding="same",
                 kernel_initializer="he_uniform")(cnn)
    cnn = PReLU(shared_axes=[1, 2])(cnn)
    cnn = BatchNormalization(renorm=True)(cnn)

    shape = cnn.get_shape()
    bgru = Reshape((shape[1], shape[2] * shape[3]))(cnn)

    bgru = Bidirectional(GRU(units=128, return_sequences=True,
                             dropout=0.5))(bgru)
    bgru = Dense(units=256)(bgru)

    bgru = Bidirectional(GRU(units=128, return_sequences=True,
                             dropout=0.5))(bgru)
    output_data = Dense(units=d_model, activation="softmax")(bgru)

    return (input_data, output_data)
Exemple #26
0
def build_model(image_size,
                n_classes,
                mode='training',
                l2_regularization=0.0,
                min_scale=0.1,
                max_scale=0.9,
                scales=None,
                aspect_ratios_global=[0.5, 1.0, 2.0],
                aspect_ratios_per_layer=None,
                two_boxes_for_ar1=True,
                steps=None,
                offsets=None,
                clip_boxes=False,
                variances=[1.0, 1.0, 1.0, 1.0],
                coords='centroids',
                normalize_coords=False,
                subtract_mean=None,
                divide_by_stddev=None,
                swap_channels=False,
                confidence_thresh=0.01,
                iou_threshold=0.45,
                top_k=200,
                nms_max_output_size=400,
                return_predictor_sizes=False):
    '''
    Build a Keras model with SSD architecture, see references.

    The model consists of convolutional feature layers and a number of convolutional
    predictor layers that take their input from different feature layers.
    The model is fully convolutional.

    The implementation found here is a smaller version of the original architecture
    used in the paper (where the base network consists of a modified VGG-16 extended
    by a few convolutional feature layers), but of course it could easily be changed to
    an arbitrarily large SSD architecture by following the general design pattern used here.
    This implementation has 7 convolutional layers and 4 convolutional predictor
    layers that take their input from layers 4, 5, 6, and 7, respectively.

    Most of the arguments that this function takes are only needed for the anchor
    box layers. In case you're training the network, the parameters passed here must
    be the same as the ones used to set up `SSDBoxEncoder`. In case you're loading
    trained weights, the parameters passed here must be the same as the ones used
    to produce the trained weights.

    Some of these arguments are explained in more detail in the documentation of the
    `SSDBoxEncoder` class.

    Note: Requires Keras v2.0 or later. Training currently works only with the
    TensorFlow backend (v1.0 or later).

    Arguments:
        image_size (tuple): The input image size in the format `(height, width, channels)`.
        n_classes (int): The number of positive classes, e.g. 20 for Pascal VOC, 80 for MS COCO.
        mode (str, optional): One of 'training', 'inference' and 'inference_fast'. In 'training' mode,
            the model outputs the raw prediction tensor, while in 'inference' and 'inference_fast' modes,
            the raw predictions are decoded into absolute coordinates and filtered via confidence thresholding,
            non-maximum suppression, and top-k filtering. The difference between latter two modes is that
            'inference' follows the exact procedure of the original Caffe implementation, while
            'inference_fast' uses a faster prediction decoding procedure.
        l2_regularization (float, optional): The L2-regularization rate. Applies to all convolutional layers.
        min_scale (float, optional): The smallest scaling factor for the size of the anchor boxes as a fraction
            of the shorter side of the input images.
        max_scale (float, optional): The largest scaling factor for the size of the anchor boxes as a fraction
            of the shorter side of the input images. All scaling factors between the smallest and the
            largest will be linearly interpolated. Note that the second to last of the linearly interpolated
            scaling factors will actually be the scaling factor for the last predictor layer, while the last
            scaling factor is used for the second box for aspect ratio 1 in the last predictor layer
            if `two_boxes_for_ar1` is `True`.
        scales (list, optional): A list of floats containing scaling factors per convolutional predictor layer.
            This list must be one element longer than the number of predictor layers. The first `k` elements are the
            scaling factors for the `k` predictor layers, while the last element is used for the second box
            for aspect ratio 1 in the last predictor layer if `two_boxes_for_ar1` is `True`. This additional
            last scaling factor must be passed either way, even if it is not being used. If a list is passed,
            this argument overrides `min_scale` and `max_scale`. All scaling factors must be greater than zero.
        aspect_ratios_global (list, optional): The list of aspect ratios for which anchor boxes are to be
            generated. This list is valid for all predictor layers. The original implementation uses more aspect ratios
            for some predictor layers and fewer for others. If you want to do that, too, then use the next argument instead.
        aspect_ratios_per_layer (list, optional): A list containing one aspect ratio list for each predictor layer.
            This allows you to set the aspect ratios for each predictor layer individually. If a list is passed,
            it overrides `aspect_ratios_global`.
        two_boxes_for_ar1 (bool, optional): Only relevant for aspect ratio lists that contain 1. Will be ignored otherwise.
            If `True`, two anchor boxes will be generated for aspect ratio 1. The first will be generated
            using the scaling factor for the respective layer, the second one will be generated using
            geometric mean of said scaling factor and next bigger scaling factor.
        steps (list, optional): `None` or a list with as many elements as there are predictor layers. The elements can be
            either ints/floats or tuples of two ints/floats. These numbers represent for each predictor layer how many
            pixels apart the anchor box center points should be vertically and horizontally along the spatial grid over
            the image. If the list contains ints/floats, then that value will be used for both spatial dimensions.
            If the list contains tuples of two ints/floats, then they represent `(step_height, step_width)`.
            If no steps are provided, then they will be computed such that the anchor box center points will form an
            equidistant grid within the image dimensions.
        offsets (list, optional): `None` or a list with as many elements as there are predictor layers. The elements can be
            either floats or tuples of two floats. These numbers represent for each predictor layer how many
            pixels from the top and left boarders of the image the top-most and left-most anchor box center points should be
            as a fraction of `steps`. The last bit is important: The offsets are not absolute pixel values, but fractions
            of the step size specified in the `steps` argument. If the list contains floats, then that value will
            be used for both spatial dimensions. If the list contains tuples of two floats, then they represent
            `(vertical_offset, horizontal_offset)`. If no offsets are provided, then they will default to 0.5 of the step size,
            which is also the recommended setting.
        clip_boxes (bool, optional): If `True`, clips the anchor box coordinates to stay within image boundaries.
        variances (list, optional): A list of 4 floats >0. The anchor box offset for each coordinate will be divided by
            its respective variance value.
        coords (str, optional): The box coordinate format to be used internally by the model (i.e. this is not the input format
            of the ground truth labels). Can be either 'centroids' for the format `(cx, cy, w, h)` (box center coordinates, width,
            and height), 'minmax' for the format `(xmin, xmax, ymin, ymax)`, or 'corners' for the format `(xmin, ymin, xmax, ymax)`.
        normalize_coords (bool, optional): Set to `True` if the model is supposed to use relative instead of absolute coordinates,
            i.e. if the model predicts box coordinates within [0,1] instead of absolute coordinates.
        subtract_mean (array-like, optional): `None` or an array-like object of integers or floating point values
            of any shape that is broadcast-compatible with the image shape. The elements of this array will be
            subtracted from the image pixel intensity values. For example, pass a list of three integers
            to perform per-channel mean normalization for color images.
        divide_by_stddev (array-like, optional): `None` or an array-like object of non-zero integers or
            floating point values of any shape that is broadcast-compatible with the image shape. The image pixel
            intensity values will be divided by the elements of this array. For example, pass a list
            of three integers to perform per-channel standard deviation normalization for color images.
        swap_channels (list, optional): Either `False` or a list of integers representing the desired order in which the input
            image channels should be swapped.
        confidence_thresh (float, optional): A float in [0,1), the minimum classification confidence in a specific
            positive class in order to be considered for the non-maximum suppression stage for the respective class.
            A lower value will result in a larger part of the selection process being done by the non-maximum suppression
            stage, while a larger value will result in a larger part of the selection process happening in the confidence
            thresholding stage.
        iou_threshold (float, optional): A float in [0,1]. All boxes that have a Jaccard similarity of greater than `iou_threshold`
            with a locally maximal box will be removed from the set of predictions for a given class, where 'maximal' refers
            to the box's confidence score.
        top_k (int, optional): The number of highest scoring predictions to be kept for each batch item after the
            non-maximum suppression stage.
        nms_max_output_size (int, optional): The maximal number of predictions that will be left over after the NMS stage.
        return_predictor_sizes (bool, optional): If `True`, this function not only returns the model, but also
            a list containing the spatial dimensions of the predictor layers. This isn't strictly necessary since
            you can always get their sizes easily via the Keras API, but it's convenient and less error-prone
            to get them this way. They are only relevant for training anyway (SSDBoxEncoder needs to know the
            spatial dimensions of the predictor layers), for inference you don't need them.

    Returns:
        model: The Keras SSD model.
        predictor_sizes (optional): A Numpy array containing the `(height, width)` portion
            of the output tensor shape for each convolutional predictor layer. During
            training, the generator function needs this in order to transform
            the ground truth labels into tensors of identical structure as the
            output tensors of the model, which is in turn needed for the cost
            function.

    References:
        https://arxiv.org/abs/1512.02325v5
    '''

    n_predictor_layers = 4 # The number of predictor conv layers in the network
    n_classes += 1 # Account for the background class.
    l2_reg = l2_regularization # Make the internal name shorter.
    img_height, img_width, img_channels = image_size[0], image_size[1], image_size[2]

    ############################################################################
    # Get a few exceptions out of the way.
    ############################################################################

    if aspect_ratios_global is None and aspect_ratios_per_layer is None:
        raise ValueError("`aspect_ratios_global` and `aspect_ratios_per_layer` cannot both be None. At least one needs to be specified.")
    if aspect_ratios_per_layer:
        if len(aspect_ratios_per_layer) != n_predictor_layers:
            raise ValueError("It must be either aspect_ratios_per_layer is None or len(aspect_ratios_per_layer) == {}, but len(aspect_ratios_per_layer) == {}.".format(n_predictor_layers, len(aspect_ratios_per_layer)))

    if (min_scale is None or max_scale is None) and scales is None:
        raise ValueError("Either `min_scale` and `max_scale` or `scales` need to be specified.")
    if scales:
        if len(scales) != n_predictor_layers+1:
            raise ValueError("It must be either scales is None or len(scales) == {}, but len(scales) == {}.".format(n_predictor_layers+1, len(scales)))
    else: # If no explicit list of scaling factors was passed, compute the list of scaling factors from `min_scale` and `max_scale`
        scales = np.linspace(min_scale, max_scale, n_predictor_layers+1)

    if len(variances) != 4: # We need one variance value for each of the four box coordinates
        raise ValueError("4 variance values must be pased, but {} values were received.".format(len(variances)))
    variances = np.array(variances)
    if np.any(variances <= 0):
        raise ValueError("All variances must be >0, but the variances given are {}".format(variances))

    if (not (steps is None)) and (len(steps) != n_predictor_layers):
        raise ValueError("You must provide at least one step value per predictor layer.")

    if (not (offsets is None)) and (len(offsets) != n_predictor_layers):
        raise ValueError("You must provide at least one offset value per predictor layer.")

    ############################################################################
    # Compute the anchor box parameters.
    ############################################################################

    # Set the aspect ratios for each predictor layer. These are only needed for the anchor box layers.
    if aspect_ratios_per_layer:
        aspect_ratios = aspect_ratios_per_layer
    else:
        aspect_ratios = [aspect_ratios_global] * n_predictor_layers

    # Compute the number of boxes to be predicted per cell for each predictor layer.
    # We need this so that we know how many channels the predictor layers need to have.
    if aspect_ratios_per_layer:
        n_boxes = []
        for ar in aspect_ratios_per_layer:
            if (1 in ar) & two_boxes_for_ar1:
                n_boxes.append(len(ar) + 1) # +1 for the second box for aspect ratio 1
            else:
                n_boxes.append(len(ar))
    else: # If only a global aspect ratio list was passed, then the number of boxes is the same for each predictor layer
        if (1 in aspect_ratios_global) & two_boxes_for_ar1:
            n_boxes = len(aspect_ratios_global) + 1
        else:
            n_boxes = len(aspect_ratios_global)
        n_boxes = [n_boxes] * n_predictor_layers

    if steps is None:
        steps = [None] * n_predictor_layers
    if offsets is None:
        offsets = [None] * n_predictor_layers

    ############################################################################
    # Define functions for the Lambda layers below.
    ############################################################################

    def identity_layer(tensor):
        return tensor

    def input_mean_normalization(tensor):
        return tensor - np.array(subtract_mean)

    def input_stddev_normalization(tensor):
        return tensor / np.array(divide_by_stddev)

    #def input_channel_swap(tensor):
    #    if len(swap_channels) == 3:
    #        return K.stack([tensor[...,swap_channels[0]], tensor[...,swap_channels[1]], tensor[...,swap_channels[2]]], axis=-1)
    #    elif len(swap_channels) == 4:
    #        return K.stack([tensor[...,swap_channels[0]], tensor[...,swap_channels[1]], tensor[...,swap_channels[2]], tensor[...,swap_channels[3]]], axis=-1)

    ############################################################################
    # Build the network.
    ############################################################################

    x = Input(shape=(img_height, img_width, img_channels))

    # The following identity layer is only needed so that the subsequent lambda layers can be optional.
    x1 = Lambda(identity_layer, output_shape=(img_height, img_width, img_channels), name='identity_layer')(x)
    if not (subtract_mean is None):
        x1 = Lambda(input_mean_normalization, output_shape=(img_height, img_width, img_channels), name='input_mean_normalization')(x1)
    if not (divide_by_stddev is None):
        x1 = Lambda(input_stddev_normalization, output_shape=(img_height, img_width, img_channels), name='input_stddev_normalization')(x1)
    #if swap_channels: #REMOVED FOR TFLITE
    #    x1 = Lambda(input_channel_swap, output_shape=(img_height, img_width, img_channels), name='input_channel_swap')(x1)

    conv1 = Conv2D(32, (5, 5), strides=(2, 2), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='conv1')(x1)
    conv1 = BatchNormalization(axis=3, momentum=0.99, name='bn1')(conv1) # Tensorflow uses filter format [filter_height, filter_width, in_channels, out_channels], hence axis = 3
    conv1 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same', name='pool1')(conv1)


    conv2 = QuantConv2D(48, (3, 3), strides=(1, 1), padding="same", kernel_initializer='glorot_normal', use_bias=False, name='conv2', **kwargs)(conv1)
    conv2 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool2')(conv2)
    conv2 = BatchNormalization(axis=3, momentum=0.99, name='bn2')(conv2)
    

    conv3 = QuantConv2D(64, (3, 3), strides=(1, 1), padding="same", kernel_initializer='glorot_normal', use_bias=False, name='conv3', **kwargs)(conv2)
    #conv3 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool3')(conv3)
    conv3 = BatchNormalization(axis=3, momentum=0.99, name='bn3')(conv3)
    
    #Conv1,2,3 are for feature extraction and downsampling
    #Conv4,5,6,7 are the pre-detection feature maps
    
    conv4 = QuantConv2D(64, (3, 3), strides=(1, 1), padding="same", kernel_initializer='glorot_normal', use_bias=False, name='conv4', **kwargs)(conv3)
    conv4 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool4')(conv4)
    conv4 = BatchNormalization(axis=3, momentum=0.99, name='bn4')(conv4)
    

    conv5 = QuantConv2D(48, (3, 3), strides=(1, 1), padding="same", kernel_initializer='glorot_normal', use_bias=False, name='conv5', **kwargs)(conv4)
    conv5 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool5')(conv5)
    conv5 = BatchNormalization(axis=3, momentum=0.99, name='bn5')(conv5)
    

    conv6 = QuantConv2D(48, (3, 3), strides=(1, 1), padding="same", kernel_initializer='glorot_normal', use_bias=False, name='conv6', **kwargs)(conv5)
    conv6 = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool6')(conv6)
    conv6 = BatchNormalization(axis=3, momentum=0.99, name='bn6')(conv6)
    

    conv7 = QuantConv2D(32, (3, 3), strides=(1, 1), padding="same", kernel_initializer='glorot_normal', use_bias=False, name='conv7', **kwargs)(conv6)
    conv7 = BatchNormalization(axis=3, momentum=0.99, name='bn7')(conv7)

    # The next part is to add the convolutional predictor layers on top of the base network
    # that we defined above. Note that I use the term "base network" differently than the paper does.
    # To me, the base network is everything that is not convolutional predictor layers or anchor
    # box layers. In this case we'll have four predictor layers, but of course you could
    # easily rewrite this into an arbitrarily deep base network and add an arbitrary number of
    # predictor layers on top of the base network by simply following the pattern shown here.

    # Build the convolutional predictor layers on top of conv layers 4, 5, 6, and 7.
    # We build two predictor layers on top of each of these layers: One for class prediction (classification), one for box coordinate prediction (localization)
    # We precidt `n_classes` confidence values for each box, hence the `classes` predictors have depth `n_boxes * n_classes`
    # We predict 4 box coordinates for each box, hence the `boxes` predictors have depth `n_boxes * 4`
    # Output shape of `classes`: `(batch, height, width, n_boxes * n_classes)`
    classes4 = Conv2D(n_boxes[0] * n_classes, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='classes4')(conv4)
    classes5 = Conv2D(n_boxes[1] * n_classes, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='classes5')(conv5)
    classes6 = Conv2D(n_boxes[2] * n_classes, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='classes6')(conv6)
    classes7 = Conv2D(n_boxes[3] * n_classes, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='classes7')(conv7)
    # Output shape of `boxes`: `(batch, height, width, n_boxes * 4)`
    boxes4 = Conv2D(n_boxes[0] * 4, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='boxes4')(conv4)
    boxes5 = Conv2D(n_boxes[1] * 4, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='boxes5')(conv5)
    boxes6 = Conv2D(n_boxes[2] * 4, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='boxes6')(conv6)
    boxes7 = Conv2D(n_boxes[3] * 4, (3, 3), strides=(1, 1), padding="same", kernel_initializer='he_normal', kernel_regularizer=l2(l2_reg), name='boxes7')(conv7)

    # Generate the anchor boxes
    # Output shape of `anchors`: `(batch, height, width, n_boxes, 8)`
    anchors4 = AnchorBoxes(img_height, img_width, this_scale=scales[0], next_scale=scales[1], aspect_ratios=aspect_ratios[0],
                           two_boxes_for_ar1=two_boxes_for_ar1, this_steps=steps[0], this_offsets=offsets[0],
                           clip_boxes=clip_boxes, variances=variances, coords=coords, normalize_coords=normalize_coords, name='anchors4')(boxes4)
    anchors5 = AnchorBoxes(img_height, img_width, this_scale=scales[1], next_scale=scales[2], aspect_ratios=aspect_ratios[1],
                           two_boxes_for_ar1=two_boxes_for_ar1, this_steps=steps[1], this_offsets=offsets[1],
                           clip_boxes=clip_boxes, variances=variances, coords=coords, normalize_coords=normalize_coords, name='anchors5')(boxes5)
    anchors6 = AnchorBoxes(img_height, img_width, this_scale=scales[2], next_scale=scales[3], aspect_ratios=aspect_ratios[2],
                           two_boxes_for_ar1=two_boxes_for_ar1, this_steps=steps[2], this_offsets=offsets[2],
                           clip_boxes=clip_boxes, variances=variances, coords=coords, normalize_coords=normalize_coords, name='anchors6')(boxes6)
    anchors7 = AnchorBoxes(img_height, img_width, this_scale=scales[3], next_scale=scales[4], aspect_ratios=aspect_ratios[3],
                           two_boxes_for_ar1=two_boxes_for_ar1, this_steps=steps[3], this_offsets=offsets[3],
                           clip_boxes=clip_boxes, variances=variances, coords=coords, normalize_coords=normalize_coords, name='anchors7')(boxes7)

    # Reshape the class predictions, yielding 3D tensors of shape `(batch, height * width * n_boxes, n_classes)`
    # We want the classes isolated in the last axis to perform softmax on them
    
    #Shape inference is different for keras.layers and tf.keras.layers (-1), check documentation
    #So I had to manually input the intended shape of the reshape
    
    #cba = classes, boxes, anchors SHAPE: shape will be reused later anyways
    cba_4 = classes4.shape[1]*classes4.shape[2]*n_boxes[0]
    cba_5 = classes5.shape[1]*classes5.shape[2]*n_boxes[1]
    cba_6 = classes6.shape[1]*classes6.shape[2]*n_boxes[2]
    cba_7 = classes7.shape[1]*classes7.shape[2]*n_boxes[3]
    
    classes4_reshaped = Reshape((cba_4, n_classes), name='classes4_reshape')(classes4)
    classes5_reshaped = Reshape((cba_5, n_classes), name='classes5_reshape')(classes5)
    classes6_reshaped = Reshape((cba_6, n_classes), name='classes6_reshape')(classes6)
    classes7_reshaped = Reshape((cba_7, n_classes), name='classes7_reshape')(classes7)
    # Reshape the box coordinate predictions, yielding 3D tensors of shape `(batch, height * width * n_boxes, 4)`
    
    #shape for classes_reshaped is SAME with boxes EXCEPT for n_classes and anchors so NO NEED TO RECOMPUTE
    
    # We want the four box coordinates isolated in the last axis to compute the smooth L1 loss
    boxes4_reshaped = Reshape((cba_4, 4), name='boxes4_reshape')(boxes4)
    boxes5_reshaped = Reshape((cba_5, 4), name='boxes5_reshape')(boxes5)
    boxes6_reshaped = Reshape((cba_6, 4), name='boxes6_reshape')(boxes6)
    boxes7_reshaped = Reshape((cba_7, 4), name='boxes7_reshape')(boxes7)
    # Reshape the anchor box tensors, yielding 3D tensors of shape `(batch, height * width * n_boxes, 8)`
    anchors4_reshaped = Reshape((cba_4, 8), name='anchors4_reshape')(anchors4)
    anchors5_reshaped = Reshape((cba_5, 8), name='anchors5_reshape')(anchors5)
    anchors6_reshaped = Reshape((cba_6, 8), name='anchors6_reshape')(anchors6)
    anchors7_reshaped = Reshape((cba_7, 8), name='anchors7_reshape')(anchors7)

    # Concatenate the predictions from the different layers and the assosciated anchor box tensors
    # Axis 0 (batch) and axis 2 (n_classes or 4, respectively) are identical for all layer predictions,
    # so we want to concatenate along axis 1
    # Output shape of `classes_concat`: (batch, n_boxes_total, n_classes)
    classes_concat = Concatenate(axis=1, name='classes_concat')([classes4_reshaped,
                                                                 classes5_reshaped,
                                                                 classes6_reshaped,
                                                                 classes7_reshaped])

    # Output shape of `boxes_concat`: (batch, n_boxes_total, 4)
    boxes_concat = Concatenate(axis=1, name='boxes_concat')([boxes4_reshaped,
                                                             boxes5_reshaped,
                                                             boxes6_reshaped,
                                                             boxes7_reshaped])

    # Output shape of `anchors_concat`: (batch, n_boxes_total, 8)
    anchors_concat = Concatenate(axis=1, name='anchors_concat')([anchors4_reshaped,
                                                                 anchors5_reshaped,
                                                                 anchors6_reshaped,
                                                                 anchors7_reshaped])

    # The box coordinate predictions will go into the loss function just the way they are,
    # but for the class predictions, we'll apply a softmax activation layer first
    classes_softmax = Activation('softmax', name='classes_softmax')(classes_concat)

    # Concatenate the class and box coordinate predictions and the anchors to one large predictions tensor
    # Output shape of `predictions`: (batch, n_boxes_total, n_classes + 4 + 8)
    predictions = Concatenate(axis=2, name='predictions')([classes_softmax, boxes_concat, anchors_concat])

    if mode == 'training':
        model = Model(inputs=x, outputs=predictions)
    elif mode == 'inference':
        decoded_predictions = DecodeDetections(confidence_thresh=confidence_thresh,
                                               iou_threshold=iou_threshold,
                                               top_k=top_k,
                                               nms_max_output_size=nms_max_output_size,
                                               coords=coords,
                                               normalize_coords=normalize_coords,
                                               img_height=img_height,
                                               img_width=img_width,
                                               name='decoded_predictions')(predictions)
        model = Model(inputs=x, outputs=decoded_predictions)
    elif mode == 'inference_fast':
        decoded_predictions = DecodeDetectionsFast(confidence_thresh=confidence_thresh,
                                                   iou_threshold=iou_threshold,
                                                   top_k=top_k,
                                                   nms_max_output_size=nms_max_output_size,
                                                   coords=coords,
                                                   normalize_coords=normalize_coords,
                                                   img_height=img_height,
                                                   img_width=img_width,
                                                   name='decoded_predictions')(predictions)
        model = Model(inputs=x, outputs=decoded_predictions)
    else:
        raise ValueError("`mode` must be one of 'training', 'inference' or 'inference_fast', but received '{}'.".format(mode))

    if return_predictor_sizes:
        # The spatial dimensions are the same for the `classes` and `boxes` predictor layers.
        predictor_sizes = np.array([classes4._keras_shape[1:3],
                                    classes5._keras_shape[1:3],
                                    classes6._keras_shape[1:3],
                                    classes7._keras_shape[1:3]])
        return model, predictor_sizes
    else:
        return model
Exemple #27
0
 def __init__(self):
     super(MyModel, self).__init__()
     self.conv1 = Conv2D(32, 3, activation='relu')
     self.flatten = Flatten()
     self.d1 = Dense(128, activation='relu')
     self.d2 = Dense(10, activation='softmax')
Exemple #28
0
'''
https://stackoverflow.com/questions/50124158/keras-loss-function-with-additional-dynamic-parameter
'''
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPool2D, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.losses import categorical_crossentropy

def sample_loss( y_true, y_pred, is_weight ) :
    return is_weight * categorical_crossentropy( y_true, y_pred ) 

x = Input(shape=(32,32,3), name='image_in')
y_true = Input( shape=(10,), name='y_true' )
is_weight = Input(shape=(1,), name='is_weight')
f = Conv2D(16,(3,3),padding='same')(x)
f = MaxPool2D((2,2),padding='same')(f)
f = Conv2D(32,(3,3),padding='same')(f)
f = MaxPool2D((2,2),padding='same')(f)
f = Conv2D(64,(3,3),padding='same')(f)
f = MaxPool2D((2,2),padding='same')(f)
f = Flatten()(f)
y_pred = Dense(10, activation='softmax', name='y_pred' )(f)
model = Model( inputs=[x, y_true, is_weight], outputs=y_pred, name='train_only' )
model.add_loss( sample_loss( y_true, y_pred, is_weight ) )
model.compile(loss=None, optimizer='sgd')
model.summary()

# train
import numpy as np 
a = np.random.randn(8,32,32,3)
a_true = np.random.randn(8,10)
a_is_weight = np.random.randint(0,2,size=(8,1))
Exemple #29
0
 def __init__(
         self,
         n_filters=256,
         # the number of dubs is inferred from the code not the paper
         n_dubs=6,
         n_convs_recon=9,
         n_scales=3,
         convs_per_scale=CONVS_PER_SCALE_DUB,
         **kwargs):
     super(DIDN, self).__init__(**kwargs)
     self.n_filters = n_filters
     self.n_dubs = n_dubs
     self.n_scales = n_scales
     self.convs_per_scale = convs_per_scale
     self.n_convs_recon = n_convs_recon
     self.dubs = [
         DUB(
             n_filters=self.n_filters,
             n_scales=self.n_scales,
             convs_per_scale=self.convs_per_scale,
         ) for _ in range(self.n_dubs)
     ]
     self.recon_block = ReconBlock(
         n_convs=self.n_convs_recon,
         n_filters=self.n_filters,
     )
     self.first_conv = Conv2D(
         filters=self.n_filters,
         kernel_size=3,
         padding='same',
         activation=PReLU(shared_axes=[1, 2]),
         use_bias=False,
     )
     self.pooling = Conv2D(
         filters=self.n_filters,
         kernel_size=3,
         strides=2,
         padding='same',
         use_bias=False,
     )
     self.post_recon_agg = Conv2D(
         filters=self.n_filters,
         kernel_size=1,
         padding='same',
         use_bias=False,
     )
     self.post_recon_conv = Conv2D(
         filters=self.n_filters,
         kernel_size=3,
         padding='same',
         activation=PReLU(shared_axes=[1, 2]),
         use_bias=False,
     )
     self.last_conv = Conv2D(
         filters=1,
         kernel_size=3,
         padding='same',
         # in code the activation is actually linear
         activation='linear',
         use_bias=False,
     )
def _conv_layer(filters, kernel_size, strides=(1, 1), padding='same', name=None):
    return Conv2D(filters, kernel_size, strides=strides, padding=padding,
                  use_bias=True, kernel_initializer='he_normal', name=name)