python functools.reduce 函数学习
参考链接: https://mathieularose.com/function-composition-in-python/
functools.reduce 第一次在 keras-yolov3代码里遇到,可以实现每一层网络计算过后参数传递给下一层。
def compose(*funcs):
"""Compose arbitrarily many functions, evaluated left to right.
Reference: https://mathieularose.com/function-composition-in-python/
"""
# return lambda x: reduce(lambda v, f: f(v), funcs, x)
# leaky(BN(conv(x)))
if funcs:
return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs)
else:
raise ValueError('Composition of empty sequence not supported.')
- 简单例子
## 实现 F(x) = (x+1)*2
##
def compose2(f, g):
return lambda x: f(g(x)) # lambda是匿名函数, 代表输入参数x, 输出f(g(x))
def double(x):
return x * 2
def inc(x):
return x + 1
inc_and_double = compose2(double, inc)(10)
print(inc_and_double)
结果:
22
- functools.reduce
import functools
def dec(x):
return x - 1;
def compose(*functions):
return functools.reduce(lambda f,g: lambda x: f(g(x)),functions)
# 1、functions代表输出参数有N函数, f第一次是取第N-1个函数,g是取第N个函数,
# 2、step1 计算完结果作为第N-2个函数的输入,依次类推。当 f(g(x)) 改为g(f(x))时f,g从第0个函数开始取,相当于倒过来。
inc_double_and_dec = compose(dec,double,inc)(10)
print(inc_double_and_dec)
结果
21