Forecasts for Product Demand (3) 시계열 기반 데이터 탐색 및 시각화
LearnerToRunner
2023. 1. 3. 00:09
Forecasts for Product Demand
시계열 기반 데이터 탐색 및 시각화
Date를 기반으로 추출한
year, month, week, day of the week를 기준으로
데이터셋을 더 살펴보았습니다
[Order Demand 관점] Order Demand 데이터는 시간별로 고르게 분포되어있나? 2011, 2017년은 데이터가 부족 매 년 1~3번째 주, 17~20째 주 사이 데이터 수가 급감하는 경향
# Additional Time features
df['Year_Month'] = df['Date'].dt.strftime('%Y-%m')
df['Year_Week'] = df['Date'].dt.strftime('%Y-%W')
# Order Demand by year and date
cols_view = ['Year', 'Year_Month', 'Year_Week', 'Date']
# Data Distribution Check
print(df.groupby('Year')['Order_Demand'].count())
print(df['Date'].min(), df['Date'].max())
for col in cols_view:
df_view = df.copy().sort_values(by=col)
# sns.barplot(data=data, kde=True)
sns.histplot(data=df_view, x=col, kde=True)
# sns.histplot(data=df, x=col, kde=True)
plt.title(f'Number of Data by {col}')
plt.xticks(rotation=60, fontsize=6)
plt.show()
연도별 데이터 수 - 2011, 2017년 데이터가 월등히 부족시간데이터 범위 - 2017년 데이터는 2017/1/9까지 밖에없음
# Order Demand by year and date
cols_view = ['Year', 'Year_Month', 'Year_Week', 'Date']
for i, col in enumerate(cols_view):
data_grp = df.groupby(col, as_index=False)['Order_Demand'].sum()
plt.plot(data_grp[col], data_grp['Order_Demand'], label = col)
plt.title(f'Order Demand by {col}')
plt.xticks(rotation=60, fontsize=6)
plt.tight_layout()
plt.show() #시각화할 데이터가 많으므로 subplot을 이용하지 않았음.
"""
# Subplots을 이용하고 싶다면?
f, ax = plt.subplots(1, len(cols_view))
for i, col in enumerate(cols_view):
data_grp = df.groupby(col, as_index=False)['Order_Demand'].sum()
ax[i].plot(data_grp[col], data_grp['Order_Demand'], label = col)
ax[i].set_title(f'Order Demand by {col}')
ax[i].set_xticklabels(ax[i].get_xticks(), rotation = 70)
f.tight_layout()
plt.show()
"""
Order Demand 추이는 어떤가? 2015년을 기점으로 trend가 하락세로 바뀌었음Order demand on yearly basis
약 3개월 간격의 seasonality가 있는듯 함 2014년 8월 추세 이탈 발생 (이상치)
To_Dos - 월, 주, 일 기준 seasonality 체크해보기
Order demand on monthly basisOrder demand on weekly basisorder demand on daily basis
연/월/주/일 별 Order Demand 분포는 어떤가? On a yearly basis (2011, 2017 제외) Interquartile range, median, 1.5*IQR whisker관점에서 큰 차이가 보이지 않음 On a monthly basis Interquartile range, median, 1.5*IQR whisker관점에서 큰 차이가 보이지 않음
10월 order demand median이 상대적으로 낮아지는 경향이 있음 On a weekly basis 52, 53주차 (연말)에 Q3, median이 높아지는 경향이 있음 On a daily basis 토요일(5)에 Order Demand가 가장 적음 Interquartile range, median, 1.5*IQR whisker관점에서 평일은 차이가 없음 FYI) Mon 0 - Sun = 6
근거
# Order Demand Boxplot by Time
cols_view = ['Year', 'Month', 'Week', 'DayOW']
df_view = df.copy().dropna()
for col in cols_view:
sns.boxplot(data = df_view, x=col, y='Order_Demand')
plt.title(f'Order Demand Boxplot by {col}')
plt.xticks(rotation = 60, fontsize = 6)
plt.show()
연 별 order demand
월 별 order demand
Week of the year 별 order demand
Day of the week 별 order demand
[Warehouse 관점] 웨어하우스 별 Order Demand 추이는 어떤가?
# Order Demand by Time (Warehouse Perspective)
cols_view = ['Year', 'Year_Month', 'Year_Week', 'Date']
ls_wh = df['Warehouse'].unique()
for col in cols_view:
data = df.groupby([col, 'Warehouse'], as_index=False)['Order_Demand']
od_sum = data.sum()
sns.lineplot(data= od_sum, x=col, y='Order_Demand', hue='Warehouse')
plt.legend()
plt.title(f'Total Order Demand by {col}')
plt.xticks(rotation=60, fontsize=6)
plt.show()
웨어하우스 공통으로 order demand가 급감하는 구간이 간혹 보임
제품 카테고리 관점
제품군 별 수요 추이는 어떨까? 전체 수요량 추이와 비슷한듯 함
## Product Category Perspective
cols_view = ['Year', 'Year_Month', 'Year_Week', 'Date']
for col in cols_view:
df_view = df.groupby([col, 'Product_Category'], as_index=False)['Order_Demand'].sum()
sns.lineplot(data = df_view, x=col, y='Order_Demand', hue='Product_Category')
plt.xticks(rotation=60, fontsize=8)
plt.title(f'Product Category Demand by {col}')
plt.legend()
plt.show()
시계열 분해 시각화
# Seasonal Decomposition
import statsmodels.api as sm
df_od = df.groupby('Date')['Order_Demand'].sum()
# 오더 디맨드 시각화
# plt.plot(df_od)
# plt.show()
# >> additive 모델 적용
for i, period in enumerate([7, 30, 90, 180, 365]):
decomposition = sm.tsa.seasonal_decompose(df_od, model='additive', period=period)
decomposition.plot()
plt.title(f'Seasonal Decomposition (Period = {period})')
plt.show()
TO-DOs 데이터 시각화 시간에 따른 데이터 시각화, Order Demand 음수 데이터 관찰
trend, seasonality 시각화 결측치 처리, 중복 데이터 처리
오더취소 횟수, 취소량 특징으로 추가하기
2011년, 2017년 데이터 drop 하기main 파일 만들어서 EDA에서 추가한 특징 재현하기