[Python] inspect 모듈의 getsource() 함수

2022. 6. 12. 00:35·Programming/Python
반응형

우리가 쓰는 패키지는 대부분 소스코드와 함께 제공이 되고 있다. 또한 공식적인 패키지가 아니라면, 함수에 자세한 설명이 적혀있지 않은 경우도 많다. 이러한 경우, 함수의 소스코드를 직접 확인하고 참조해야 하는 경우가 있는데, 이럴 때 inspect의 get source를 사요하면 좋다. 

 

1. inspect 설치

inspect 설치는 간단하다. pip install로 설치한다. 

pip install inspect

 

2. inspect의 기능

inspect는 모듈, 클래스, 함수에 대한 소스코드를 출력해준다. 

다양한 기능이 있다고 하지만, getsource()함수 하나도 참 유용하다. 

getsource() 안에 클래스 이름을 써주면, 해당 클래스의 소스코드가 출력된다.

from inspect import getsource
from sklearn.metrics improt confusion_matrix

print(getsource(confusion_matrix))

위의 예시와 같이 confusion_matrix의 소스코드를 보고싶다면 다음과 같이 쓰면 되고, 그럼 아래와 같이 출력된다.

def confusion_matrix(
    y_true, y_pred, *, labels=None, sample_weight=None, normalize=None
):
    """Compute confusion matrix to evaluate the accuracy of a classification.
    By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}`
    is equal to the number of observations known to be in group :math:`i` and
    predicted to be in group :math:`j`.
    Thus in binary classification, the count of true negatives is
    :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is
    :math:`C_{1,1}` and false positives is :math:`C_{0,1}`.
    Read more in the :ref:`User Guide <confusion_matrix>`.
    Parameters
    ----------
    y_true : array-like of shape (n_samples,)
        Ground truth (correct) target values.
    y_pred : array-like of shape (n_samples,)
        Estimated targets as returned by a classifier.
    labels : array-like of shape (n_classes), default=None
        List of labels to index the matrix. This may be used to reorder
        or select a subset of labels.
        If ``None`` is given, those that appear at least once
        in ``y_true`` or ``y_pred`` are used in sorted order.
    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.
        .. versionadded:: 0.18
    normalize : {'true', 'pred', 'all'}, default=None
        Normalizes confusion matrix over the true (rows), predicted (columns)
        conditions or all the population. If None, confusion matrix will not be
        normalized.
    Returns
    -------
    C : ndarray of shape (n_classes, n_classes)
        Confusion matrix whose i-th row and j-th
        column entry indicates the number of
        samples with true label being i-th class
        and predicted label being j-th class.
    See Also
    --------
    ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix
        given an estimator, the data, and the label.
    ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix
        given the true and predicted labels.
    ConfusionMatrixDisplay : Confusion Matrix visualization.
    References
    ----------
    .. [1] `Wikipedia entry for the Confusion matrix
           <https://en.wikipedia.org/wiki/Confusion_matrix>`_
           (Wikipedia and other references may use a different
           convention for axes).
    Examples
    --------
    >>> from sklearn.metrics import confusion_matrix
    >>> y_true = [2, 0, 2, 2, 0, 1]
    >>> y_pred = [0, 0, 2, 2, 0, 2]
    >>> confusion_matrix(y_true, y_pred)
    array([[2, 0, 0],
           [0, 0, 1],
           [1, 0, 2]])
    >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
    >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
    >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"])
    array([[2, 0, 0],
           [0, 0, 1],
           [1, 0, 2]])
    In the binary case, we can extract true positives, etc as follows:
    >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()
    >>> (tn, fp, fn, tp)
    (0, 2, 1, 1)
    """
    y_type, y_true, y_pred = _check_targets(y_true, y_pred)
    if y_type not in ("binary", "multiclass"):
        raise ValueError("%s is not supported" % y_type)

    if labels is None:
        labels = unique_labels(y_true, y_pred)
       
  ...(생략)

이런식으로 inspect의 getsource()함수를 이용해 print하면 도큐멘테이션을 찾아볼 필요 없이, 소스코드를 바로 확인할 수 있다. 

검색이 어려운 환경 안에서, 해당 함수를 확인하고 싶을 때 유용해 보인다.

반응형

'Programming > Python' 카테고리의 다른 글

[python] 대용량 csv 불러오는 패키지 dask 간단 리뷰  (2) 2022.09.30
[Python/Oracle] cx_Oracle timeout 설정하기  (0) 2022.04.10
[Python] HTTP web server log dataframe으로 불러오기 (with pandas)  (0) 2022.02.13
[Python] 주피터 노트북 테마 변경하기  (3) 2021.05.17
[Python]Pytorch - RuntimeError:Error(s) in loading state_dict ... : Missing key(s) in state_dict: ... Unexpected key(s) in state_dict:... GPU 병렬 사용 문제  (0) 2021.04.30
'Programming/Python' 카테고리의 다른 글
  • [python] 대용량 csv 불러오는 패키지 dask 간단 리뷰
  • [Python/Oracle] cx_Oracle timeout 설정하기
  • [Python] HTTP web server log dataframe으로 불러오기 (with pandas)
  • [Python] 주피터 노트북 테마 변경하기
자동화먹
자동화먹
많은 사람들에게 도움이 되는 생산적인 기록하기
    반응형
  • 자동화먹
    자동화먹의 생산적인 기록
    자동화먹
  • 전체
    오늘
    어제
    • 분류 전체보기 (144)
      • 생산성 & 자동화 툴 (30)
        • Notion (24)
        • Obsidian (0)
        • Make.com (1)
        • tips (5)
      • Programming (37)
        • Python (18)
        • Oracle (6)
        • Git (13)
      • AI Study (65)
        • DL_Basic (14)
        • ML_Basic (14)
        • NLP (21)
        • Marketing&Recommend (4)
        • chatGPT (0)
        • etc (12)
      • 주인장의 생각서랍 (10)
        • 생각정리 (4)
        • 독서기록 (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자연어처리
    cnn
    Python
    파이토치
    데이터베이스
    Transformer
    pytorch
    노션첫걸음
    gcp
    python기초
    노션
    머신러닝
    dl
    ML
    Google Cloud Platform
    seq2seq
    Jupyter notebook
    기초
    빅데이터분석
    LSTM
    파이토치로 시작하는 딥러닝 기초
    Github
    빅데이터
    데이터분석
    딥러닝
    nlp
    git
    notion
    GPT
    git commit
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
자동화먹
[Python] inspect 모듈의 getsource() 함수
상단으로

티스토리툴바