Delete Analysis_code/find_reason
Browse files
Analysis_code/find_reason/trend_analysis.ipynb
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:a2ab33c31a63cf8d02985b53cd7de8ac36ede7e3988ee257ffc0f21c4b4caf31
|
| 3 |
-
size 921757
|
|
|
|
|
|
|
|
|
|
|
|
Analysis_code/find_reason/utils.py
DELETED
|
@@ -1,340 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Trend 분석 유틸리티 함수 모듈
|
| 3 |
-
|
| 4 |
-
지역별 데이터의 월별 trend를 분석하고 시각화하는 함수들을 제공합니다.
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import numpy as np
|
| 9 |
-
import matplotlib.pyplot as plt
|
| 10 |
-
import matplotlib.dates as mdates
|
| 11 |
-
import warnings
|
| 12 |
-
from typing import List, Dict, Any, Tuple, Optional
|
| 13 |
-
|
| 14 |
-
warnings.filterwarnings('ignore')
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# ==========================================
|
| 18 |
-
# 1. 설정 및 유틸리티 함수
|
| 19 |
-
# ==========================================
|
| 20 |
-
|
| 21 |
-
def setup_korean_font():
|
| 22 |
-
"""한글 폰트 설정."""
|
| 23 |
-
plt.rcParams['font.family'] = 'NanumGothic'
|
| 24 |
-
plt.rcParams['axes.unicode_minus'] = False
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def load_region_data(
|
| 28 |
-
region: str,
|
| 29 |
-
features: List[str] = None,
|
| 30 |
-
years: List[int] = None
|
| 31 |
-
) -> pd.DataFrame:
|
| 32 |
-
"""지역별 데이터를 로드하고 필터링합니다.
|
| 33 |
-
|
| 34 |
-
Args:
|
| 35 |
-
region: 지역명 ('seoul', 'busan', 'daegu', 'incheon', 'gwangju', 'daejeon')
|
| 36 |
-
features: 선택할 컬럼 리스트 (기본값: None - 전체 컬럼)
|
| 37 |
-
years: 필터링할 연도 리스트 (기본값: None - 전체 연도)
|
| 38 |
-
|
| 39 |
-
Returns:
|
| 40 |
-
pd.DataFrame: 필터링된 데이터프레임
|
| 41 |
-
|
| 42 |
-
Raises:
|
| 43 |
-
FileNotFoundError: 데이터 파일을 찾을 수 없는 경우
|
| 44 |
-
"""
|
| 45 |
-
# 기본값 설정
|
| 46 |
-
if features is None:
|
| 47 |
-
features = [
|
| 48 |
-
# 대기질 변수
|
| 49 |
-
'hm', 'PM10', 'PM25', 'O3', 'NO2',
|
| 50 |
-
# 기상 변수
|
| 51 |
-
'temp_C', 'wind_speed', 'cloudcover', 'solarRad', 'precip_mm',
|
| 52 |
-
'vap_pressure', 'dewpoint_C', 'loc_pressure', 'sea_pressure',
|
| 53 |
-
# 기타 변수
|
| 54 |
-
'visi', 'groundtemp', 'ground_temp - temp_C',
|
| 55 |
-
# 필수 변수
|
| 56 |
-
'multi_class', 'year', 'month', 'hour'
|
| 57 |
-
]
|
| 58 |
-
if years is None:
|
| 59 |
-
years = [2018, 2019, 2020, 2021]
|
| 60 |
-
|
| 61 |
-
# 데이터 파일 경로
|
| 62 |
-
file_path = f"../../data/data_for_modeling/df_{region}.feather"
|
| 63 |
-
|
| 64 |
-
try:
|
| 65 |
-
# 데이터 로드
|
| 66 |
-
df = pd.read_feather(file_path)
|
| 67 |
-
|
| 68 |
-
# Feature 선택
|
| 69 |
-
if features:
|
| 70 |
-
# 필수 컬럼 확인
|
| 71 |
-
required_cols = ['year', 'month']
|
| 72 |
-
missing_cols = [col for col in required_cols if col not in df.columns]
|
| 73 |
-
if missing_cols:
|
| 74 |
-
raise ValueError(f"필수 컬럼이 없습니다: {missing_cols}")
|
| 75 |
-
|
| 76 |
-
# features에 없는 필수 컬럼 추가
|
| 77 |
-
for col in required_cols:
|
| 78 |
-
if col not in features:
|
| 79 |
-
features.append(col)
|
| 80 |
-
|
| 81 |
-
# 존재하는 컬럼만 선택
|
| 82 |
-
available_features = [f for f in features if f in df.columns]
|
| 83 |
-
df = df[available_features]
|
| 84 |
-
|
| 85 |
-
# 연도 필터링
|
| 86 |
-
if years:
|
| 87 |
-
df = df.loc[df['year'].isin(years), :]
|
| 88 |
-
|
| 89 |
-
return df
|
| 90 |
-
|
| 91 |
-
except FileNotFoundError:
|
| 92 |
-
raise FileNotFoundError(f"데이터 파일을 찾을 수 없습니다: {file_path}")
|
| 93 |
-
except Exception as e:
|
| 94 |
-
raise RuntimeError(f"데이터 로드 중 오류 발생: {e}")
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
# ==========================================
|
| 98 |
-
# 2. Trend 분석 함수
|
| 99 |
-
# ==========================================
|
| 100 |
-
|
| 101 |
-
def get_monthly_trend(df: pd.DataFrame, variable: str) -> pd.DataFrame:
|
| 102 |
-
"""월별 평균, Q1, Q3를 계산합니다.
|
| 103 |
-
|
| 104 |
-
Args:
|
| 105 |
-
df: 데이터프레임
|
| 106 |
-
variable: 분석할 변수명
|
| 107 |
-
|
| 108 |
-
Returns:
|
| 109 |
-
pd.DataFrame: 월별 trend 데이터프레임
|
| 110 |
-
- year: 연도
|
| 111 |
-
- month: 월
|
| 112 |
-
- mean: 평균값
|
| 113 |
-
- q1: 1사분위수
|
| 114 |
-
- q3: 3사분위수
|
| 115 |
-
- date: 날짜 (월의 첫날)
|
| 116 |
-
|
| 117 |
-
Raises:
|
| 118 |
-
ValueError: 변수가 데이터프레임에 없는 경우
|
| 119 |
-
"""
|
| 120 |
-
if variable not in df.columns:
|
| 121 |
-
raise ValueError(f"변수 '{variable}'가 데이터프레임에 없습니다.")
|
| 122 |
-
|
| 123 |
-
if 'year' not in df.columns or 'month' not in df.columns:
|
| 124 |
-
raise ValueError("데이터프레임에 'year'와 'month' 컬럼이 필요합니다.")
|
| 125 |
-
|
| 126 |
-
# 월별 평균, Q1, Q3 계산
|
| 127 |
-
monthly = df.groupby(['year', 'month'])[variable].agg([
|
| 128 |
-
'mean',
|
| 129 |
-
lambda x: x.quantile(0.25),
|
| 130 |
-
lambda x: x.quantile(0.75)
|
| 131 |
-
]).reset_index()
|
| 132 |
-
|
| 133 |
-
monthly.columns = ['year', 'month', 'mean', 'q1', 'q3']
|
| 134 |
-
|
| 135 |
-
# 날짜 컬럼 생성 (월의 첫날로)
|
| 136 |
-
monthly['date'] = pd.to_datetime(
|
| 137 |
-
monthly['year'].astype(str) + '-' +
|
| 138 |
-
monthly['month'].astype(str).str.zfill(2) + '-01'
|
| 139 |
-
)
|
| 140 |
-
|
| 141 |
-
# 날짜 순으로 정렬
|
| 142 |
-
monthly = monthly.sort_values('date')
|
| 143 |
-
|
| 144 |
-
return monthly
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
def calculate_trend_slope(trend_data: pd.DataFrame) -> float:
|
| 148 |
-
"""선형 트렌드의 기울기를 계산합니다.
|
| 149 |
-
|
| 150 |
-
Args:
|
| 151 |
-
trend_data: get_monthly_trend()로 생성된 데이터프레임
|
| 152 |
-
|
| 153 |
-
Returns:
|
| 154 |
-
float: 월별 변화율 (기울기)
|
| 155 |
-
"""
|
| 156 |
-
if len(trend_data) < 2:
|
| 157 |
-
return 0.0
|
| 158 |
-
|
| 159 |
-
# 선형 회귀로 기울기 계산
|
| 160 |
-
z = np.polyfit(range(len(trend_data)), trend_data['mean'], 1)
|
| 161 |
-
slope = z[0]
|
| 162 |
-
|
| 163 |
-
return slope
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
# ==========================================
|
| 167 |
-
# 3. 시각화 함수
|
| 168 |
-
# ==========================================
|
| 169 |
-
|
| 170 |
-
def plot_monthly_trend(
|
| 171 |
-
trend_data: pd.DataFrame,
|
| 172 |
-
variable: str,
|
| 173 |
-
ax: Optional[plt.Axes] = None,
|
| 174 |
-
title: Optional[str] = None,
|
| 175 |
-
show_slope: bool = True
|
| 176 |
-
) -> plt.Axes:
|
| 177 |
-
"""단일 변수의 월별 trend를 시각화합니다.
|
| 178 |
-
|
| 179 |
-
Args:
|
| 180 |
-
trend_data: get_monthly_trend()로 생성된 데이터프레임
|
| 181 |
-
variable: 변수명 (제목에 사용)
|
| 182 |
-
ax: matplotlib Axes 객체 (None이면 새로 생성)
|
| 183 |
-
title: 그래프 제목 (None이면 자동 생성)
|
| 184 |
-
show_slope: 월별 변화율 표시 여부
|
| 185 |
-
|
| 186 |
-
Returns:
|
| 187 |
-
plt.Axes: 생성된 또는 사용된 Axes 객체
|
| 188 |
-
"""
|
| 189 |
-
if ax is None:
|
| 190 |
-
fig, ax = plt.subplots(figsize=(8, 6))
|
| 191 |
-
|
| 192 |
-
# 평균값 플롯
|
| 193 |
-
ax.plot(trend_data['date'], trend_data['mean'], 'o-', color='blue', label='Mean')
|
| 194 |
-
|
| 195 |
-
# Q1, Q3 플롯
|
| 196 |
-
ax.plot(trend_data['date'], trend_data['q1'], 's--', color='orange', alpha=0.7, label='Q1')
|
| 197 |
-
ax.plot(trend_data['date'], trend_data['q3'], 's--', color='purple', alpha=0.7, label='Q3')
|
| 198 |
-
|
| 199 |
-
# 선형 트렌드선
|
| 200 |
-
if len(trend_data) > 1:
|
| 201 |
-
z = np.polyfit(range(len(trend_data)), trend_data['mean'], 1)
|
| 202 |
-
p = np.poly1d(z)
|
| 203 |
-
ax.plot(trend_data['date'], p(range(len(trend_data))), "r--", linewidth=1, alpha=0.6)
|
| 204 |
-
|
| 205 |
-
if show_slope:
|
| 206 |
-
slope = z[0]
|
| 207 |
-
ax.text(
|
| 208 |
-
trend_data['date'].iloc[0],
|
| 209 |
-
trend_data['mean'].max(),
|
| 210 |
-
f'Monthly Change Rate: {slope:.4f}/month',
|
| 211 |
-
fontsize=10,
|
| 212 |
-
color='darkred'
|
| 213 |
-
)
|
| 214 |
-
|
| 215 |
-
# 제목 설정
|
| 216 |
-
if title is None:
|
| 217 |
-
title = f'{variable} Monthly Trend'
|
| 218 |
-
ax.set_title(title, fontsize=14)
|
| 219 |
-
|
| 220 |
-
# 축 레이블 설정
|
| 221 |
-
ax.set_xlabel('Date', fontsize=12)
|
| 222 |
-
ax.set_ylabel(variable, fontsize=12)
|
| 223 |
-
|
| 224 |
-
# 그리드 및 범례
|
| 225 |
-
ax.grid(True, linestyle='--', alpha=0.7)
|
| 226 |
-
ax.legend()
|
| 227 |
-
|
| 228 |
-
# x축 날짜 포맷
|
| 229 |
-
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
|
| 230 |
-
plt.setp(ax.xaxis.get_majorticklabels(), rotation=45)
|
| 231 |
-
|
| 232 |
-
return ax
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
def plot_multiple_trends(
|
| 236 |
-
df: pd.DataFrame,
|
| 237 |
-
variables: List[str],
|
| 238 |
-
figsize: Tuple[int, int] = (16, 6),
|
| 239 |
-
show_slope: bool = True
|
| 240 |
-
) -> plt.Figure:
|
| 241 |
-
"""여러 변수의 월별 trend를 동시에 시각화합니다.
|
| 242 |
-
|
| 243 |
-
Args:
|
| 244 |
-
df: 원본 데이터프레임
|
| 245 |
-
variables: 분석할 변수 리스트
|
| 246 |
-
figsize: 그림 크기
|
| 247 |
-
show_slope: 월별 변화율 표시 여부
|
| 248 |
-
|
| 249 |
-
Returns:
|
| 250 |
-
plt.Figure: 생성된 Figure 객체
|
| 251 |
-
"""
|
| 252 |
-
n_vars = len(variables)
|
| 253 |
-
fig, axes = plt.subplots(1, n_vars, figsize=figsize)
|
| 254 |
-
|
| 255 |
-
# 단일 변수인 경우 axes를 리스트로 변환
|
| 256 |
-
if n_vars == 1:
|
| 257 |
-
axes = [axes]
|
| 258 |
-
|
| 259 |
-
for i, var in enumerate(variables):
|
| 260 |
-
if var in df.columns:
|
| 261 |
-
trend = get_monthly_trend(df, var)
|
| 262 |
-
plot_monthly_trend(trend, var, ax=axes[i], show_slope=show_slope)
|
| 263 |
-
else:
|
| 264 |
-
axes[i].text(0.5, 0.5, f'{var} Column not found', ha='center', va='center', fontsize=12)
|
| 265 |
-
axes[i].set_title(f'{var} (No data)', fontsize=14)
|
| 266 |
-
|
| 267 |
-
plt.tight_layout()
|
| 268 |
-
return fig
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
# ==========================================
|
| 272 |
-
# 4. 메인 분석 함수
|
| 273 |
-
# ==========================================
|
| 274 |
-
|
| 275 |
-
def analyze_trend(
|
| 276 |
-
region: str,
|
| 277 |
-
variables: List[str],
|
| 278 |
-
years: Optional[List[int]] = None,
|
| 279 |
-
features: Optional[List[str]] = None,
|
| 280 |
-
show_plot: bool = True,
|
| 281 |
-
figsize: Tuple[int, int] = (16, 6),
|
| 282 |
-
show_slope: bool = True
|
| 283 |
-
) -> Dict[str, Any]:
|
| 284 |
-
"""지역과 변수를 받아 월별 trend를 분석하고 시각화합니다.
|
| 285 |
-
|
| 286 |
-
Args:
|
| 287 |
-
region: 지역명 ('seoul', 'busan', 'daegu', 'incheon', 'gwangju', 'daejeon')
|
| 288 |
-
variables: 분석할 변수 리스트 (예: ['hm', 'PM25', 'temp_C', 'O3'])
|
| 289 |
-
사용 가능한 변수: hm, PM10, PM25, O3, NO2, temp_C, wind_speed,
|
| 290 |
-
cloudcover, solarRad, precip_mm, vap_pressure, dewpoint_C,
|
| 291 |
-
loc_pressure, sea_pressure, visi, groundtemp, ground_temp - temp_C 등
|
| 292 |
-
years: 분석할 연도 리스트 (기본값: [2018, 2019, 2020, 2021, 2022, 2023])
|
| 293 |
-
features: 데이터에서 선택할 컬럼 리스트
|
| 294 |
-
(기본값: None - 주요 변수들 자동 포함)
|
| 295 |
-
show_plot: 시각화 표시 여부
|
| 296 |
-
figsize: 그림 크기
|
| 297 |
-
show_slope: 월별 변화율 표시 여부
|
| 298 |
-
|
| 299 |
-
Returns:
|
| 300 |
-
dict: 분석 결과
|
| 301 |
-
- data: 필터링된 데이터프레임
|
| 302 |
-
- trends: 각 변수별 trend 데이터프레임 딕셔너리
|
| 303 |
-
- slopes: 각 변수별 월별 변화율 딕셔너리
|
| 304 |
-
|
| 305 |
-
Example:
|
| 306 |
-
>>> result = analyze_trend('seoul', ['hm', 'PM25', 'temp_C', 'O3'])
|
| 307 |
-
>>> print(result['slopes'])
|
| 308 |
-
{'hm': 0.0123, 'PM25': -0.0456, 'temp_C': 0.0234, 'O3': -0.0012}
|
| 309 |
-
"""
|
| 310 |
-
# 한글 폰트 설정
|
| 311 |
-
setup_korean_font()
|
| 312 |
-
|
| 313 |
-
# 데이터 로드 및 필터링
|
| 314 |
-
df = load_region_data(region, features=features, years=years)
|
| 315 |
-
|
| 316 |
-
# 각 변수별 trend 계산
|
| 317 |
-
trends = {}
|
| 318 |
-
slopes = {}
|
| 319 |
-
|
| 320 |
-
for var in variables:
|
| 321 |
-
if var in df.columns:
|
| 322 |
-
trend_data = get_monthly_trend(df, var)
|
| 323 |
-
trends[var] = trend_data
|
| 324 |
-
slopes[var] = calculate_trend_slope(trend_data)
|
| 325 |
-
else:
|
| 326 |
-
print(f"Warning: 변수 '{var}'가 데이터에 없습니다.")
|
| 327 |
-
trends[var] = None
|
| 328 |
-
slopes[var] = None
|
| 329 |
-
|
| 330 |
-
# 시각화
|
| 331 |
-
if show_plot:
|
| 332 |
-
plot_multiple_trends(df, variables, figsize=figsize, show_slope=show_slope)
|
| 333 |
-
plt.show()
|
| 334 |
-
|
| 335 |
-
return {
|
| 336 |
-
'data': df,
|
| 337 |
-
'trends': trends,
|
| 338 |
-
'slopes': slopes
|
| 339 |
-
}
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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