파이썬을 활용한 이커머스 데이터분석 (구매요인분석 - Decision Tree)
1. 분석의 목적
디시젼 트리 모델을 통하여 온라인 경매 아이템 판매여부를 예측하고 각 변수의 영향도를 확인
2. 모듈 설치 & 데이터 셋 살펴보기
(1) 모듈 및 데이터 로딩
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
data = pd.read_csv('galaxy.csv')
(2) 데이터 특성 확인하기
데이터 셋 : 온라인 경매 아이템 판매여부
data.head()
여기서 주의할 점 : 'carrier' columns 주의 !
-> None(값이 없는 것, 이 데이터 셋에서는 자급제 폰 ? 이런 것들) 이랑 NaN(결측치) 다름 !
data.describe()
plt.figure(figsize=(20, 10))
sns.boxplot(x='productline', y='startprice', data = data)
3. 결측치 전처리
(1) 칼럼별 결측치 비율 확인하기
data.isna().sum() / len(data)
(2) 결측치는 'Unknown' 으로 채우기
data = data.fillna('Unknown')
4. 카테고리 변수 전처리
DT 모델은 카테고리 변수를 전처리 안 한 상태로 사용해도 모델 돌아감
그러나 복잡한 DT 모델을 만들 경우에, 카테고리 변수를 그대로 사용하는 것은 좋지 못한 습관임
data[['carrier','color','productline','noDescription']].nunique()
(1) Black 종류를 하나로 통합시켜줄 함수 작성
def black(x):
if x in ['Midnight Black','Aura Black','Prism Black']:
return 'Black'
else:
return x
data['color'] = data['color'].apply(lambda x: black(x))
(2) 더미 함수를 이용해서 더미 변수 만들기
data = pd.get_dummies(data, columns = ['carrier', 'color', 'productline', 'noDescription'])
칼럼이 25개로 늘어난 것을 확인해볼 수 있음
5. Decision Tree 모델 만들기
from sklearn.model_selection import train_test_split
X = data.drop('sold', axis = 1)
y = data['sold']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=100)
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(max_depth = 10)
model.fit(X_train, y_train)
DecisionTreeClassifier 할 때, max_depth 정해주는게 필수는 아님,
DecisionTreeClassifier는 "설정하는 파라미터가 없다" 라는 것이 특징
(1) 예측
pred = model.predict(X_test)
(2) 평가
from sklearn.metrics import accuracy_score, confusion_matrix
accuracy_score(y_test, pred)
>>> 0.7878787878787878
6. 최적의 Max Depth 찾기
for i in range(2, 31):
model = DecisionTreeClassifier(max_depth = i)
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(i, round(accuracy_score(y_test, pred), 4))
for 문을 이용해서 accuracy score가 가장 높은 것을 찾으면, max depth는 '3' 정도가 됨
7. Tree Plot 만들기
Tree 시각화 가능
from sklearn.tree import plot_tree
plt.figure(figsize=(20,10))
plot_tree(model, feature_names=X_train.columns, fontsize=15, label ="None", max_depth = 2)
plt.figure(figsize=(20,10))
plot_tree(model, feature_names=X_train.columns, fontsize=15, label ="None", max_depth = 3)
- 특정 변수와 특정 기준점을 잡아서 "예", "아니오" 에 따라 데이터를 분류
- 가장 중요하다가 여겨주는 변수와 기준점부터 적용
- Gini Index : 각 노드가 얼마나 순수한가의 평가지표로 모든 노드가 한 쪽 클래스에 다 속하면 0, 데이터가 정확히 반반일 경우에 0.5의 값을 보여줌. 즉 지니 값이 낮아지는 방향으로 데이터를 분류