How to implement keras.layers.core.Lambda in pytorch

add a x -> x^2 layer

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

1 Like

That is one of the cases where it’s better not to use nn.Sequential, and inherit from model yourself and perform the operations that you want.
For example

class MyModel(nn.Module):
    def forward(self, input):
        return input ** 2 + 1
model = MyModel()

But if you want an equivalent to a Lambda layer, you can write it very easily in pytorch

class LambdaLayer(nn.Module):
    def __init__(self, lambd):
        super(LambdaLayer, self).__init__()
        self.lambd = lambd
    def forward(self, x):
        return self.lambd(x)

And now you can use it as you would in keras

model.add(Lambda(lambda x: x ** 2))
15 Likes

Your method is valid,thank you very much