Search

[Archive] functools.wraps & functools.reduce

Created
2022/08/18
Last modified date
Tags
ai
URL
작성일: 2022.08.18 (Thu)

What is wraps func?

wraps()는 데코레이터로 사용됨.
from functools import wraps def logged(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging @logged def f(x): """does some math""" return x + x * x print(f.__name__) # prints 'f' print(f.__doc__) # prints 'does some math'
Python
복사
Usage of wraps()

What is reduce func?

Iterable한 데이터를 왼쪽에서 오른쪽으로 순차적으로 function의 인자로 넣어 누적된 하나의 결과를 반환하는 함수
Example 1
from functools import reduce data = [1, 2, 3, 4, 5] def func_sum(a, b): return a + b print(reduce(func_sum, data)) # 15
Python
복사
Usage of reduce()
위 예시에서 15 가 도출된 과정은 아래와 동일함
1.
sum(sum(sum(sum(1,2),3),4),5)
2.
((((1+2)+3)+4)+5)
3.
15
Example 2
from functools import reduce def compose(*funcs): if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty sequence not supported.') x = compose( DarknetConv2D_BN_Leaky(256, (1,1)), UpSampling2D(2))(x_1)
Python
복사
Usage of reduce function in YOLOv3
위 예시에서 x 의 도출 과정은 간단하게,
1.
x_1DarknetConv2D_BN_Leaky(256, (1,1)) 로 넣어서 output 도출
2.
도출된 outputUpSampling2D(2)input 으로 들어가 output 도출
3.
두 번째로 도출된 outputx 에 대입됨
Reference