python functools.reduce 函数学习

本文深入探讨了Python中functools模块的reduce函数,通过实例展示了如何使用reduce进行函数组合,实现网络层间参数的传递。文章还对比了两种不同的函数组合方式,并提供了清晰的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值