[파이썬] inspect 모듈의 getsource() 함수- 도큐멘테이션을 안보고 함수 구현부를 빠르게 확인하기
글 작성자: 만렙개발자
Kaggle의 커널을 리뷰하다가 흥미로운 패키지를 발견했습니다.
inspect 패키지인데, 설치는 간단히 pip로 가능합니다.
pip install inspect
inspect 모듈의 기능은 모듈, 클래스, 함수에대한 정보를 얻는 것입니다.
좀 더 깊이 보면 기능이 다양하지만, 가장 간단한 기능 하나만으로도 매우 유용합니다.
여기서 소개하고자 하는 함수는 getsource() 함수이다. 함수의 구현부 소스코드를 가져옵니다.
import inspect from keras.utils import to_categorical print(inspect.getsource(to_categorical))
keras.utils에 있는 to_categorical 코드를 살펴봅시다.
출력 결과는 다음과 같습니다.
def to_categorical(y, num_classes=None, dtype='float32'): """Converts a class vector (integers) to binary class matrix. E.g. for use with categorical_crossentropy. # Arguments y: class vector to be converted into a matrix (integers from 0 to num_classes). num_classes: total number of classes. dtype: The data type expected by the input, as a string (`float32`, `float64`, `int32`...) # Returns A binary matrix representation of the input. The classes axis is placed last. # Example ```python # Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}: > labels array([0, 2, 1, 2, 0]) # `to_categorical` converts this into a matrix with as many # columns as there are classes. The number of rows # stays the same. > to_categorical(labels) array([[ 1., 0., 0.], [ 0., 0., 1.], [ 0., 1., 0.], [ 0., 0., 1.], [ 1., 0., 0.]], dtype=float32) ``` """ y = np.array(y, dtype='int') input_shape = y.shape if input_shape and input_shape[-1] == 1 and len(input_shape) > 1: input_shape = tuple(input_shape[:-1]) y = y.ravel() if not num_classes: num_classes = np.max(y) + 1 n = y.shape[0] categorical = np.zeros((n, num_classes), dtype=dtype) categorical[np.arange(n), y] = 1 output_shape = input_shape + (num_classes,) categorical = np.reshape(categorical, output_shape) return categorical
즉, 도큐멘테이션을 찾아볼 필요도 없고, 원래 소스코드를 찾기 위해 함수를 검색할 필요도 없습니다.
inspect의 getsource() 함수를 이용해 print하기만 하면 소스코드를 바로 확인할 수 있습니다.
jupyter 개발환경에서 매우 잘 활용할 수 있을 것으로 보입니다 :)
이 글은
(새창열림)
본 저작자 표시 규칙 하에 배포할 수 있습니다. 자세한 내용은 Creative Commons 라이선스를 확인하세요.
Creative Commons
본 저작자 표시
'✏️ 수동로깅 > dev_log' 카테고리의 다른 글
[opencv] ImportError: libSM.so.6: cannot open shared object file: No such file or directory (0) | 2020.03.15 |
---|---|
[Google Colab] OSError: [Errno 107] Transport endpoint is not connected (0) | 2020.02.27 |
[파이썬] python subprocess 가 에러 메세지도 없이 죽었다/사라졌다 dmesg (0) | 2020.02.20 |
Jupyter Lab에서 VS Code로 개발환경 이전 (0) | 2020.02.14 |
[Golang] Factory Method Design Pattern - 공장처럼 찍어내는 팩토리 메소드 디자인 패턴 (0) | 2020.02.12 |
댓글
이 글 공유하기
다른 글
-
[opencv] ImportError: libSM.so.6: cannot open shared object file: No such file or directory
[opencv] ImportError: libSM.so.6: cannot open shared object file: No such file or directory
2020.03.15 -
[Google Colab] OSError: [Errno 107] Transport endpoint is not connected
[Google Colab] OSError: [Errno 107] Transport endpoint is not connected
2020.02.27 -
[파이썬] python subprocess 가 에러 메세지도 없이 죽었다/사라졌다 dmesg
[파이썬] python subprocess 가 에러 메세지도 없이 죽었다/사라졌다 dmesg
2020.02.20 -
Jupyter Lab에서 VS Code로 개발환경 이전
Jupyter Lab에서 VS Code로 개발환경 이전
2020.02.14
댓글을 사용할 수 없습니다.