글 작성자: 만렙개발자

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 개발환경에서 매우 잘 활용할 수 있을 것으로 보입니다 :)