본문 바로가기
Data Projects/ecommerce 로그 데이터 분석 프로젝트

[ecommerce 웹 로그 분석] 4. XGBoost 사용한 고객 행동 예측 모델

by 천뿌니 2022. 6. 28.
728x90

이번 프로젝트는 kaggle에서 제공하는 데이터셋인 eCommerce 웹 로그 데이터 분석 프로젝트이다.

1. 데이터 전처리

2. 데이터 분석 & 시각화

3. 데이터 모델링

해당 파일은 xgboost를 사용한 고객 구매 정확도 모델을 만들 것이다.

가격과 브랜드를 포함한 여러 개의 피처들을 사용하여 고객이 결국 장바구니에 있는 항목을 구매할지 여부를 예측하는 파일이다.

 


데이터 load & import

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import datetime as dt

from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from xgboost import plot_importance
from sklearn.utils import resample
from sklearn import metrics

%matplotlib inline

ecommerce_df = pd.read_csv("refined_2019_Oct.csv", index_col = 0)

 

모델링

event_type이 cart인 제품을 고객이 구매할지 안 할지 예측하는 모델링한다.

피처 엔지니어링

머신러닝 모델을 학습시키기 위해서 데이터를 재구조화한다. 이때 고객이 장바구니에 제품을 "cart" 데이터만 대상으로 할 것이다.

  • category_code_level1: 카테고리
  • category_code_level2: 하위 카테고리
  • event_weekday: 요일
  • activity_count: 세션 활동 수
  • is_purchased: cart 제품 구매 여부

train 데이터 세트에는 위에서 언급한 새로운 기능과 함께 중복되지 않은 모든 장바구니 트랜잭션이 포함한다.
원래 가격과 브랜드를 포함한 이러한 기능을 사용하여 고객이 결국 장바구니에 있는 항목을 구매할지 여부를 예측한다.

 

  1. event_type이 cart, purchase인 데이터를 대상으로 중복 없이 추출한다.
  2. event_type이 puchasedlaus 1, 아니면 0인 새로운 "is_purchased" 칼럼을 생성한다.
  3. "user_session", "product_id"가 같다면 같은 제품에 대한 처리이기 때문에 하나라도 구입한 사례가 있으면 1로 처리한다.
  4. 우리의 목표는 cart에 있는 항묵을 구매할지 여부를 예측하는 것이니 cart인 데이터를 대상으로 중복 없이 추출한다.
  5. "kst_time"에 weekday 함수를 사용해 요일을 추출해 새로운 "event_weekend" 칼럼을 생성한다.. (0-월 ~ 6-일)
  6. 상위 카테고리와 하위 카테고리를 추출하기 위해 category_code에 split을 하고 category 타입으로 astype하여 추출해 새로운 칼럼들을 생성한다.
df_targets = ecommerce_df.loc[ecommerce_df["event_type"].isin(["cart","purchase"])].drop_duplicates(subset=['event_type', 'product_id','price', 'user_id','user_session'])
df_targets["is_purchased"] = np.where(df_targets["event_type"] == "purchase", 1, 0)
df_targets["is_purchased"] = df_targets.groupby(["user_session", "product_id"])["is_purchased"].transform("max")
df_targets = df_targets.loc[df_targets["event_type"] == "cart"].drop_duplicates(["user_session", "product_id", "is_purchased"])
df_targets['event_weekend'] = df_targets['kst_time'].apply(lambda s: str(datetime.strptime(str(s)[0:10], "%Y-%m-%d").weekday()))
df_targets["category_code_level1"] = df_targets["category_code"].str.split(".", expand=True)[0].astype("category")
df_targets["category_code_level2"] = df_targets["category_code"].str.split(".", expand=True)[1].astype("category")

세션 활동 수 칼럼 생성

  1. event_type이 cart와 purchase가 있는 user_id 데이터만 뽑는다.
  2. user_session 별 그룹핑하여 evnet_type의 개수를 세면 해당 세션의 활동 수가 나온다.
  3. event_type 명을 activity_count로 rename 한다.
cart_purchase_users = ecommerce_df[ecommerce_df["event_type"].isin(["cart", "purchase"])].drop_duplicates(subset = ["user_id"])
cart_purchase_users_al_activity = ecommerce_df.loc[ecommerce_df['user_id'].isin(cart_purchase_users['user_id'])]
activity_in_session = cart_purchase_users_al_activity.groupby(['user_session'])['event_type'].count().reset_index()
activity_in_session = activity_in_session.rename(columns={"event_type": "activity_count"})

새롭게 만든 칼럼들이 있는 데이터 프레임과 세션 활동 수 칼럼의 데이터 프레임을 merge 한다.

 

resampling 진행

  • training set에서 반복해서 sample을 뽑고, 거기에 반복에서 model을 적합시켜 볼 것이다.

n_samples = 200000
is_purchase_sample = resample(is_purchase_set, replace=False, n_samples=n_samples, random_state=27)
not_purchase_sample = resample(not_purchase_set, replace=False, n_samples=n_samples, random_state=27)

sampled = pd.concat([is_purchase_sample, not_purchase_sample])
sampled['is_purchased'].value_counts()

features = sampled.loc[:,['brand', 'price', 'event_weekend', 'category_code_level1', 'category_code_level2', 'activity_count']]

 

카테고리 칼럼 Encode

모델을 학습시키기 위해 칼럼들의 값들이 숫자형으로 인코딩하는 작업이 요구된다. 카테고리 데이터들을 인코딩하는 간단한 방법인 labelencoder를 사용할 것이다.

features.loc[:,'brand'] = LabelEncoder().fit_transform(sampled.loc[:,'brand'].copy())
features.loc[:,'event_weekend'] = LabelEncoder().fit_transform(sampled.loc[:,'event_weekend'].copy())
features.loc[:,'category_code_level1'] = LabelEncoder().fit_transform(sampled.loc[:,'category_code_level1'].copy())
features.loc[:,'category_code_level2'] = LabelEncoder().fit_transform(sampled.loc[:,'category_code_level2'].copy())

is_purchased = LabelEncoder().fit_transform(sampled['is_purchased']) # 정답 배열 - 구입 여부

 

데이터 분리 & 모델 학습

X_train, X_test, y_train, y_test = train_test_split(features, is_purchased, test_size = 0.3, random_state = 0)

from xgboost import XGBClassifier
model = XGBClassifier(learning_rate = 0.1)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

 

피처 중요도

 

마무리

이번 포스팅은 데이터에서 피처 엔지니어링을 통해 XGBoost 사용한 고객 행동 예측 모델을 만들고, 정확도를 측정해봤습니다. ecommerce 웹 로그 분석 프로젝트는 여기까지입니다. 

해당 프로젝트는 아래 github에 상세히 정리가 되어 있어서 많은 관심 부탁드립니다. 개인으로 진행한 프로젝트라 정확하지 않을 수 있는 점 양해 부탁드립니다. 감사합니다.

 

https://github.com/JunSeokCheon/eCommerce_weblog_analysis

 

GitHub - JunSeokCheon/eCommerce_weblog_analysis

Contribute to JunSeokCheon/eCommerce_weblog_analysis development by creating an account on GitHub.

github.com

댓글