本文整理匯總了Python中keras.layers.core.Lambda方法的典型用法代碼示例。如果您正苦於以下問題:Python core.Lambda方法的具體用法?Python core.Lambda怎麽用?Python core.Lambda使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類keras.layers.core
的用法示例。
在下文中一共展示了core.Lambda方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: crosschannelnormalization
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def crosschannelnormalization(alpha=1e-4, k=2, beta=0.75, n=5, **kwargs):
"""
This is the function used for cross channel normalization in the original
Alexnet
"""
def f(X):
b, ch, r, c = X.shape
half = n // 2
square = K.square(X)
extra_channels = K.spatial_2d_padding(K.permute_dimensions(square, (0, 2, 3, 1))
, (0, half))
extra_channels = K.permute_dimensions(extra_channels, (0, 3, 1, 2))
scale = k
for i in range(n):
scale += alpha * extra_channels[:, i:i + ch, :, :]
scale = scale ** beta
return X / scale
return Lambda(f, output_shape=lambda input_shape: input_shape, **kwargs)
示例2: splittensor
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def splittensor(axis=1, ratio_split=1, id_split=0, **kwargs):
def f(X):
div = X.shape[axis] // ratio_split
if axis == 0:
output = X[id_split * div:(id_split + 1) * div, :, :, :]
elif axis == 1:
output = X[:, id_split * div:(id_split + 1) * div, :, :]
elif axis == 2:
output = X[:, :, id_split * div:(id_split + 1) * div, :]
elif axis == 3:
output = X[:, :, :, id_split * div:(id_split + 1) * div]
else:
raise ValueError('This axis is not possible')
return output
def g(input_shape):
output_shape = list(input_shape)
output_shape[axis] = output_shape[axis] // ratio_split
return tuple(output_shape)
return Lambda(f, output_shape=lambda input_shape: g(input_shape), **kwargs)
示例3: get_model
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def get_model(num_users, num_items, latent_dim, regs=[0,0]):
# Input variables
user_input = Input(shape=(1,), dtype='int32', name = 'user_input')
item_input = Input(shape=(1,), dtype='int32', name = 'item_input')
MF_Embedding_User = Embedding(input_dim = num_users, output_dim = latent_dim, name = 'user_embedding',
init = init_normal, W_regularizer = l2(regs[0]), input_length=1)
MF_Embedding_Item = Embedding(input_dim = num_items, output_dim = latent_dim, name = 'item_embedding',
init = init_normal, W_regularizer = l2(regs[1]), input_length=1)
# Crucial to flatten an embedding vector!
user_latent = Flatten()(MF_Embedding_User(user_input))
item_latent = Flatten()(MF_Embedding_Item(item_input))
# Element-wise product of user and item embeddings
predict_vector = merge([user_latent, item_latent], mode = 'mul')
# Final prediction layer
#prediction = Lambda(lambda x: K.sigmoid(K.sum(x)), output_shape=(1,))(predict_vector)
prediction = Dense(1, activation='sigmoid', init='lecun_uniform', name = 'prediction')(predict_vector)
model = Model(input=[user_input, item_input],
output=prediction)
return model
示例4: crosschannelnormalization
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def crosschannelnormalization(alpha = 1e-4, k=2, beta=0.75, n=5,**kwargs):
"""
This is the function used for cross channel normalization in the original
Alexnet
"""
def f(X):
b, ch, r, c = X.shape
half = n // 2
square = K.square(X)
extra_channels = K.spatial_2d_padding(K.permute_dimensions(square, (0,2,3,1))
, (0,half))
extra_channels = K.permute_dimensions(extra_channels, (0,3,1,2))
scale = k
for i in range(n):
scale += alpha * extra_channels[:,i:i+ch,:,:]
scale = scale ** beta
return X / scale
return Lambda(f, output_shape=lambda input_shape:input_shape,**kwargs)
示例5: splittensor
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def splittensor(axis=1, ratio_split=1, id_split=0,**kwargs):
def f(X):
div = X.shape[axis] // ratio_split
if axis == 0:
output = X[id_split*div:(id_split+1)*div,:,:,:]
elif axis == 1:
output = X[:, id_split*div:(id_split+1)*div, :, :]
elif axis == 2:
output = X[:,:,id_split*div:(id_split+1)*div,:]
elif axis == 3:
output == X[:,:,:,id_split*div:(id_split+1)*div]
else:
raise ValueError("This axis is not possible")
return output
def g(input_shape):
output_shape=list(input_shape)
output_shape[axis] = output_shape[axis] // ratio_split
return tuple(output_shape)
return Lambda(f,output_shape=lambda input_shape:g(input_shape),**kwargs)
示例6: crosschannelnormalization
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def crosschannelnormalization(alpha = 1e-4, k=2, beta=0.75, n=5,**kwargs):
"""
This is the function used for cross channel normalization in the original
Alexnet
"""
def f(X):
b, ch, r, c = X.shape
half = n // 2
square = K.square(X)
extra_channels = K.spatial_2d_padding(K.permute_dimensions(square, (0,2,3,1)))
extra_channels = K.permute_dimensions(extra_channels, (0,3,1,2))
scale = k
for i in range(n):
scale += alpha * extra_channels[:,i:i+ch,:,:]
scale = scale ** beta
return X / scale
return Lambda(f, output_shape=lambda input_shape:input_shape,**kwargs)
示例7: splittensor
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def splittensor(axis=1, ratio_split=1, id_split=0,**kwargs):
def f(X):
div = X.shape[axis] // ratio_split
if axis == 0:
output = X[id_split*div:(id_split+1)*div,:,:,:]
elif axis == 1:
output = X[:, id_split*div:(id_split+1)*div, :, :]
elif axis == 2:
output = X[:,:,id_split*div:(id_split+1)*div,:]
elif axis == 3:
output = X[:,:,:,id_split*div:(id_split+1)*div]
else:
raise ValueError("This axis is not possible")
return output
def g(input_shape):
output_shape=list(input_shape)
output_shape[axis] = output_shape[axis] // ratio_split
return tuple(output_shape)
return Lambda(f,output_shape=lambda input_shape:g(input_shape),**kwargs)
示例8: emit_Slice
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def emit_Slice(self, IR_node, in_scope=False):
# It arouses some problems:
# it can be implemented by Lambda Layer
# https://github.com/keras-team/keras/issues/890
self.used_layers.add(IR_node.type)
extra_str = ""
if IR_node.get_attr('strides'):
extra_str += "strides={}".format(IR_node.get_attr('strides'))
if IR_node.get_attr('begin_mask'):
extra_str += ", begin_mask={}".format(IR_node.get_attr('begin_mask'))
if IR_node.get_attr('end_mask'):
extra_str += ", end_mask={}".format(IR_node.get_attr('end_mask'))
if IR_node.get_attr('shrink_axis_mask'):
extra_str += ", shrink_axis_mask={}".format(IR_node.get_attr('shrink_axis_mask'))
code = "{:<15} = __slice({}, {}, {}, {})".format(
IR_node.variable_name,
self.parent_variable_name(IR_node),
IR_node.get_attr('starts'),
IR_node.get_attr('ends'),
extra_str)
return code
示例9: _layer_Fill
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def _layer_Fill(self):
self.add_body(0, '''
def __fill(input, value):
class Fill(keras.layers.Layer):
def call(self, input):
if keras.backend.backend() =='tensorflow':
output = tf.fill(input, value)
else:
raise NotImplementedError
self.output_dim = [dim.value for dim in output.shape]
return output
def compute_output_shape(self, input_shape):
return tuple(self.output_dim)
# output = Lambda(lambda x: tf.fill(x, value))(input)
output = Fill()(input)
# return output
''')
示例10: _layer_Shape
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def _layer_Shape(self):
self.add_body(0, '''
def __shape(input):
return Lambda(lambda x: tf.shape(x))(input)
''')
# def _layer_Constant(self):
# self.add_body(0, '''
# class my_constant(keras.layers.Layer):
# def __init__(self, value, **kwargs):
# super(my_constant, self).__init__(**kwargs)
# self._value = value
# # the input is dummy, just for creating keras graph.
# def call(self, dummy):
# res = K.constant(self._value)
# self.output_shapes = K.int_shape(res)
# return res
# def compute_output_shape(self, input_shape):
# return self.output_shapes
# ''')
示例11: createModel
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def createModel(patchSize, patchSize_down=None, ScaleFactor=1, learningRate=1e-3, optimizer='SGD',
dr_rate=0.0, input_dr_rate=0.0, max_norm=5, iPReLU=0, l2_reg=1e-6):
# Total params: 453,570
input_orig = Input(shape=(1, int(patchSize[0]), int(patchSize[1])))
path_orig_output = fConveBlock(input_orig)
input_down = Input(shape=(1, int(patchSize_down[0]), int(patchSize_down[1])))
path_down = fConveBlock(input_down)
path_down_output = fUpSample(path_down, ScaleFactor)
multi_scale_connect = fconcatenate(path_orig_output, path_down_output)
# fully connect layer as dense
flat_out = Flatten()(multi_scale_connect)
dropout_out = Dropout(dr_rate)(flat_out)
dense_out = Dense(units=2,
kernel_initializer='normal',
kernel_regularizer=l2(l2_reg))(dropout_out)
# Fully connected layer as convo with 1X1 ?
output_fc1 = Activation('softmax')(dense_out)
output_fc2 = Activation('softmax')(dense_out)
output_p1 = Lambda(sliceP1,name='path1_output',output_shape=(None,2))(output_fc1)
output_p2 = Lambda(sliceP2,name='path2_output',output_shape=(None,2))(output_fc2)
cnn_ms = Model(inputs=[input_orig, input_down], outputs=[output_p1,output_p2])
return cnn_ms
示例12: get_model
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def get_model(img_h, nclass):
input = Input(shape=(img_h, None, 1), name='the_input')
y_pred = densenet.dense_cnn(input, nclass)
basemodel = Model(inputs=input, outputs=y_pred)
basemodel.summary()
labels = Input(name='the_labels', shape=[None], dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')
loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])
model = Model(inputs=[input, labels, input_length, label_length], outputs=loss_out)
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer='adam', metrics=['accuracy'])
return basemodel, model
示例13: adverse_model
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def adverse_model(discriminator):
train_input = Input(shape=(None,), dtype='int32')
hypo_input = Input(shape=(None,), dtype='int32')
def margin_opt(inputs):
assert len(inputs) == 2, ('Margin Output needs '
'2 inputs, %d given' % len(inputs))
return K.log(inputs[0]) + K.log(1-inputs[1])
margin = Lambda(margin_opt, output_shape=(lambda s : (None, 1)))\
([discriminator(train_input), discriminator(hypo_input)])
adverserial = Model([train_input, hypo_input], margin)
adverserial.compile(loss=minimize, optimizer='adam')
return adverserial
示例14: build_siamese_resnet_18
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def build_siamese_resnet_18(input_shape, num_outputs):
channels, height, width = input_shape
branch_channels = 3 #channels / 2
branch_input_shape = (branch_channels, height, width)
branch = ResnetBuilder.build_resnet_18(branch_input_shape, NUM_EMBEDDING, False)
input = Input(shape=(height, width, channels))
first_branch = branch(Lambda(lambda x: x[:, :, :, :3])(input))
second_branch = branch(Lambda(lambda x: x[:, :, :, 3:])(input))
if NORMALIZATION_ON:
first_branch = Lambda(lambda x: K.l2_normalize(x, axis=1))(first_branch)
second_branch = Lambda(lambda x: K.l2_normalize(x, axis=1))(second_branch)
raw_result = concatenate([first_branch, second_branch])
output = _top_network(raw_result)
# raw_result = dot([first_branch, second_branch], axes=1)
# result = Lambda(lambda x: (K.clip(x, 0.5, 1) - 0.5) * 2.0)(raw_result)
# negated_result = Lambda(lambda x: 1 - x)(result)
# output = concatenate([negated_result, result])
return Model(inputs=input, outputs=output)
示例15: create_model
# 需要導入模塊: from keras.layers import core [as 別名]
# 或者: from keras.layers.core import Lambda [as 別名]
def create_model(gpu):
with tf.device(gpu):
input = Input((1280, 1918, len(dirs)))
x = Lambda(lambda x: K.mean(x, axis=-1, keepdims=True))(input)
model = Model(input, x)
model.summary()
return model