relu activation function using lambda - python

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....

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)))

You program is right, but need some modification.
Try this,
>>> p = [-1,0,2,4,-3,1]
>>> relu_vals = lambda x: x if x>0 else 0
>>> [relu_vals(i) for i in p]
[0, 0, 2, 4, 0, 1]

Related

Lambda with if statement

Let say I have a list called "y_pred", I want to write a lambda function to change the value to 0 if the value is less than 0.
Before: y_pred=[1,2,3,-1]
After: y_pred=[1,2,3,0]
I wrote something like this, and return an error message
y_pred=list(lambda x: 0 if y_pred[x]<0 else y_pred[x])
TypeError: 'function' object is not iterable
You want an expression (a if cond else b) mapped over your list:
y_pred_before = [1, 2, 3, -1]
y_pred_after = list(map(lambda x: 0 if x < 0 else x, y_pred_before))
# => [1, 2, 3, 0]
A shorter form of the same thing is a list comprehension ([expr for item in iterable]):
y_pred_after = [0 if x < 0 else x for x in y_pred_before]
Your error "TypeError: 'function' object is not iterable" comes from the fact that list() tries to iterate over its argument. You've given it a lambda, i.e. a function. And functions are not iterable.
You meant to iterate over the results of the function. That's what map() does.
You can use numpy (assuming that using lambda is not a requirement):
import numpy as np
y_pred = np.array(y_pred)
y_pred[y_pred < 0] = 0
y_pred
Output:
array([1, 2, 3, 0])
An easy way to do this with list comprehension:
y_pred=[x if x>0 else 0 for x in y_pred_before]

Passing a list of conditions to a function to be checked

I have an list of n conditions, for example
cond = [x > 0, x < 10, x == 2]
where x is any variable I wish to test against those conditions. I can easily test these conditions if x is already defined, but what if I want to pass this set of conditions to another function where x has not already been defined? Is there a way in Python to pass this set of conditions while keeping x an anonymous variable? If not, is there an alternative?
You're probably looking for an anonymous function or lambda
This could be
cond = [
lambda x: x > 0,
lambda x: x < 10,
lambda x: x == 2,
]
>>> [f(5) for f in cond]
[True, True, False]
or as #John Coleman suggests in a comment you could have them all together
cond = lambda x: all((x > 0, x < 10, x == 2)) # tuple of booleans
>>> cond(5)
False
>>> cond(2)
True
If it's the same as the example, you could check the last case == 2

Python: How can I add a parameter to an itertools function?

I want to create a function which returns a function creating an iterator (like something from itertools), but with a parameter set by the outer function.
For example, say I want to take a running sum, but exclude values that are larger than a given cutoff (which is the parameter of the function).
So, say I have a list like this:
x = [1, 1, 1, 1, 25, 1, 1]
And I want a function that would take the running sum, but ignore values greater than 10, to give me an output like this:
y = [1, 2, 3, 4, 4, 5, 6]
This code will do the trick:
t = 10
accumulate(x,lambda x,y:x if y>=t else x+y)
But now I want to make a function which returns a function like the above, where I can pass it the value t as the parameter.
This is what I tried:
def sum_small_nums(t):
def F(x):
new_x = accumulate(x,lambda x,y: x if y>=t else x+y)
return F
Unfortunately this doesn't seem to work. I can create a function from the above, but when I try to call it, I don't get the output I am expecting (e.g. I get 'None' instead of a list):
sum_under_10 = sum_small_nums(10)
print(sum_under_10)
x = [1, 1, 1, 1, 25, 1, 1]
x2 = sum_under_10(x)
print(x2)
returns
<function sum_small_nums.<locals>.F at 0x7feab135a1f0>
None
You're close! Need to return the list from the inner function:
def sum_small_nums(t):
def F(x):
new_x = accumulate(x, lambda x, y: x if y >= t else x + y)
return list(new_x)
return F
When you don't return anything from a function, None is implicitly returned.

Execute a code block in a map in Python

I want to replicate the following JavaScript code in Python:
let a = [0, 4, 5]
b = a.map(x => {
if(x < 3) return 0
else return 1
})
Any idea how I can do this?
I'm not sure how execute a code block in a map function.
You can either make a function, or use a lambda function like this:
>>> a = [0, 4, 5]
>>> b = map(lambda x: 0 if x < 3 else 1, a)
>>> b
[0, 1, 1]
The only kind of anonymous functions in Python are lambdas, and they're limited to being only an expression, if you want a proper function you have to give it a name:
def map_f(x):
if x < 3:
return 0
else:
return 1
b = map(map_f, a)
Personally, I prefer list comprehension to the map function.
>>> a = [0, 4, 5]
>>> [int(x >= 3) for x in a]
[0, 1, 1]
They allow you to use whatever expression you want without having to create a function.

python map function (+ lambda) involving conditionals (if)

I'm curious if it's possible to do something with the map()function that I can do via list comprehension.
For ex, take this list comp:
example_list = [x*2 for x in range(5) if x*2/6. != 1]
obviously, this gives me [0, 2, 4, 8].
How do I make the equivalent using the map() function? Doing this gives me a syntax error.
example_map = map(lambda x:x*2 if x*2/6. != 1, range(5))
Just trying to get a better understanding of how to use this function.
You'll have to wrap the map around a filter around the list:
example_map = map(lambda x: x*2, filter(lambda x: x*2/6. != 1, range(5)))
Alternatively, you could filter your map rather than maping your filter.
example_map = filter(lambda x: x/6. != 1, map(lambda x: x*2, range(5)))
Just remember that you're now filtering the RESULT rather than the original (i.e. lambda x: x/6. != 1 instead of lambda x: x*2/6. != 1 since x is already doubled from the map)
Heck if you really want, you could kind of throw it all together with a conditional expression
example_map = map(lambda x: x*2 if x*2/6. != 1 else None, range(5))
But it'll leave you with [0, 2, 4, None, 8]. filter(None, example_map) will drop the Nones and leave you [0, 2, 4, 8] as expected.
Along side the other answers that suggests some solutions the reason of your Syntax Error is that map function :
Apply function to every item of iterable and return a list of the results.
So the result is in a same length as your iterable.and if you use if statement you need to specify an else too.
>>> map(lambda x:x*2 if x*2/6. != 1 else None, range(5))
[0, 2, 4, None, 8]
And as an alternative way you can use itertools.ifilter to filter your iterable :
>>> from itertools import ifilter
>>> map(lambda x:x*2,ifilter(lambda x: x*2/6. != 1,range(5)))
[0, 2, 4, 8]
Note that as you don't need the result of filtered list and you just want to pass it to map it's more efficient that use ifilter because it returns a generator and you can save much memory for long lists ;) (its all in python 2 and in python 3 filter returns generator)
you can do it at two stages, first stage by applying filter on the list and the second stage by applying mapping function on the output list
list(map(lambda x:x*2, filter(lambda x: x*2/6 != 1 , [x for x in range(5)])))
[0, 2, 4, 8]

Categories

Resources