cuser
cuser

Reputation: 432

lambda layer function definition without tf.keras.backend (Python Keras Package)

tf.keras.layers.Lambda documentation explains how a function can be defined in a lambda layer. That document provides the following function as an example,

def antirectifier(x):

    x -= K.mean(x, axis=1, keepdims=True)
    x = K.l2_normalize(x, axis=1)

    pos = K.relu(x)
    neg = K.relu(-x)

    return K.concatenate([pos, neg], axis=1)

model.add(Lambda(antirectifier))

But according to that, tf.keras.backend must be used to conduct operations on the input Tensor object.

Is there any way we can use default python packages and user-defined function to define the steps of a lambda function.

If it's possible, please be kind enough to provide some examples.

Upvotes: 1

Views: 967

Answers (2)

Daniel Möller
Daniel Möller

Reputation: 86600

If you're not using import tensorflow and its functions, there is absolutely no problem.

The code is perfect and that's it.

Just import keras.backend as K

Example rounded = K.round(x)


This is Keras independent documentation: https://keras.io/layers/core/#lambda

Upvotes: 2

Leo K
Leo K

Reputation: 5354

There is no requirement to use tf.keras.backend as such. The function that you give to keras.layers.Lambda() can do anything you want with the input tensor.

However, most 'default python packages' are simply not able to work with a Tensor object (e.g., as you noted in your comment, round(x) won't work on it).

You can use most of the Python language constructs on a tensor x (such as x*2, or x+y, etc) - the tensor objects implement those. Likewise, you can call some 'regular' python libraries, as long as they use only operations that are supported by tensors. For everything else, you will need to use either methods of the tensor object or appropriate Keras library functions - or write your own.

Upvotes: 1

Related Questions