Common functions of python and Keras.backend

Keywords: Python Lambda

python common functions (v3.0)

lambda anonymous function

# lambda <params>:<result>
func = lambda x, y: x + y
print(func(1, 2))
# Output 3

map function

Pass one or more elements in sequnce as parameters to func for execution, and return the result of function execution as an iterator.

# map(func, sequnce[, sequnce,....]) -> iterator
>> list(map(lambda x: x+2, [1,2,3]))
[3, 4, 5]
>> list(map(pow, [1,2,3], [2,3,4]))
[1, 8, 81]

filter function

Filter, if function is None, an iterator containing a non empty element is returned.

# filter(func or None, sequence) -> iterator
>> list(filter((lambda x: x>0),range(-5,5)))
[1,2,3,4]
>> list(filter(None,range(-5,5)))
[-5, -4, -3, -2, -1, 1, 2, 3, 4]

map function

Perform func on the elements in sequnce in turn and return a map object

# map(func, sequence)
>> map(lambda x: x*x*x, range(1, 11)
<map object at 0x7fafdf0d6978>
>> list(map(lambda x: x*x*x, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

When the func parameter is multiple, the number of sequence s corresponds to it

reduce function

Call corresponding functions one by one in iterative sequence to return a result

# reduce(func, sequence, starting_value)
# starting_value is the initial call value, which can be empty or omitted
>> reduce(lambda x, y: x + y, range(1, 11))
55

After python 3, if you want to use reduce, you can use functools, because its built-in functions have been removed, as follows:

import functools
functools.reduce(lambda x, y: x + y, range(1, 11))

zip function

Receive the sequence object as a parameter, package the corresponding elements in the object into tuples, and then return the list composed of these tuples. If the length of the incoming parameters is not the same, the length of the returned list is the same as that of the object with the shortest length in the parameters. Use * operator and zip function to achieve the opposite function of zip, that is, split the combined sequence into multiple tuples

# zip([sequence, ...])
>> x = [1, 2, 3]; y = ['a', 'b', 'c']
>> list(zip(x, y))
[(1,'a'),(2,'b'),(3,'c')]
>> list(zip(*zip(x, y)))
[(1,2,3),('a','b','c')]
# Different length
>> x = [1, 2, 3]; y = ['a', 'b', 'c', 'd']
>> list(zip(x, y))
[(1,'a'),(2,'b'),(3,'c')]
>> list(zip(*zip(x, y)))
[(1,2,3),('a','b','c')]

keras sample break up

# Data? X is the numpy.array object
indices = numpy.random.permutation(data_x.shape[0]) # shape[0] indicates the length of the 0-th axis, usually the number of training data
rand_data_x = data_x[indices]
rand_data_y = data_y[indices] # Data? Is the label

Posted by TheoGB on Fri, 06 Dec 2019 11:29:36 -0800