본문 바로가기
TOY Project

[Project] ML모형을 활용한 Bank Marketing의 고객 가입여부 예측

by LydiaRyu 2021. 8. 27.
반응형
  • 분석 동기 

직접 전화하는 마케팅이 고객의 가입 여부에 영향을 미치는지 분석하기 위한 프로젝트이다. 2012년 데이터로 지금의 상황과는 다를 수 있다. 그러나, 가입/미가입으로 분류하는 예측 모델을 만드는 것에 의의를 두며 향후 현 상황의 데이터로  은행에서 마케팅에 영향을 미치는 요소를 분석하거나 채무불이행(Default/ Non-default)을 분류할 때 사용할 수 있을 것으로 예상한다. 

 

  • 본론
  • 데이터 구성

데이터는 UCI Machine Learning Repository에서 제공하는 Bank Marketing Data Set을 사용한다. 분석에 사용된 데이터는 2008년 5월에서 2010년 11월까지 수집된 데이터이다.

Data Set Characteristics:  Multivariate Number of Instances: 41188
Associated Tasks: Classification Number of Attributes: 21

 

  • 변수 설명

- Input variables:
# bank client data:
1 age (numeric)
2 job : type of job (categorical: 'admin.', 'blue-collar', 'entrepreneur', 'housemaid', 'management', 'retired', 'self-employed', 'services', 'student', 'technician', 'unemployed', 'unknown')
3 marital : marital status (categorical: 'divorced', 'married', 'single', 'unknown'; note: 'divorced' means divorced or widowed)
4 education (categorical: 'basic.4y', 'basic.6y', 'basic.9y', 'high.school', 'illiterate', 'professional.course', 'university.degree', 'unknown')
5 default: has credit in default? (categorical: 'no', 'yes', 'unknown')
6 housing: has housing loan? (categorical: 'no', 'yes', 'unknown')
7 loan: has personal loan? (categorical: 'no', 'yes', 'unknown')
# related with the last contact of the current campaign:
8 contact: contact communication type (categorical: 'cellular', 'telephone')
9 month: last contact month of year (categorical: 'jan', 'feb', 'mar',..., 'nov', 'dec')
10 day_of_week: last contact day of the week (categorical: 'mon', 'tue', 'wed', 'thu', 'fri')
11 duration: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y='no'). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model.
# other attributes:
12 campaign: number of contacts performed during this campaign and for this client (numeric, includes last contact)
13 pdays: number of days that passed by after the client was last contacted from a previous campaign (numeric; 999 means client was not previously contacted)
14 previous: number of contacts performed before this campaign and for this client (numeric)
15 poutcome: outcome of the previous marketing campaign (categorical: 'failure', 'nonexistent', 'success')
# social and economic context attributes
16 emp.var.rate: employment variation rate - quarterly indicator (numeric)
17 cons.price.idx: consumer price index - monthly indicator (numeric)
18 cons.conf.idx: consumer confidence index - monthly indicator (numeric)
19 euribor3 m: euribor 3 month rate - daily indicator (numeric)
20 nr.employed: number of employees - quarterly indicator (numeric)

Output variable (desired target):
21 y:  has the client subscribed a term deposit? (binary: 'yes', 'no')

 

  • EDA

[Missing Value]

 

- 결측 값 확인 결과 존재하지 않기 때문에 분석을 진행한다. (full data set으로 결측 값이 존재하지 않는 것으로 추측)

 

[Encoding]

 

- 반응 변수 y를 가입한 경우('yes') 1으로, 가입하지 않은 경우('no') 0으로 변경한다. 

- One-hot encoding을 이용하여 범주형 변수를 더미화시킨다. 

 

[Visualization]

왼쪽: Age / 오른쪽: Duration

 

- 반응 변수(y)에 연령별로 미치는 영향을 파악하기 위해서 Age 변수를 geom-density로 시각화했다. 25세에서 50세 사이에 많이 분포되어 있으며, 가입과 미가입의 연령별 분포가 비슷한 모양을 띄고 있는 것을 확인할 수 있다.

- 전화 마케팅 시 지속 시간이 0에 가까울수록 미가입의 정도가 높은 것으로 보아 duration 변수가 결과에 많은 영향을 미치는 것을 볼 수 있다. duration은 초 단위로, 2000초를 넘기는 경우는 거의 없으며 500-1000초 사이의 지속기간이 있을수록 가입이 이루어지고 있다.

 

  • 모형 적합

[Divide Training Set and Test Set]

 

- 데이터 분할은 Training Set 60%, Test Set 40%로 랜덤 하게 나누어 진행한다. 

- 분할한 결과 Training Set의 length가 24712, Test Set의 length가 16475로 산출된다. 

 

[Modeling]

 

1) Logistic Regression

 

- GLM함수를 사용하고, family를 binomial("logit")으로 모형 적합시킨다. 

- 변수 전체를 사용하기에는 변수가 너무 많고, 의미 있는 결과를 도출하기 어렵기 때문에 p-value가 0.01 이하로 산출되는 변수들만 재적합한다. 

- 다중 공선성을 가지는 변수들은 제거한다. 

- predict 함수를 사용하여 Y^hat의 예측 모형을 만들어 준다. 아래 그래프는 Test Set과 Y^hat Set을 비교해 보기 위한 그래프로 box-plot과 density함수를 사용했다. 아무래도 duration의 영향이 크다 보니 위에서 duration으로 density를 그린 그래프와 비슷한 분포를 띄고 있다. 향후 추가 분석에서는 이 변수를 제외하고 분석해 볼 필요가 있을 것이다. 

GLM ggplot

 

2) Glmnet

 

- cv.glmnet 함수를 이용하여 모형 적합을 한다. 이때, family는 binomial로 지정한다. 적합한 결과에서 최적화된 람다를 구하기 위해 Plot으로 그리면 아래와 같은 그래프가 나온다. 왼쪽의 수직선은 람다의 최솟값에 해당하는 값이고, 오른쪽의 수직선은 1 표준편차 안에서의 정규화된 모델을 나타낸다. 

Plot

 

- coefficient가 양수인 경우의 length를 구하면 최솟값은 29, 1 표준편차 안에서 length는 9가 산출된다. 

- Alpha 값을 구하기 위해서 alpha가 1, 0.5, 0 일 때 값들로 적합시킨 후 plot 그림을 그린다. 그래프를 통해서 alpha가 1일 때의 lasso모형이 가장 적합하다는 것을 확인할 수 있으며, 람다의 범위가 alpha 값에 의해서 달라지는 것을 볼 수 있다.

Plot

 

- predict 함수를 이용해서 람다가 1 표준편차 일 때의 Y^hat 예측 모형을 만든다.

 

3) Decision Tree

 

- rpart 함수를 사용하여 모형을 적합시킨다. 적합시킨 모형을 plot으로 그리면 아래와 같은 의사결정 나무(Decision Tree) 그래프가 작성된다.

Plot

 

- 이때, 모든 변수로 모델링하면 과적합이 발생할 수 있으므로, 가지치기(Pruning)를 한다.  plotcp를 이용하여 그려주면, 3 -> 4까지 하강하는 모양이고, 이후 값들에서는 비슷하게 일정한 모양을 띄고 있다. 따라서, prune 함수를 이용하여 4번째에서 가지치기를 진행한다.

 

- 가지 치기를 한 모형으로 predict 함수를 사용해서 Y^hat을 예측하는 작업을 한다.

 

4) Random Forest

 

- 먼저, 전체 feature를 사용하여 randomForest 함수로 모형 적합을 시켜본다. 500개의 트리가 산출되고, 5.35%로 오류율이 나온다.(Confusion Matrix)

- 변수 전체를 입력하면 과적합(Overfitting)이 발생할 수 있기 때문에 varImpPlot을 사용하여 변수의 중요도를 파악한다. 아래의 결과는 지니계수로 계산한 것으로 구분이 되는 Plot들까지를 중요한 변수로 고려한다. 

varImpPlot
Important Values

 

- 중요도가 높은 변수들만 고려하여 모델을 재적합 시키고, predict 함수를 사용하여 Random Forest의 예측모형 Y^hat을 만든다. 

 

  • 결론 도출

[Compare the Models]

 

METHOD RMSE ROC
Logistic Regression 0.2673550 0.8847327
Glmnet 0.2548612 0.9301272
Decision Tree 0.2504250 0.8986976
Random Forest 1.0206071 0.7266485

- 4가지 모델의 RMSE 값을 비교해보면 Decision Tree가 0.2504로 가장 낮고, Glmnet이 0.2549로 비슷한 수준으로 낮다. 따라서 RMSE 값으로 비교해 본 결과 Decision TreeGlmnet 모델의 성능이 높다고 볼 수 있다. 

- ROC 곡선을 비교하면, Glmnet, Logistic Regression, Decision Tree, Random Forest 순으로 성능이 좋다는 것을 확인할 수 있다. 

 

→ 결론적으로, Banking Marketing Data Set의 모형 간의 최종 성능을 RMSE 값과 ROC 곡선으로 비교하면 Glmnet 모형이 가장 높은 일반화 성능을 나타낸다. 

 

데이터 출처: https://archive.ics.uci.edu/ml/datasets/Bank+Marketing 

 

UCI Machine Learning Repository: Bank Marketing Data Set

Bank Marketing Data Set Download: Data Folder, Data Set Description Abstract: The data is related with direct marketing campaigns (phone calls) of a Portuguese banking institution. The classification goal is to predict if the client will subscribe a term d

archive.ics.uci.edu

분석 코드(R):  https://github.com/LydiaRyu/Project/blob/main/Bank%20Marketing%20Prediction.R

 

GitHub - LydiaRyu/Project

Contribute to LydiaRyu/Project development by creating an account on GitHub.

github.com

 

728x90

'TOY Project' 카테고리의 다른 글

[Project] Arima Model을 이용한 주가 예측 분석  (0) 2021.07.18

댓글