Certificate/data analytics-Google

Outlier, 이상치 처리하기, global, contextual, collective outliers,

Olivia-BlackCherry 2023. 7. 10. 17:03

목차

    Ouliter 이상치

    보통의 값에서 멀리 떨어진 값을 이상값이라고 한다. 

    Observations that are an abnormal distance from other values or an overall pattern in a data population.

    데이터 전문가로서 이상치에 대한 탐구와 처리는 데이터분석에서 반드시 필요하다. 

     

    1) Global

    Values that are completely different from the overall data group and have no association with any other outliers.

    보통의 값에서 현저히 떨어진 값을 이야기한다. 다른 이상치에 비해 발견하기 쉽다. 

    예를 들어 키에 관한 데이터가 있을 때 7.9m는 말도 안되게 큰 값이다. 따라서 이것이 이상값이라는 것을 쉽게 발견할 수 있다. 

     

    2) Contextual

    Nornal data points under certain conditions but become anomalies under most other conditions.

    특정 조건 하에서는 정상적인 데이터이지만, 대부분의 다른 조건에서는 이상치로 판단되는 데이터이다. 

    예를 들어, 1-3반 학생 대부분이 수학 성적이 좋은데 한 학생은 특이하게 국어 성적이 뛰어난 경우이다. 이 학생은 맥락에서 벗어나는 이상치라고 볼 수 있다. 

     

    3) Collective

    A group of abnormal points that follow similar patterns and are isolated from the rest of the population.

    비슷한 패턴을 따르는 이상치들로 전체 집단과 분리되어 있는 데이터 그룹이다. 

    예를 들어, 한 도시의 주택 가격 데이터가 있을 때 대부분의 주택 가격은 비슷한 범위인데 한 동네의 주택들만 비정상적으로 높은 가격을 가진다면 이 그룹의 주택은 나머지와 패턴이 다르며 집단 이상치라고 볼 수 있다.

     

     

    box plot

    이상치값을 잘 볼 수 있는 방법으로 박스 플랏이 있다. 

     

    1) 그래프 그리기

    sns.boxplot(x=df['number_of_strikes'])

    box = sns.boxplot(x=df['number_of_strikes'])
    g = plt.gca()
    box.set_xticklabels(np.array([readable_numbers(x) for x in g.get_xticks()]))
    plt.xlabel('Number of strikes')
    plt.title('Yearly number of lightning strikes');
    def readable_numbers(x):
        """takes a large number and formats it into K,M to make it more readable"""
        if x >= 1e6:
            s = '{:1.1f}M'.format(x*1e-6)
        else:
            s = '{:1.0f}K'.format(x*1e-3)
        return s
    
    # Use the readable_numbers() function to create a new column 
    df['number_of_strikes_readable']=df['number_of_strikes'].apply(readable_numbers)

     

    gca()는 get current axes의 약자로 Matplotlib library함수로 현재 Axes 객체를 반환하는 역할을 한다.

    보통 Matplotlib에서 서브플롯을 조작하거나 그래프를 그릴 때, gca()를 사용하여 현재 활성화된 서브플롯 객체에 접근한다. 

    import matplotlib.pyplot as plt
    
    x = [1, 2, 3, 4, 5]
    y = [2, 4, 6, 8, 10]
    
    plt.plot(x, y)  # 현재 활성화된 서브플롯에 선 그래프 추가
    
    g = plt.gca()  # 현재 활성화된 서브플롯 객체 가져오기
    g.set_xlabel('X-axis')  # x축 레이블 설정
    g.set_ylabel('Y-axis')  # y축 레이블 설정
    g.set_title('My Plot')  # 그래프 제목 설정
    
    plt.show()  # 그래프 표시

     

    2) quantile 값구하기

    25(1Q)

    75(3Q)

    IQR(3Q-1Q)

    Min(1Q-1.5IQR)

    Max(3Q+1.5IQR)

    # Calculate 25th percentile of annual strikes
    percentile25 = df['number_of_strikes'].quantile(0.25)
    
    # Calculate 75th percentile of annual strikes
    percentile75 = df['number_of_strikes'].quantile(0.75)
    
    # Calculate interquartile range
    iqr = percentile75 - percentile25
    
    # Calculate upper and lower thresholds for outliers
    upper_limit = percentile75 + 1.5 * iqr
    lower_limit = percentile25 - 1.5 * iqr
    
    print('Lower limit is: '+ readable_numbers(lower_limit))

     

     

     

    outlier, 데이터교육, 데이터분석