Search code examples
pythonlambdaactivation-functionrelu

relu activation function using lambda


Hi I want to implement a lambda function in python which gives me back x if x> 1 and 0 otherhwise (relu):

so I have smth. like:

p = [-1,0,2,4,-3,1]

relu_vals = lambda x: x if x>0 else 0 

print(relu_vals(p))

It is important to note that I want to pass the value of lambda to a function

but it fails....


Solution

  • You want to use map to apply this function on every element of the list

    list(map(relu_vals, p))
    

    gives you

    [0, 0, 2, 4, 0, 1]
    

    Also it's better to define the lambda function within map if you are not planning to use it again

    print(list(map(lambda x: x if x > 0 else 0, p)))