我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用keras.layers.Convolution2D()。
def build_encoder(self,input_shape): return [Reshape((*input_shape,1)), GaussianNoise(self.parameters['noise']), BN(), *[Convolution2D(self.parameters['clayer'],(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), Dropout(self.parameters['dropout']), BN(), MaxPooling2D((2,2)),], *[Convolution2D(self.parameters['clayer'],(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), Dropout(self.parameters['dropout']), BN(), MaxPooling2D((2,2)),], flatten, Sequential([ Dense(self.parameters['layer'], activation=self.parameters['activation'], use_bias=False), BN(), Dropout(self.parameters['dropout']), Dense(self.parameters['N']*self.parameters['M']), ])]
def build_encoder(self,input_shape): return [Reshape((*input_shape,1)), GaussianNoise(0.1), BN(), Convolution2D(self.parameters['clayer'],(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), Dropout(self.parameters['dropout']), BN(), MaxPooling2D((2,2)), Convolution2D(self.parameters['clayer'],(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), Dropout(self.parameters['dropout']), BN(), MaxPooling2D((2,2)), Convolution2D(self.parameters['clayer'],(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), Dropout(self.parameters['dropout']), BN(), MaxPooling2D((2,2)), flatten,]
def build_network(num_actions, agent_history_length, resized_width, resized_height): state = tf.placeholder("float", [None, agent_history_length, resized_width, resized_height]) inputs_v = Input(shape=(agent_history_length, resized_width, resized_height,)) #model_v = Permute((2, 3, 1))(inputs_v) model_v = Convolution2D(nb_filter=16, nb_row=8, nb_col=8, subsample=(4,4), activation='relu', border_mode='same')(inputs_v) model_v = Convolution2D(nb_filter=32, nb_row=4, nb_col=4, subsample=(2,2), activation='relu', border_mode='same')(model_v) model_v = Flatten()(model_v) model_v = Dense(output_dim=512)(model_v) model_v = PReLU()(model_v) action_probs = Dense(name="p", output_dim=num_actions, activation='softmax')(model_v) state_value = Dense(name="v", output_dim=1, activation='linear')(model_v) value_network = Model(input=inputs_v, output=[state_value, action_probs]) return state, value_network
def discriminator_model(): """ return a (b, 1) logits""" model = Sequential() model.add(Convolution2D(64, 4, 4,border_mode='same',input_shape=(IN_CH*2, img_cols, img_rows))) model.add(BatchNormalization(mode=2)) model.add(Activation('tanh')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(128, 4, 4,border_mode='same')) model.add(BatchNormalization(mode=2)) model.add(Activation('tanh')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(512, 4, 4,border_mode='same')) model.add(BatchNormalization(mode=2)) model.add(Activation('tanh')) model.add(Convolution2D(1, 4, 4,border_mode='same')) model.add(BatchNormalization(mode=2)) model.add(Activation('tanh')) model.add(Activation('sigmoid')) return model
def conv2d_bn(x, nb_filter,num_row, num_col, strides=(1,1), padding='same', name=None): if name is not None: bn_name = name + '_bn' conv_name = name + '_conv' else: bn_name = None conv_name = None if K.image_data_format() == 'channels_first': bn_axis = 1 else: bn_axis = 3 x = Convolution2D(nb_filter,[num_row, num_col],padding=padding,strides=strides,activation='relu',name=conv_name)(x) x = FixedBatchNormalization(axis=bn_axis, name=bn_name)(x) return x
def build_encoder(self,input_shape): last_convolution = np.array(input_shape) // 8 self.parameters['clayer'] = 8 self.parameters['N'] = int(np.prod(last_convolution)*self.parameters['clayer'] // self.parameters['M']) return [Reshape((*input_shape,1)), GaussianNoise(0.1), BN(), Convolution2D(16,(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), Dropout(self.parameters['dropout']), BN(), MaxPooling2D((2,2)), Convolution2D(64,(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), SpatialDropout2D(self.parameters['dropout']), BN(), MaxPooling2D((2,2)), Convolution2D(64,(3,3), activation=self.parameters['activation'],padding='same', use_bias=False), SpatialDropout2D(self.parameters['dropout']), BN(), MaxPooling2D((2,2)), Convolution2D(64,(1,1), activation=self.parameters['activation'],padding='same', use_bias=False), SpatialDropout2D(self.parameters['dropout']), BN(), Convolution2D(self.parameters['clayer'],(1,1), padding='same'), flatten, ] # mixin classes ############################################################### # Now effectively 3 subclasses; GumbelSoftmax in the output, Convolution, Gaussian. # there are 4 more results of mixins:
def load_model(input_shape, num_classes): model = Sequential() model.add(Convolution2D(6, kernel_size=(3, 3), activation='relu', input_shape=input_shape, padding="same")) model.add(Convolution2D(32, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Convolution2D(64, kernel_size=(3, 3), border_mode='same', activation='relu')) model.add(Convolution2D(64, kernel_size=(3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) return model
def GatedPixelCNN(input_shape, filters, depth, latent=None, build=True): height, width, channels = input_shape palette = 256 # TODO: Make it scalable to any amount of palette. input_img = Input(shape=input_shape, name=str(channels)+'_channels_'+str(palette)+'_palette') latent_vector = None if latent is not None: latent_vector = Input(shape=(latent,), name='latent_vector') model = GatedCNNs(filters, depth, latent_vector)(*GatedCNN(filters, latent_vector)(input_img)) for _ in range(2): model = Convolution2D(filters, 1, 1, border_mode='valid')(model) model = PReLU()(model) outs = OutChannels(*input_shape, masked=False, palette=palette)(model) if build: model = Model(input=[input_img, latent_vector] if latent is not None else input_img, output=outs) model.compile(optimizer=Nadam(), loss='binary_crossentropy' if channels == 1 else 'sparse_categorical_crossentropy') return model
def __call__(self, model1, model2=None): if model2 is None: h_model = model1 filter_size = (7, 7) else: h_model = model2 filter_size = (3, 3) v_model = PaddedConvolution2D(self.filters, filter_size, 'vertical')(model1) feed_vertical = FeedVertical(self.filters)(v_model) v_model = GatedBlock(self.filters, h=self.h)(v_model) h_model_new = PaddedConvolution2D(self.filters, filter_size, 'horizontal', 'A')(h_model) h_model_new = GatedBlock(self.filters, v=feed_vertical, h=self.h, crop_right=True)(h_model_new) h_model_new = Convolution2D(self.filters, 1, 1, border_mode='valid')(h_model_new) return (v_model, h_model_new if model2 is None else Merge(mode='sum')([h_model_new, h_model]))
def conv2d_bn(x, nb_filter, nb_row, nb_col, border_mode='same', subsample=(1, 1), name=None): '''Utility function to apply conv + BN. ''' if name is not None: bn_name = name + '_bn' conv_name = name + '_conv' else: bn_name = None conv_name = None if K.image_dim_ordering() == 'th': bn_axis = 1 else: bn_axis = 3 x = Convolution2D(nb_filter, nb_row, nb_col, subsample=subsample, activation='relu', border_mode=border_mode, name=conv_name)(x) x = BatchNormalization(axis=bn_axis, name=bn_name)(x) return x
def fire_module(x, fire_id, squeeze=16, expand=64): s_id = 'fire' + str(fire_id) + '/' if K.image_data_format() == 'channels_first': channel_axis = 1 else: channel_axis = 3 x = Convolution2D(squeeze, (1, 1), padding='valid', name=s_id + sq1x1)(x) x = Activation('relu', name=s_id + relu + sq1x1)(x) left = Convolution2D(expand, (1, 1), padding='valid', name=s_id + exp1x1)(x) left = Activation('relu', name=s_id + relu + exp1x1)(left) right = Convolution2D(expand, (3, 3), padding='same', name=s_id + exp3x3)(x) right = Activation('relu', name=s_id + relu + exp3x3)(right) x = concatenate([left, right], axis=channel_axis, name=s_id + 'concat') return x # Original SqueezeNet from paper.
def double_conv_layer(x, size, dropout, batch_norm): from keras.models import Model from keras.layers import Input, merge, Convolution2D, MaxPooling2D, UpSampling2D from keras.layers.normalization import BatchNormalization from keras.layers.core import Dropout, Activation conv = Convolution2D(size, 3, 3, border_mode='same')(x) if batch_norm == True: conv = BatchNormalization(mode=0, axis=1)(conv) conv = Activation('relu')(conv) conv = Convolution2D(size, 3, 3, border_mode='same')(conv) if batch_norm == True: conv = BatchNormalization(mode=0, axis=1)(conv) conv = Activation('relu')(conv) if dropout > 0: conv = Dropout(dropout)(conv) return conv
def res_block(input_tensor, nb_filters=16, block=0, subsample_factor=1): subsample = (subsample_factor, subsample_factor) x = BatchNormalization(axis=3)(input_tensor) x = Activation('relu')(x) x = Convolution2D(nb_filters, 3, 3, subsample=subsample, border_mode='same')(x) x = BatchNormalization(axis=3)(x) x = Activation('relu')(x) x = Convolution2D(nb_filters, 3, 3, subsample=(1, 1), border_mode='same')(x) if subsample_factor > 1: shortcut = Convolution2D(nb_filters, 1, 1, subsample=subsample, border_mode='same')(input_tensor) else: shortcut = input_tensor x = merge([x, shortcut], mode='sum') return x
def addLayer(previousLayer, nChannels, nOutChannels, dropRate, blockNum): bn = BatchNormalization(name = 'denseb_BatchNorm_{}'.format(blockNum) , axis = 1)(previousLayer) relu = Activation('relu', name ='denseb_relu_{}'.format(blockNum))(bn) conv = Convolution2D(nOutChannels, 3, 3, border_mode='same', name='denseb_conv_{}'.format(blockNum))(relu) if dropRate is not None: dp = Dropout(dropRate, name='denseb_dropout_{}'.format)(conv) return merge([dp, previousLayer], mode='concat', concat_axis=1) else: return merge([conv, previousLayer], mode='concat', concat_axis=1)
def addTransition(previousLayer, nChannels, nOutChannels, dropRate, blockNum): bn = BatchNormalization(name = 'tr_BatchNorm_{}'.format(blockNum), axis = 1)(previousLayer) relu = Activation('relu', name ='tr_relu_{}'.format(blockNum))(bn) conv = Convolution2D(nOutChannels, 1, 1, border_mode='same', name='tr_conv_{}'.format(blockNum))(relu) if dropRate is not None: dp = Dropout(dropRate, name='tr_dropout_{}'.format)(conv) avgPool = AveragePooling2D(pool_size=(2, 2))(dp) else: avgPool = AveragePooling2D(pool_size=(2, 2))(conv) return avgPool
def create_conv_model(self): # This is the place where neural network model initialized init = 'glorot_uniform' self.state_in = Input(self.state_dim) self.l1 = Convolution2D(32, 8, 8, activation='elu', init=init, subsample=(4, 4), border_mode='same')( self.state_in) self.l2 = Convolution2D(64, 4, 4, activation='elu', init=init, subsample=(2, 2), border_mode='same')( self.l1) # self.l3 = Convolution2D(64, 3, 3, activation='relu', init=init, subsample=(1, 1), border_mode='same')( # self.l2) self.l3 = self.l2 self.h = Flatten()(self.l3) self.hidden = Dense(256, init=init, activation='elu')(self.h) self.value = Dense(1, init=init)(self.hidden) self.policy = Dense(self.action_dim, init=init, activation='softmax')(self.hidden) self.q_values = self.entropy_coef * (Theano.log(self.policy + 1e-18) - Theano.tile(Theano.sum(Theano.log(self.policy + 1e-18) * self.policy, axis=[1], keepdims=True), (1, self.action_dim))) self.q_values = self.q_values + Theano.tile(self.value, (1, self.action_dim)) self.model = Model(self.state_in, output=[self.policy, self.value])
def createModel(w=None,h=None): # Input placeholder original = Input(shape=(w, h, 4), name='icon_goes_here') # Model layer stack x = original x = Convolution2D(64, 4, 4, activation='relu', border_mode='same', b_regularizer=l2(0.1))(x) x = Convolution2D(64, 4, 4, activation='relu', border_mode='same', b_regularizer=l2(0.1))(x) x = Convolution2D(64, 4, 4, activation='relu', border_mode='same', b_regularizer=l2(0.1))(x) x = Convolution2D(64, 4, 4, activation='relu', border_mode='same', b_regularizer=l2(0.1))(x) x = AveragePooling2D((2, 2), border_mode='valid')(x) x = Convolution2D(16, 4, 4, activation='relu', border_mode='same', b_regularizer=l2(0.1))(x) x = Convolution2D(4, 4, 4, activation='relu', border_mode='same', b_regularizer=l2(0.1))(x) downscaled = x # Compile model hintbot = Model(input=original, output=downscaled) hintbot.compile(optimizer='adam', loss='mean_squared_error') # Train if (os.path.isfile(load_weights_filepath)): hintbot.load_weights(load_weights_filepath) return hintbot
def build_model(self, dataset, nb_classes): self.model = Sequential() self.model.add(Convolution2D(32, (3, 3), padding='same', input_shape=dataset.x_train.shape[1:])) self.model.add(Activation('relu')) self.model.add(Convolution2D(32, (3, 3))) self.model.add(Activation('relu')) self.model.add(MaxPooling2D(pool_size=(2, 2))) self.model.add(Dropout(0.25)) self.model.add(Convolution2D(64, (3, 3), padding='same')) self.model.add(Activation('relu')) self.model.add(Convolution2D(64, (3, 3))) self.model.add(Activation('relu')) self.model.add(MaxPooling2D(pool_size=(2, 2))) self.model.add(Dropout(0.25)) self.model.add(Flatten()) self.model.add(Dense(512)) self.model.add(Activation('relu')) self.model.add(Dropout(0.5)) self.model.add(Dense(nb_classes)) self.model.add(Activation('softmax')) self.model.summary()
def get_model(img_channels, img_width, img_height, dropout=0.5): model = Sequential() model.add(Convolution2D(32, 3, 3, input_shape=( img_channels, img_width, img_height))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, 3, 3)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Convolution2D(32, 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(Dropout(dropout)) model.add(Dense(1)) model.add(Activation('sigmoid')) return model
def get_model(shape, dropout=0.5, path=None): print('building neural network') model=Sequential() model.add(Convolution2D(512, 3, 3, border_mode='same', input_shape=shape)) model.add(Activation('relu')) model.add(Convolution2D(512, 3, 3, border_mode='same')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(SpatialDropout2D(dropout)) model.add(Flatten())#input_shape=shape)) # model.add(Dense(4096)) # model.add(Activation('relu')) # model.add(Dropout(0.5)) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) #model.add(Activation('linear')) return model
def buildmodel(opt): print("Now we build the model") model = Sequential() model.add(Convolution2D(32, 8, 8, subsample=(4,4), border_mode='same',input_shape=(80,80,1))) model.add(Activation('relu')) model.add(Convolution2D(64, 4, 4, subsample=(2,2), border_mode='same')) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3, subsample=(1,1), border_mode='same')) model.add(Activation('relu')) model.add(Flatten()) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dense(1)) model.compile(loss='binary_crossentropy',optimizer=opt) print("We finish building the model") return model
def _adversary(): model = Sequential() model.add(Convolution2D( 64, 5, 5, border_mode='same', input_shape=(3, 32, 32),subsample=(2,2))) model.add(LeakyReLU(0.2)) model.add(Convolution2D(128, 5, 5,subsample=(2,2))) model.add(BatchNormalization(mode=2)) model.add(LeakyReLU(0.2)) model.add(Flatten()) model.add(Dense(1024)) model.add(LeakyReLU()) model.add(Dense(1)) model.add(Activation('sigmoid')) return model
def conv_2d(filters, kernel_shape, strides, padding): """ Defines the right convolutional layer according to the version of Keras that is installed. :param filters: (required integer) the dimensionality of the output space (i.e. the number output of filters in the convolution) :param kernel_shape: (required tuple or list of 2 integers) specifies the strides of the convolution along the width and height. :param padding: (required string) can be either 'valid' (no padding around input or feature map) or 'same' (pad to ensure that the output feature map size is identical to the layer input) :return: the Keras layer """ if LooseVersion(keras.__version__) >= LooseVersion('2.0.0'): return Conv2D(filters=filters, kernel_size=kernel_shape, strides=strides, padding=padding) else: return Convolution2D(filters, kernel_shape[0], kernel_shape[1], subsample=strides, border_mode=padding) # the cnn_model used
def mnist_cnn(args, input_image): shape = (args.channels, args.height, args.width) x = Convolution2D(32, 5, 5, activation='relu', border_mode='valid', input_shape=shape)(input_image) x = MaxPooling2D((2,2))(x) x = Convolution2D(64, 3, 3, activation='relu', border_mode='same')(x) x = Dropout(0.2)(x) x = MaxPooling2D((2,2))(x) x = Flatten()(x) x = Dense(128, activation='relu')(x) x = Dense(64, activation='relu')(x) predictions = Dense(args.num_labels, activation='softmax')(x) # this creates a model that includes # the Input layer and three Dense layers model = Model(input=input_image, output=predictions) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.summary() return model
def xtest_net(self): input_shape = (28,28,1) model = Sequential() model.add(MaxPooling2D(pool_size=(3,3), input_shape = input_shape)) print("----->", model.layers[-1].output_shape) model.add(MaxPooling2D(pool_size=(3,3))) print("----->", model.layers[-1].output_shape) model.add(MaxPooling2D(pool_size=(3,3))) print("----->", model.layers[-1].output_shape) if model.layers[-1].output_shape[1] >= 2 and model.layers[-1].output_shape[2] >= 2: model.add(MaxPooling2D(pool_size=(2,2))) print("----->", model.layers[-1].output_shape) model.add(Flatten()) #model.add(Convolution2D(20, 5, 5, border_mode='same')) #model.add(MaxPooling2D(pool_size=(2,2))) #model.add(MaxPooling2D(pool_size=(2,2))) #model.add(MaxPooling2D(pool_size=(2,2))) #model.add(Flatten()) model.summary()
def conv2d_bn(x, nb_filter, nb_row, nb_col, border_mode='same', subsample=(1, 1), bias=False): """ Utility function to apply conv + BN. (Slightly modified from https://github.com/fchollet/keras/blob/master/keras/applications/inception_v3.py) """ if K.image_dim_ordering() == "th": channel_axis = 1 else: channel_axis = -1 x = Convolution2D(nb_filter, nb_row, nb_col, subsample=subsample, border_mode=border_mode, bias=bias)(x) x = BatchNormalization(axis=channel_axis)(x) x = Activation('relu')(x) return x
def conv2d_bn(x, nb_filter, nb_row, nb_col, border_mode='same', subsample=(1, 1), name=None): """ Utility function to apply conv + BN for Inception V3. """ if name is not None: bn_name = name + '_bn' conv_name = name + '_conv' else: bn_name = None conv_name = None bn_axis = 1 x = Convolution2D(nb_filter, nb_row, nb_col, subsample=subsample, activation='relu', border_mode=border_mode, name=conv_name)(x) x = BatchNormalization(axis=bn_axis, name=bn_name)(x) return x
def m6_1(): model.add(Convolution2D(32, 3, 3, init=my_init, input_shape=input_shape)) model.add(Activation('relu')) model.add(Convolution2D(32, 3, 3, init=my_init)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Convolution2D(64, 3, 3, init=my_init)) model.add(Activation('relu')) model.add(Convolution2D(64, 3, 3, init=my_init)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(256, init=my_init)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(nb_classes)) model.add(Activation('softmax'))
def getNN(n): """ ????????? ???????????VGG??? """ nn=Sequential() nn.add(Convolution2D(32,(3,3),input_shape=(30,30,1),activation='relu')) nn.add(MaxPooling2D(pool_size=(2, 2))) nn.add(Convolution2D(16,(3,3),activation='relu')) nn.add(Dropout(0.2)) nn.add(Convolution2D(8,(3,3),activation='relu')) nn.add(MaxPooling2D(pool_size=(2, 2))) nn.add(Convolution2D(8,(3,3),activation='relu')) nn.add(Dense(50,activation='tanh')) nn.add(Dropout(0.2)) nn.add(Dense(50,activation='tanh')) nn.add(Flatten()) nn.add(Dense(n,activation='sigmoid')) nn.compile(optimizer='rmsprop',loss='categorical_crossentropy') return nn
def unet_water(input_shapes, n_classes): inputs = [Input(shape, name=name) for name, shape in input_shapes.items()] conv1 = conv_block(merge(inputs, mode='concat', concat_axis=1), 64) conv1 = conv_block(conv1, 64) pool1 = pool_block(conv1, 2) conv2 = conv_block(pool1, 96) conv2 = conv_block(conv2, 96) pool2 = pool_block(conv2, 2) conv3 = conv_block(pool2, 128) conv3 = conv_block(conv3, 128) up8 = merge_block(conv3, conv2) conv8 = conv_block(up8, 96) conv8 = conv_block(conv8, 96) up9 = merge_block(conv8, conv1) conv9 = conv_block(up9, 64) conv9 = conv_block(conv9, 64) conv10 = Convolution2D(n_classes, 3, 3, activation='sigmoid', border_mode='same')(conv9) return Model(input=inputs, output=conv10)
def create_trainable_model(self,nb_event,nb_type,nb_feature): from keras.layers import Input, Dense, Flatten, Convolution2D, Activation, Dropout, merge from keras.models import Model from keras.regularizers import l1,l2 x = Input(batch_shape=(1, nb_event, nb_type, nb_feature), dtype='float') y = Convolution2D(128, kernel_size=[nb_event-10+1, 1], strides=(2,1), activation='relu')(x) y = Dropout(0.5)(y) y = Convolution2D(128, kernel_size=[3, nb_type], activation='relu')(y) y = Dropout(0.5)(y) y = Flatten()(y) y = Dense(2,activation='softmax')(y) model = Model(inputs=[x], outputs=[y], name='dis_output') self.model = model return model
def create_trainable_wasserstein(self,nb_event,nb_type,nb_feature,wgan_clip=1.): from keras.layers import Input, Dense, Flatten, Convolution2D, Activation, Dropout, merge from keras.models import Model from keras.constraints import MinMaxNorm constraint = MinMaxNorm(min_value= - wgan_clip,max_value=wgan_clip) x = Input(batch_shape=(1, nb_event, nb_type, nb_feature), dtype='float') y = Convolution2D(128, kernel_size=[nb_event-10+1, 1], strides=(2,1), activation='relu', kernel_constraint=constraint,bias_constraint=constraint)(x) y = Dropout(0.5)(y) y = Convolution2D(128, kernel_size=[3, nb_type], activation='relu', kernel_constraint=constraint,bias_constraint=constraint)(y) y = Dropout(0.5)(y) y = Flatten()(y) y = Dense(2,activation=None, kernel_constraint=constraint,bias_constraint=constraint)(y) model = Model(inputs=[x], outputs=[y], name='dis_output') self.model = model return model
def __init__(self, **kwargs): super(KerasLenetModel, self).__init__(**kwargs) norm_shape = self.norm_shape self.model = Sequential() self.model.add(Convolution2D(32, (3, 3), activation='relu', input_shape=(norm_shape[0], norm_shape[1], 1))) self.model.add(Convolution2D(32, (3, 3), activation='relu')) self.model.add(MaxPooling2D(pool_size=(2,2))) self.model.add(Dropout(0.25)) self.model.add(Flatten()) self.model.add(Dense(128, activation='relu')) self.model.add(Dropout(0.5)) self.model.add(Dense(self.max_n_label, activation='softmax')) # 8. Compile model self.model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
def build_model(self, dataset, nb_classes=2): self.model = Sequential() self.model.add(Convolution2D(32, 3, 3, border_mode='same', input_shape=dataset.X_train.shape[1:])) self.model.add(Activation('relu')) self.model.add(Convolution2D(32, 3, 3)) self.model.add(Activation('relu')) self.model.add(MaxPooling2D(pool_size=(2, 2))) self.model.add(Dropout(0.25)) self.model.add(Convolution2D(64, 3, 3, border_mode='same')) self.model.add(Activation('relu')) self.model.add(Convolution2D(64, 3, 3)) self.model.add(Activation('relu')) self.model.add(MaxPooling2D(pool_size=(2, 2))) self.model.add(Dropout(0.25)) self.model.add(Flatten()) # multi -> one dimension self.model.add(Dense(512)) self.model.add(Activation('relu')) self.model.add(Dropout(0.5)) self.model.add(Dense(nb_classes)) self.model.add(Activation('softmax')) self.model.summary()