[파이썬] 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 개발환경에서 매우 잘 활용할 수 있을 것으로 보입니다 :)
'✏️ 수동로깅 > 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.15python에서 opencv를 설치하고 import 했는데, 다음과 같은 에러가 발생할 수 있다. ----> import cv2 ImportError: libSM.so.6: cannot open shared object file: No such file or directory 이 에러는 두 가지 방법으로 해결할 수 있다. GUI와 관련된 문제 에러다. 첫번째 해결방법은, 관련된 패키지를 업데이트 혹은 설치하는 것이다. apt-get update apt-get install -y libsm6 libxext6 libxrender-dev pip install opencv-python (위의 방법으로 해결이 되지 않을 경우) 두번째 해결방법은, pip install opencv-python-headless aw… -
[Google Colab] OSError: [Errno 107] Transport endpoint is not connected
[Google Colab] OSError: [Errno 107] Transport endpoint is not connected
2020.02.27import numpy as np from google.colab import drive drive.mount('/content/drive',force_remount=True) %cd "/content/drive/My Drive/" 이런식으로 force_remount를 했으나, 아래와 같은 장문의 에러가 발생했다. ERROR:root:Internal Python error in the inspect module. Below is the traceback from this internal error. Mounted at /content/drive Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/IPython/co… -
[파이썬] python subprocess 가 에러 메세지도 없이 죽었다/사라졌다 dmesg
[파이썬] python subprocess 가 에러 메세지도 없이 죽었다/사라졌다 dmesg
2020.02.20서브 프로세스 중 하나가 에러 메세지도 없이 죽었다. 원인을 파악할 수도 없고, 계속 실행하다 보면 어느 한 녀석이 죽어있다. 해답은 파블로프의 개로부터 찾을 수 있었다. https://blog.naver.com/wpdls6012/221817075009 서브 프로세스가 아무 이유 없이 죽어있다 도커 컨테이너 내의 파이썬 프로세스에서 서브 프로세스로 워커를 띄워서 작업을 처리하던 도중서브 프로…. blog.naver.com 결과적으로 OS가 죽인 것이었다. 죽은 이유를 찾기 위해서는 dmesg를 아래와 같이 사용하면 된다. dmesg -T| grep -E -i -B100 'Killed process' 그러면 무언가 좌르륵 뜨고, 마지막에 이런 유언이 남아있다. 'Out of memory: Kill pr… -
Jupyter Lab에서 VS Code로 개발환경 이전
Jupyter Lab에서 VS Code로 개발환경 이전
2020.02.14Jupyter Lab을 이용해서 ipynb를 이용한 개발을 많이했었습니다. Jupyter notebook에서 Lab으로 옮겨갔을 때, Terminal을 함께 사용할 수 있어서 매우 편리했었죠. VS Code가 나오더라도, 조금 써보고 계속 Jupyter Lab을 쓰고 있었는데, Live share extension을 보고는 감탄하면서, 와!! 무조건 해야겠다! 하면서 VS Code로 옮겨갔지만, 그 외에는 제게는 잘 안맞더라구요. (사실 원래 진성 Visual Studio + C++ 개발자 였습니다….) 그러던 반복의 삶 속에서…. VS Code의 extension이 너무 발달해버린 요즘, 이제는 이전을 정말 무조건 해야겠다! 라는 마음으로 셋팅 중에 있습니다. 평소 쇼핑을 좋아해서 그런지, 사용하지…
댓글을 사용할 수 없습니다.