[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,64 +1,219 @@
|
||||
---
|
||||
id: wiki-2026-0508-exploratory-data-analysis
|
||||
title: Exploratory Data Analysis
|
||||
title: Exploratory Data Analysis (EDA)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [EDA-001]
|
||||
aliases: [EDA, data exploration, Tukey, pandas-profiling, sweetviz, descriptive analytics]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [data-science, Statistics, eda, visualization, machine-learning]
|
||||
confidence_score: 0.98
|
||||
verification_status: applied
|
||||
tags: [data-science, eda, statistics, pandas, visualization, tukey, profiling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: Python
|
||||
framework: pandas / matplotlib / seaborn / ydata-profiling
|
||||
---
|
||||
|
||||
# Exploratory Data [[Analysis|Analysis]] (EDA, 탐색적 데이터 분석)
|
||||
# Exploratory Data Analysis (EDA)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "모델을 만들기 전, 데이터가 들려주는 날것의 이야기에 귀를 기울여라" — 수집된 데이터를 다양한 각도에서 관찰하고 시각화하여 데이터의 분포, 이상치, 변수 간 상관관계를 파악하고 가설을 세우는 필수적인 기초 분석 단계.
|
||||
## 매 한 줄
|
||||
> **"매 model 전 의 의 의 data 의 understand"**. Tukey 1977. 매 distribution + missing + outlier + correlation + leakage. 매 modern: 매 ydata-profiling (auto), 매 LLM-aided EDA, 매 Plotly interactive.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 고정된 정답을 찾기보다 데이터의 전체적인 윤곽을 파악하고, 전처리 방향(Feature Engineering)을 결정하기 위한 통계적 직관 형성 패턴.
|
||||
- **주요 수행 작업:**
|
||||
- **Summary Statistics:** 평균, 중앙값, 표준편차 확인.
|
||||
- **Distribution Analysis:** 히스토그램이나 박스 플롯을 통해 데이터 치우침 및 이상치 탐색.
|
||||
- **Correlation Analysis:** 산점도(Scatter plot)나 Heatmap을 통해 변수 간 관계 파악.
|
||||
- **Missing Value Check:** 결측치 비중과 패턴 분석.
|
||||
- **의의:** 쓰레기를 넣으면 쓰레기가 나오는(GIGO) 현상을 방지하고, 데이터에 숨겨진 도메인 지식을 발견하는 과정.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 바로 모델 학습 코드를 짜던 성급함에서 벗어나, 데이터의 특성에 맞는 적절한 알고리즘을 선택하기 위한 근거 중심의 분석으로 정착.
|
||||
- **정책 변화:** Antigravity 프로젝트는 새로운 위키 소스 데이터가 확보될 때마다 자동화된 EDA 리포트를 생성하여, 지식의 밀도와 편향성을 사전에 점검함.
|
||||
### 매 step
|
||||
1. **Schema**: 매 dtype, shape.
|
||||
2. **Univariate**: 매 dist, missing.
|
||||
3. **Bivariate**: 매 correlation, scatter.
|
||||
4. **Outlier**: 매 IQR, z-score.
|
||||
5. **Target**: 매 class balance, regression target dist.
|
||||
6. **Leakage**: 매 feature → target.
|
||||
7. **Time**: 매 trend, seasonality.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Machine-Learning, [[Feature-Engineering|Feature-Engineering]], [[Dimensionality-Reduction|Dimensionality-Reduction]], [[Principal-Component-Analysis|Principal-Component-Analysis]]-PCA
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Exploratory-Data-Analysis.md
|
||||
### 매 modern tool
|
||||
- **ydata-profiling** (formerly pandas-profiling).
|
||||
- **sweetviz**.
|
||||
- **DataPrep**.
|
||||
- **Polars** (10x faster).
|
||||
- **DuckDB** in pandas.
|
||||
- **Plotly Express**.
|
||||
- **LLM-EDA** (Claude / ChatGPT).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Quick scan
|
||||
```python
|
||||
import pandas as pd
|
||||
df = pd.read_csv('data.csv')
|
||||
print(df.shape, df.dtypes, df.describe(include='all'), df.isna().sum())
|
||||
```
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Auto-profile (ydata-profiling)
|
||||
```python
|
||||
from ydata_profiling import ProfileReport
|
||||
report = ProfileReport(df, title='EDA', explorative=True)
|
||||
report.to_file('eda.html')
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Missing pattern
|
||||
```python
|
||||
import missingno as msno
|
||||
msno.matrix(df)
|
||||
msno.heatmap(df) # 매 missing correlation
|
||||
```
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### Univariate (numeric)
|
||||
```python
|
||||
import seaborn as sns
|
||||
sns.histplot(df['amount'], kde=True)
|
||||
sns.boxplot(x=df['amount'])
|
||||
print(df['amount'].skew(), df['amount'].kurt())
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### Univariate (categorical)
|
||||
```python
|
||||
df['category'].value_counts(normalize=True).plot(kind='bar')
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Outlier (IQR)
|
||||
```python
|
||||
def iqr_outliers(s, k=1.5):
|
||||
q1, q3 = s.quantile([0.25, 0.75])
|
||||
iqr = q3 - q1
|
||||
return s[(s < q1 - k * iqr) | (s > q3 + k * iqr)]
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Outlier (z-score)
|
||||
```python
|
||||
from scipy.stats import zscore
|
||||
df[(zscore(df.select_dtypes('number')) > 3).any(axis=1)]
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### Correlation
|
||||
```python
|
||||
import seaborn as sns
|
||||
corr = df.corr(numeric_only=True)
|
||||
sns.heatmap(corr, annot=True, cmap='coolwarm', fmt='.2f')
|
||||
```
|
||||
|
||||
### Mutual information (non-linear)
|
||||
```python
|
||||
from sklearn.feature_selection import mutual_info_regression
|
||||
mi = mutual_info_regression(X, y)
|
||||
pd.Series(mi, index=X.columns).sort_values().plot(kind='barh')
|
||||
```
|
||||
|
||||
### Pairplot
|
||||
```python
|
||||
sns.pairplot(df, hue='target', diag_kind='kde')
|
||||
```
|
||||
|
||||
### Time series quick
|
||||
```python
|
||||
df.set_index('date').resample('W').mean().plot()
|
||||
from statsmodels.tsa.seasonal import seasonal_decompose
|
||||
seasonal_decompose(df['target'], period=7).plot()
|
||||
```
|
||||
|
||||
### Class imbalance
|
||||
```python
|
||||
print(df['target'].value_counts(normalize=True))
|
||||
sns.countplot(x='target', data=df)
|
||||
```
|
||||
|
||||
### Leakage detection
|
||||
```python
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
for col in df.columns:
|
||||
if col == 'target': continue
|
||||
score = LogisticRegression().fit(df[[col]].fillna(0), df['target']).score(df[[col]].fillna(0), df['target'])
|
||||
if score > 0.95: print(f'⚠️ leakage suspected: {col} → target ({score:.2f})')
|
||||
```
|
||||
|
||||
### Plotly interactive
|
||||
```python
|
||||
import plotly.express as px
|
||||
px.scatter_matrix(df, dimensions=['a', 'b', 'c'], color='target').show()
|
||||
```
|
||||
|
||||
### LLM-aided EDA
|
||||
```python
|
||||
def llm_eda(df, llm):
|
||||
schema = df.head().to_string() + '\n' + df.describe().to_string()
|
||||
prompt = f"""You are a data scientist. Given this data summary:
|
||||
{schema}
|
||||
|
||||
Suggest:
|
||||
1. 5 hypotheses to test
|
||||
2. Likely data quality issues
|
||||
3. Feature engineering ideas"""
|
||||
return llm.generate(prompt)
|
||||
```
|
||||
|
||||
### High-cardinality categorical
|
||||
```python
|
||||
def high_cardinality(df, threshold=50):
|
||||
return [c for c in df.select_dtypes('object').columns if df[c].nunique() > threshold]
|
||||
```
|
||||
|
||||
### Datetime feature peek
|
||||
```python
|
||||
def datetime_summary(s):
|
||||
return {
|
||||
'min': s.min(), 'max': s.max(),
|
||||
'gaps': s.sort_values().diff().describe(),
|
||||
'weekday_dist': s.dt.dayofweek.value_counts().to_dict(),
|
||||
}
|
||||
```
|
||||
|
||||
### Polars (faster)
|
||||
```python
|
||||
import polars as pl
|
||||
df = pl.read_csv('big.csv')
|
||||
print(df.describe())
|
||||
df.group_by('cat').agg(pl.col('amount').mean()).head()
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Quick check | describe + missing + value_counts |
|
||||
| Auto-report | ydata-profiling |
|
||||
| Big data | Polars / DuckDB |
|
||||
| Interactive | Plotly Express |
|
||||
| ML prep | + leakage + correlation |
|
||||
| LLM aided | Schema → suggest hypotheses |
|
||||
|
||||
**기본값**: 매 schema + missing + describe + correlation + ydata-profiling 빠른 진단 + 매 leakage scan.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Data-Science]] · [[Statistics]]
|
||||
- 변형: [[Auto-EDA]] · [[Visual-EDA]]
|
||||
- 응용: [[Feature Engineering]] · [[Data-Cleaning]]
|
||||
- Adjacent: [[Pandas]] · [[Polars]] · [[Tukey]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 모든 ML / DS 프로젝트 시작.
|
||||
**언제 X**: 매 already-known schema.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Skip EDA**: 매 모델 의 garbage in.
|
||||
- **Auto-only**: 매 domain context 의 miss.
|
||||
- **No leakage check**: 매 fake high score.
|
||||
- **Plot everything**: 매 noise.
|
||||
- **Ignore class imbalance**: 매 wrong metric.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Tukey 1977, Wickham R for DS).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-04-26 | EDA auto |
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — EDA + 매 ydata / IQR / MI / leakage / LLM code |
|
||||
|
||||
Reference in New Issue
Block a user