Skip to main content

Seaborn 관계형

변수 간 관계를 시각화하면 상관관계, 군집 패턴, 이상 데이터 포인트를 직관적으로 파악할 수 있습니다. 산점도로 두 변수의 관계를, 히트맵으로 전체 상관 행렬을 한눈에 확인할 수 있습니다.

학습 목표

  • scatterplot으로 두 변수의 관계를 시각화할 수 있다
  • lineplot으로 시계열 추이를 표현할 수 있다
  • heatmap으로 상관 행렬을 시각화할 수 있다
  • clustermap으로 계층적 군집화 결과를 표현할 수 있다

왜 중요한가

피처 간 상관관계는 다중공선성 문제를 식별하고, 피처 선택의 근거를 제공합니다. 타겟 변수와 상관이 높은 피처를 발견하면 모델 성능 향상에 직접 기여합니다.

scatterplot

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

np.random.seed(42)
df = pd.DataFrame({
    'experience': np.random.uniform(1, 20, 100),
    'salary': np.random.normal(4000, 1000, 100),
    'department': np.random.choice(['개발', '영업', '마케팅'], 100),
    'performance': np.random.uniform(60, 100, 100)
})
df['salary'] = df['salary'] + df['experience'] * 150

fig, ax = plt.subplots(figsize=(8, 6))
sns.scatterplot(data=df, x='experience', y='salary', hue='department',
                size='performance', sizes=(20, 200), ax=ax, palette='Set2', alpha=0.7)
ax.set_title('경력 vs 연봉')
ax.set_xlabel('경력 (년)')
ax.set_ylabel('연봉 (만원)')
plt.tight_layout()
plt.show()

regplot — 회귀선 포함 산점도

fig, ax = plt.subplots(figsize=(8, 6))
sns.regplot(data=df, x='experience', y='salary', ax=ax,
            scatter_kws={'alpha': 0.5}, line_kws={'color': '#e6a23c'})
ax.set_title('경력 vs 연봉 (회귀선)')
plt.tight_layout()
plt.show()

heatmap — 상관 행렬

# 상관 행렬 계산
corr = df[['experience', 'salary', 'performance']].corr()

fig, ax = plt.subplots(figsize=(8, 6))
sns.heatmap(corr, annot=True, fmt='.2f', cmap='RdBu_r',
            center=0, vmin=-1, vmax=1, ax=ax,
            square=True, linewidths=0.5)
ax.set_title('상관 행렬')
plt.tight_layout()
plt.show()
상관 행렬 히트맵에서 cmap='RdBu_r'center=0을 사용하면 양의 상관(빨강)과 음의 상관(파랑)을 직관적으로 구분할 수 있습니다.

clustermap — 계층적 군집화

# 피처 간 유사도를 기반으로 재정렬
sns.clustermap(corr, annot=True, fmt='.2f', cmap='RdBu_r',
               center=0, figsize=(8, 8), linewidths=0.5)
plt.show()

lineplot — 시계열 추이

dates = pd.date_range('2024-01-01', periods=90, freq='D')
ts_df = pd.DataFrame({
    'date': np.tile(dates, 3),
    'value': np.concatenate([
        np.cumsum(np.random.randn(90)) + 100,
        np.cumsum(np.random.randn(90)) + 80,
        np.cumsum(np.random.randn(90)) + 90,
    ]),
    'group': np.repeat(['A', 'B', 'C'], 90)
})

fig, ax = plt.subplots(figsize=(10, 5))
sns.lineplot(data=ts_df, x='date', y='value', hue='group',
             ax=ax, palette='Set2')
ax.set_title('그룹별 시계열 추이')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

AI/ML에서의 활용

  • 다중공선성 탐지: 히트맵에서 높은 상관계수(0.9 이상)를 가진 피처 쌍을 식별합니다
  • 피처-타겟 관계: 각 피처와 타겟 변수의 상관관계 강도를 비교합니다
  • 예측 검증: 실제값 vs 예측값 산점도로 모델 성능을 시각적으로 평가합니다
  • 학습 곡선: lineplot으로 epoch별 loss 변화를 추적합니다
annot=True는 각 셀에 숫자를 표시하고, fmt='.2f'는 소수점 둘째 자리까지 표시합니다. 큰 행렬에서는 annot=False로 설정하면 가독성이 좋아집니다.

체크리스트

  • scatterplot으로 두 변수의 관계를 시각화할 수 있다
  • hue, size 파라미터로 다차원 정보를 표현할 수 있다
  • 상관 행렬을 계산하고 heatmap으로 시각화할 수 있다
  • lineplot으로 시계열 추이를 그룹별로 시각화할 수 있다

다음 문서