Keras example — using the lambda layer

Keras provides a lambda layer; it can wrap a function of your choosing. For example, if you wanted to build a layer that squares its input tensor element-wise, you can say simply:

model.add(lambda(lambda x: x ** 2))

You can also wrap functions within a lambda layer. For example, if you want to build a custom layer that computes the element-wise euclidean distance between two input tensors, you would define the function to compute the value itself, as well as one that returns the output shape from this function, like so:

def euclidean_distance(vecs):    x, y = vecs    return K.sqrt(K.sum(K.square(x - y), axis=1, keepdims=True))def euclidean_distance_output_shape(shapes):    shape1, shape2 = shapes return (shape1[0], ...

Get Deep Learning with Keras now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.