728x90
반응형
시계열 데이터 분석은 데이터가 시간의 흐름에 따라 변하는 패턴을 분석하는 방법입니다. 예를 들어 주식 가격, 기온, 판매량 등과 같은 데이터를 분석할 때 사용됩니다. 아래는 시계열 데이터 분석의 예시입니다.
예시: 월별 온도 변화 분석
1. 데이터 준비
먼저, 예시 데이터를 생성하겠습니다. 월별 온도 변화를 나타내는 시계열 데이터를 생성하겠습니다.
import pandas as pd
import numpy as np
# 날짜 범위 생성 (2020년 1월부터 2022년 12월까지)
dates = pd.date_range(start='2020-01-01', end='2022-12-31', freq='M')
# 임의의 온도 데이터 생성
np.random.seed(0)
temperatures = 20 + 10 * np.sin(np.linspace(0, 3*np.pi, len(dates))) + np.random.normal(0, 2, len(dates))
# 데이터프레임 생성
df = pd.DataFrame({'Date': dates, 'Temperature': temperatures})
# 데이터 확인
df.head()
2. 데이터 시각화
데이터의 변화를 시각화하여 패턴을 확인합니다.
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
plt.plot(df['Date'], df['Temperature'], marker='o')
plt.title('Monthly Temperature Change')
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.grid(True)
plt.show()
3. 이동 평균 적용
데이터의 노이즈를 줄이고 추세를 더 잘 보기 위해 이동 평균을 적용합니다.
df['Temperature_MA'] = df['Temperature'].rolling(window=3).mean()
plt.figure(figsize=(12, 6))
plt.plot(df['Date'], df['Temperature'], marker='o', label='Original')
plt.plot(df['Date'], df['Temperature_MA'], color='red', label='Moving Average')
plt.title('Monthly Temperature Change with Moving Average')
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.legend()
plt.grid(True)
plt.show()
4. 시계열 분해
시계열 데이터를 추세(trend), 계절성(seasonality), 잔차(residual)로 분해합니다.
from statsmodels.tsa.seasonal import seasonal_decompose
# 시계열 분해
result = seasonal_decompose(df.set_index('Date')['Temperature'], model='additive')
# 분해 결과 시각화
result.plot()
plt.show()
5. 예측 모델 적용
ARIMA (AutoRegressive Integrated Moving Average) 모델을 사용하여 미래의 값을 예측합니다.
from statsmodels.tsa.arima.model import ARIMA
# ARIMA 모델 생성 및 학습
model = ARIMA(df['Temperature'], order=(5, 1, 0))
model_fit = model.fit()
# 예측
forecast = model_fit.forecast(steps=12)
# 예측 결과 시각화
plt.figure(figsize=(12, 6))
plt.plot(df['Date'], df['Temperature'], marker='o', label='Original')
plt.plot(pd.date_range(start=dates[-1] + pd.DateOffset(months=1), periods=12, freq='M'), forecast, color='red', marker='o', label='Forecast')
plt.title('Temperature Forecast')
plt.xlabel('Date')
plt.ylabel('Temperature (°C)')
plt.legend()
plt.grid(True)
plt.show()
위의 예시는 시계열 데이터를 분석하는 기본적인 과정입니다. 실제 분석에서는 데이터의 특성에 따라 다양한 모델과 기법을 적용할 수 있습니다.
728x90
반응형
'programming > 파이썬으로 배우는 통계학' 카테고리의 다른 글
[파이썬/머신러닝] sklearn.RandomForestClassifier로 다항분류 모델링하기 (2) | 2024.01.07 |
---|---|
[파이썬/머신러닝] 가중치(coef),편향(intercept)에 관하여 (2) | 2024.01.07 |
[파이썬/머신러닝] 로지스틱 회귀 알고리즘의 유형 (0) | 2024.01.07 |
K-Fold 교차 검증_모델 성능 평가 (0) | 2023.07.24 |
머신러닝 훈련데이터와 테스트데이터 나누는 방법 (0) | 2023.07.23 |