본문 바로가기
목차
Python

[Python] functools.partial

by ds31x 2023. 8. 25.
728x90
반응형

signature

functools.partial(func, /, \*args, \*\*keywords)

function 처럼 동작하는 partial object를 반환하는 High-order Function임.

  • 반환되는 partaial object를 호출시 parameter로 받은 func이 호출되며
  • partial object를 호출할 때 넘겨진 positional arguments args와 keyword arguments keywords가 해당 func의 argument로 주어져 호출된다.
  • 만약 partial object가 호출될 때 더 많은 arguments가 주어질 경우, partial object를 생성할 때 주어졌던 argskeywords에 append되어 func에 넘겨진다 (keyword에 따라 override가 발생함).

용도

동일한 arguments와 keyword arguments로 동일 함수를 여러차례 호출해야하는 경우

functools.partial을 통해 가벼운 wrapper인 partial object를 만들어 사용하는게 편함.

 

  • 2개의 기능을 한번에 구현하고 argument를 통해 실행 기능이 결정되는 경우에,
  • partial다른 이름의 callable object를 얻어서 사용하면 가독성 측면에서도 용이함.
  • python 공식문서에서는 docstring까지 기재하는 예도 있음.

예제

다음의 code snippet은 동일한 arguments를 가지는 Dense layer를 여러 개 사용하기 위해 partial을 이용하고 있음.

from functools import partial

RegularizedDense = partial(
    tf.keras.layers.Dense, 
    activation="relu",
    kernel_initializer="he_normal", 
    kernel_regularizer=tf.keras.regularizers.l2(0.01)
)

model = tf.keras.Sequential(
    [ 
        tf.keras.layers.Flatten(input_shape=[28, 28]), 
        RegularizedDense(100),
        RegularizedDense(100),
        RegularizedDense(10, activation="softmax") 
    ]
)

 

참고로 위의 코드의 출처는 다음과 같음.

https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/

 

Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition

Through a series of recent breakthroughs, deep learning has boosted the entire field of machine learning. Now, even programmers who know close to nothing about this technology can use simple, … - Selection from Hands-On Machine Learning with Scikit-Learn

www.oreilly.com


같이 보면 좋은 자료들

2024.11.20 - [Python] - [Py] Higher-order Function (고차함수)

 

[Py] Higher-order Function (고차함수)

정의 : Higher-order function(고차 함수)란, 다음 조건 중 하나 이상을 충족하는 function를 가리킴:다른 함수를 argument로 받을 수 있는 function다른 함수를 반환할 수 있는 function즉, Higher-order function이란 fu

ds31x.tistory.com


 

728x90