统计与机器学习 / 40

机器学习项目:客户流失预测

从假设、目标到模型和评估。 机器学习项目:客户流失预测。

阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。

In this project, we use supervised learning models to identify customers who are likely to churn in the future. Furthermore, we will analyze top factors that influence user retention. Dataset information.

整理注: 仅用于教学,不提供原始数据下载。含客户标识或姓名的历史表格已脱敏;不能据此识别任何个人。

Things need to know

  • 对于0基础的同学,以了解为主
  • 不需要可以从0把code写出来
  • 这部分code与算法课程code的思维不一样
  • 需要下课自己去跑一下code,尽量去理解
  • 工具终归是辅助我们的,先尽力学会一个
  • 逐步掌握python code debug能力

Contents

  • Part 1: Data Exploration(见本篇目录)
  • Part 2: Feature Preprocessing(见本篇目录)
  • Part 3: Model Training and Results Evaluation(见本篇目录)

Part 0: Setup Google Drive Environment / Data Collection

check this link for more info

PYTHON · 仅供阅读
# # install pydrive to load data
# !pip install -U -q PyDrive

# from pydrive.auth import GoogleAuth
# from pydrive.drive import GoogleDrive
# from google.colab import auth
# from oauth2client.client import GoogleCredentials

# auth.authenticate_user()
# gauth = GoogleAuth()
# gauth.credentials = GoogleCredentials.get_application_default()
# drive = GoogleDrive(gauth)
PYTHON · 仅供阅读
# # the same way we get id from last class
# #https://drive.google.com/file/d/[FILE_ID]/view?usp=sharing
# id = "[FILE_ID]"
# file = drive.CreateFile({'id':id}) 
# file.GetContentFile('bank_churn.csv')
PYTHON · 仅供阅读
import pandas as pd

df = pd.read_csv('bank_churn.csv')
df.head()
原笔记输出 · 已脱敏 · 本次未执行
   RowNumber  CustomerId   Surname  CreditScore Geography  Gender  Age  \
0          1    [ID] [NAME]          619    France  Female   42   
1          2    [ID] [NAME]          608     Spain  Female   41   
2          3    [ID] [NAME]          502    France  Female   42   
3          4    [ID] [NAME]          699    France  Female   39   
4          5    [ID] [NAME]          850     Spain  Female   43   

   Tenure    Balance  NumOfProducts  HasCrCard  IsActiveMember  \
0       2       0.00              1          1               1   
1       1   83807.86              1          0               1   
2       8  159660.80              3          1               0   
3       1       0.00              2          0               0   
4       2  125510.82              1          1               1   

   EstimatedSalary  Exited  
0        101348.88       1  
1        112542.58       0  
2        113931.57       1  
3         93826.63       0  
4         79084.10       0

Part 1: Data Exploration

Part 1.1: Understand the Raw Dataset

PYTHON · 仅供阅读
import pandas as pd
import numpy as np

churn_df = pd.read_csv('bank_churn.csv')
PYTHON · 仅供阅读
churn_df.head()
原笔记输出 · 已脱敏 · 本次未执行
   RowNumber  CustomerId   Surname  CreditScore Geography  Gender  Age  \
0          1    [ID] [NAME]          619    France  Female   42   
1          2    [ID] [NAME]          608     Spain  Female   41   
2          3    [ID] [NAME]          502    France  Female   42   
3          4    [ID] [NAME]          699    France  Female   39   
4          5    [ID] [NAME]          850     Spain  Female   43   

   Tenure    Balance  NumOfProducts  HasCrCard  IsActiveMember  \
0       2       0.00              1          1               1   
1       1   83807.86              1          0               1   
2       8  159660.80              3          1               0   
3       1       0.00              2          0               0   
4       2  125510.82              1          1               1   

   EstimatedSalary  Exited  
0        101348.88       1  
1        112542.58       0  
2        113931.57       1  
3         93826.63       0  
4         79084.10       0
PYTHON · 仅供阅读
# check data info
churn_df.info()
原笔记输出 · 本次未执行
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10000 entries, 0 to 9999
Data columns (total 14 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   RowNumber        10000 non-null  int64  
 1   CustomerId       10000 non-null  int64  
 2   Surname          10000 non-null  object 
 3   CreditScore      10000 non-null  int64  
 4   Geography        10000 non-null  object 
 5   Gender           10000 non-null  object 
 6   Age              10000 non-null  int64  
 7   Tenure           10000 non-null  int64  
 8   Balance          10000 non-null  float64
 9   NumOfProducts    10000 non-null  int64  
 10  HasCrCard        10000 non-null  int64  
 11  IsActiveMember   10000 non-null  int64  
 12  EstimatedSalary  10000 non-null  float64
 13  Exited           10000 non-null  int64  
dtypes: float64(2), int64(9), object(3)
memory usage: 1.1+ MB
PYTHON · 仅供阅读
# check the unique values for each column
churn_df.nunique()
原笔记输出 · 本次未执行
RowNumber          10000
CustomerId         10000
Surname             2932
CreditScore          460
Geography              3
Gender                 2
Age                   70
Tenure                11
Balance             6382
NumOfProducts          4
HasCrCard              2
IsActiveMember         2
EstimatedSalary     9999
Exited                 2
dtype: int64
PYTHON · 仅供阅读
# Get target variable
y = churn_df['Exited']

Part 1.2: Understand the features

PYTHON · 仅供阅读
# check missing values
churn_df.isnull().sum()
原笔记输出 · 本次未执行
RowNumber          0
CustomerId         0
Surname            0
CreditScore        0
Geography          0
Gender             0
Age                0
Tenure             0
Balance            0
NumOfProducts      0
HasCrCard          0
IsActiveMember     0
EstimatedSalary    0
Exited             0
dtype: int64
PYTHON · 仅供阅读
# understand Numerical feature
# discrete/continuous
# 'CreditScore', 'Age', 'Tenure', 'NumberOfProducts'
# 'Balance', 'EstimatedSalary'
churn_df[['CreditScore', 'Age', 'Tenure', 'NumOfProducts','Balance', 'EstimatedSalary']].describe()
原笔记输出 · 本次未执行
        CreditScore           Age        Tenure  NumOfProducts        Balance  \
count  10000.000000  10000.000000  10000.000000   10000.000000   10000.000000   
mean     650.528800     38.921800      5.012800       1.530200   76485.889288   
std       96.653299     10.487806      2.892174       0.581654   62397.405202   
min      350.000000     18.000000      0.000000       1.000000       0.000000   
25%      584.000000     32.000000      3.000000       1.000000       0.000000   
50%      652.000000     37.000000      5.000000       1.000000   97198.540000   
75%      718.000000     44.000000      7.000000       2.000000  127644.240000   
max      850.000000     92.000000     10.000000       4.000000  250898.090000   

       EstimatedSalary  
count     10000.000000  
mean     100090.239881  
std       57510.492818  
min          11.580000  
25%       51002.110000  
50%      100193.915000  
75%      149388.247500  
max      199992.480000
PYTHON · 仅供阅读
# check the feature distribution
# pandas.DataFrame.describe()
# boxplot, distplot, countplot
import matplotlib.pyplot as plt
import seaborn as sns
PYTHON · 仅供阅读
# boxplot for numerical feature
_,axss = plt.subplots(2,3, figsize=[20,10])
sns.boxplot(x='Exited', y ='CreditScore', data=churn_df, ax=axss[0][0])
sns.boxplot(x='Exited', y ='Age', data=churn_df, ax=axss[0][1])
sns.boxplot(x='Exited', y ='Tenure', data=churn_df, ax=axss[0][2])
sns.boxplot(x='Exited', y ='NumOfProducts', data=churn_df, ax=axss[1][0])
sns.boxplot(x='Exited', y ='Balance', data=churn_df, ax=axss[1][1])
sns.boxplot(x='Exited', y ='EstimatedSalary', data=churn_df, ax=axss[1][2])
原笔记输出 · 本次未执行
<AxesSubplot:xlabel='Exited', ylabel='EstimatedSalary'>
原笔记输出 · 本次未执行
<Figure size 1440x720 with 6 Axes>

输出图整理: 箱线图用于比较流失与未流失组各数值特征的中位数、离散和异常。具体分位数不从像素臆测;完整原始describe表保留在前文。

PYTHON · 仅供阅读
# correlations between features
corr_score = churn_df[['CreditScore', 'Age', 'Tenure', 'NumOfProducts','Balance', 'EstimatedSalary']].corr()

# show heapmap of correlations
sns.heatmap(corr_score)
原笔记输出 · 本次未执行
<AxesSubplot:>
原笔记输出 · 本次未执行
<Figure size 432x288 with 2 Axes>

输出图整理: 相关性热图已由下一单元原始数值矩阵替代,矩阵对称且对角为1。颜色只是数值编码,不增加新的结论。

PYTHON · 仅供阅读
# check the actual values of correlations
corr_score
原笔记输出 · 本次未执行
                 CreditScore       Age    Tenure  NumOfProducts   Balance  \
CreditScore         1.000000 -0.003965  0.000842       0.012238  0.006268   
Age                -0.003965  1.000000 -0.009997      -0.030680  0.028308   
Tenure              0.000842 -0.009997  1.000000       0.013444 -0.012254   
NumOfProducts       0.012238 -0.030680  0.013444       1.000000 -0.304180   
Balance             0.006268  0.028308 -0.012254      -0.304180  1.000000   
EstimatedSalary    -0.001384 -0.007201  0.007784       0.014204  0.012797   

                 EstimatedSalary  
CreditScore            -0.001384  
Age                    -0.007201  
Tenure                  0.007784  
NumOfProducts           0.014204  
Balance                 0.012797  
EstimatedSalary         1.000000
PYTHON · 仅供阅读
# understand categorical feature
# 'Geography', 'Gender'
# 'HasCrCard', 'IsActiveMember'
_,axss = plt.subplots(2,2, figsize=[20,10])
sns.countplot(x='Exited', hue='Geography', data=churn_df, ax=axss[0][0])
sns.countplot(x='Exited', hue='Gender', data=churn_df, ax=axss[0][1])
sns.countplot(x='Exited', hue='HasCrCard', data=churn_df, ax=axss[1][0])
sns.countplot(x='Exited', hue='IsActiveMember', data=churn_df, ax=axss[1][1])
原笔记输出 · 本次未执行
<AxesSubplot:xlabel='Exited', ylabel='count'>
原笔记输出 · 本次未执行
<Figure size 1440x720 with 4 Axes>

输出图整理: 分类特征需比较各组数量及组内流失率;原计数图不能仅凭柱子高度证明某类更易流失。改用本说明保留分析目的,不捏造计数。

Part 2: Feature Preprocessing

PYTHON · 仅供阅读
# Get feature space by dropping useless feature
to_drop = ['RowNumber','CustomerId','Surname','Exited']
X = churn_df.drop(to_drop, axis=1)
PYTHON · 仅供阅读
X.head()
原笔记输出 · 本次未执行
   CreditScore Geography  Gender  Age  Tenure    Balance  NumOfProducts  \
0          619    France  Female   42       2       0.00              1   
1          608     Spain  Female   41       1   83807.86              1   
2          502    France  Female   42       8  159660.80              3   
3          699    France  Female   39       1       0.00              2   
4          850     Spain  Female   43       2  125510.82              1   

   HasCrCard  IsActiveMember  EstimatedSalary  
0          1               1        101348.88  
1          0               1        112542.58  
2          1               0        113931.57  
3          0               0         93826.63  
4          1               1         79084.10
PYTHON · 仅供阅读
X.dtypes
原笔记输出 · 本次未执行
CreditScore          int64
Geography           object
Gender              object
Age                  int64
Tenure               int64
Balance            float64
NumOfProducts        int64
HasCrCard            int64
IsActiveMember       int64
EstimatedSalary    float64
dtype: object
PYTHON · 仅供阅读
cat_cols = X.columns[X.dtypes == 'O']
num_cols = X.columns[(X.dtypes == 'float64') | (X.dtypes == 'int64')]
PYTHON · 仅供阅读
num_cols
原笔记输出 · 本次未执行
Index(['CreditScore', 'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
       'IsActiveMember', 'EstimatedSalary'],
      dtype='object')
PYTHON · 仅供阅读
cat_cols
原笔记输出 · 本次未执行
Index(['Geography', 'Gender'], dtype='object')

Split dataset

PYTHON · 仅供阅读
# Splite data into training and testing
# 100 -> 75:y=1, 25:y=0
# training(80): 60 y=1; 20 y=0 
# testing(20):  15 y=1; 5 y=0

from sklearn import model_selection

# Reserve 25% for testing
# stratify example:
# 100 -> y: 80 '0', 20 '1' -> 4:1
# 80% training 64: '0', 16:'1' -> 4:1
# 20% testing  16:'0', 4: '1' -> 4:1
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.25, stratify = y, random_state=1) #stratified sampling

print('training data has ' + str(X_train.shape[0]) + ' observation with ' + str(X_train.shape[1]) + ' features')
print('test data has ' + str(X_test.shape[0]) + ' observation with ' + str(X_test.shape[1]) + ' features')
原笔记输出 · 本次未执行
training data has 7500 observation with 10 features
test data has 2500 observation with 10 features
  • 10000 -> 8000 ‘0’ + 2000 ‘1’

  • 25% test 75% training


  • without stratified sampling:
    extreme case:
    1. testing: 2000 ‘1’ + 500 ‘0’
    2. training: 7500 ‘0’
  • with stratified sampling:
    1. testing: 2000 ‘0’ + 500 ‘1’
    2. training: 6000 ‘0’ + 1500 ‘1’

Read more for handling categorical feature, and there is an awesome package for encoding.

PYTHON · 仅供阅读
X_train.head()
原笔记输出 · 本次未执行
      CreditScore Geography  Gender  Age  Tenure   Balance  NumOfProducts  \
7971          633     Spain    Male   42      10      0.00              1   
9152          708   Germany  Female   23       4  71433.08              1   
6732          548    France  Female   37       9      0.00              2   
902           645    France  Female   48       7  90612.34              1   
2996          729     Spain  Female   45       7  91091.06              2   

      HasCrCard  IsActiveMember  EstimatedSalary  
7971          0               1         79408.17  
9152          1               0        103697.57  
6732          0               0         98029.58  
902           1               1        149139.13  
2996          1               0         71133.12
PYTHON · 仅供阅读
# One hot encoding
# another way: get_dummies
from sklearn.preprocessing import OneHotEncoder

def OneHotEncoding(df, enc, categories):  
    transformed = pd.DataFrame(enc.transform(df[categories]).toarray(), columns=enc.get_feature_names(categories))
    return pd.concat([df.reset_index(drop=True), transformed], axis=1).drop(categories, axis=1)

categories = ['Geography']
enc_ohe = OneHotEncoder()
enc_ohe.fit(X_train[categories])

X_train = OneHotEncoding(X_train, enc_ohe, categories)
X_test = OneHotEncoding(X_test, enc_ohe, categories)

整理注: 原环境使用旧scikit-learn接口;新版对应get_feature_names_out。这里保留旧接口以配合历史输出,不承诺在最新版直接运行。

PYTHON · 仅供阅读
X_train.head()
原笔记输出 · 本次未执行
   CreditScore  Gender  Age  Tenure   Balance  NumOfProducts  HasCrCard  \
0          633    Male   42      10      0.00              1          0   
1          708  Female   23       4  71433.08              1          1   
2          548  Female   37       9      0.00              2          0   
3          645  Female   48       7  90612.34              1          1   
4          729  Female   45       7  91091.06              2          1   

   IsActiveMember  EstimatedSalary  Geography_France  Geography_Germany  \
0               1         79408.17               0.0                0.0   
1               0        103697.57               0.0                1.0   
2               0         98029.58               1.0                0.0   
3               1        149139.13               1.0                0.0   
4               0         71133.12               0.0                0.0   

   Geography_Spain  
0              1.0  
1              0.0  
2              0.0  
3              0.0  
4              1.0
PYTHON · 仅供阅读
# Ordinal encoding
from sklearn.preprocessing import OrdinalEncoder

categories = ['Gender']
enc_oe = OrdinalEncoder()
enc_oe.fit(X_train[categories])

X_train[categories] = enc_oe.transform(X_train[categories])
X_test[categories] = enc_oe.transform(X_test[categories])
PYTHON · 仅供阅读
X_train.head()
原笔记输出 · 本次未执行
   CreditScore  Gender  Age  Tenure   Balance  NumOfProducts  HasCrCard  \
0          633     1.0   42      10      0.00              1          0   
1          708     0.0   23       4  71433.08              1          1   
2          548     0.0   37       9      0.00              2          0   
3          645     0.0   48       7  90612.34              1          1   
4          729     0.0   45       7  91091.06              2          1   

   IsActiveMember  EstimatedSalary  Geography_France  Geography_Germany  \
0               1         79408.17               0.0                0.0   
1               0        103697.57               0.0                1.0   
2               0         98029.58               1.0                0.0   
3               1        149139.13               1.0                0.0   
4               0         71133.12               0.0                0.0   

   Geography_Spain  
0              1.0  
1              0.0  
2              0.0  
3              0.0  
4              1.0

Standardize/Normalize Data

PYTHON · 仅供阅读
# Scale the data, using standardization
# standardization (x-mean)/std
# normalization (x-x_min)/(x_max-x_min) ->[0,1]

# 1. speed up gradient descent
# 2. same scale
# 3. algorithm requirments

# for example, use training data to train the standardscaler to get mean and std 
# apply mean and std to both training and testing data.
# fit_transform does the training and applying, transform only does applying.
# Because we can't use any info from test, and we need to do the same modification
# to testing data as well as training data

# https://scikit-learn.org/stable/auto_examples/preprocessing/plot_all_scaling.html#sphx-glr-auto-examples-preprocessing-plot-all-scaling-py
# https://scikit-learn.org/stable/modules/preprocessing.html


# min-max example: (x-x_min)/(x_max-x_min)
# [1,2,3,4,5,6,100] -> fit(min:1, max:6) (scalar.min = 1, scalar.max = 6) -> transform [(1-1)/(6-1),(2-1)/(6-1)..]
# scalar.fit(train) -> min:1, max:100
# scalar.transform(apply to x) -> apply min:1, max:100 to X_train
# scalar.transform -> apply min:1, max:100 to X_test

# scalar.fit -> mean:1, std:100
# scalar.transform -> apply mean:1, std:100 to X_train
# scalar.transform -> apply mean:1, std:100 to X_test

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train[num_cols])
X_train[num_cols] = scaler.transform(X_train[num_cols])
X_test[num_cols] = scaler.transform(X_test[num_cols])
PYTHON · 仅供阅读
X_train.head()
原笔记输出 · 本次未执行
   CreditScore  Gender       Age    Tenure   Balance  NumOfProducts  \
0    -0.172985     1.0  0.289202  1.731199 -1.218916      -0.912769   
1     0.602407     0.0 -1.509319 -0.341156 -0.076977      -0.912769   
2    -1.051762     0.0 -0.184093  1.385806 -1.218916       0.796109   
3    -0.048922     0.0  0.857156  0.695022  0.229625      -0.912769   
4     0.819517     0.0  0.573179  0.695022  0.237278       0.796109   

   HasCrCard  IsActiveMember  EstimatedSalary  Geography_France  \
0  -1.542199        0.968496        -0.352044               0.0   
1   0.648425       -1.032529         0.072315               0.0   
2  -1.542199       -1.032529        -0.026711               1.0   
3   0.648425        0.968496         0.866221               1.0   
4   0.648425       -1.032529        -0.496617               0.0   

   Geography_Germany  Geography_Spain  
0                0.0              1.0  
1                1.0              0.0  
2                0.0              0.0  
3                0.0              0.0  
4                0.0              1.0

Part 3: Model Training and Result Evaluation

Part 3.1: Model Training

PYTHON · 仅供阅读
#@title build models
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier 
from sklearn.linear_model import LogisticRegression

# Logistic Regression
classifier_logistic = LogisticRegression()

# K Nearest Neighbors
classifier_KNN = KNeighborsClassifier()

# Random Forest
classifier_RF = RandomForestClassifier()
PYTHON · 仅供阅读
# Train the model
classifier_logistic.fit(X_train, y_train)
原笔记输出 · 本次未执行
LogisticRegression()
PYTHON · 仅供阅读
# Prediction of test data
classifier_logistic.predict(X_test)
原笔记输出 · 本次未执行
array([0, 0, 0, ..., 0, 0, 0], dtype=int64)
PYTHON · 仅供阅读
# Accuracy of test data
classifier_logistic.score(X_test, y_test)
原笔记输出 · 本次未执行
0.8088
PYTHON · 仅供阅读
# Use 5-fold Cross Validation to get the accuracy for different models
model_names = ['Logistic Regression','KNN','Random Forest']
model_list = [classifier_logistic, classifier_KNN, classifier_RF]
count = 0

for classifier in model_list:
    cv_score = model_selection.cross_val_score(classifier, X_train, y_train, cv=5)
    print(cv_score)
    print('Model accuracy of ' + model_names[count] + ' is ' + str(cv_score.mean()))
    count += 1
原笔记输出 · 本次未执行
[0.81933333 0.80666667 0.80666667 0.80933333 0.82      ]
Model accuracy of Logistic Regression is 0.8124
[0.84133333 0.84066667 0.83       0.83066667 0.84      ]
Model accuracy of KNN is 0.8365333333333334
[0.878      0.86066667 0.852      0.85866667 0.868     ]
Model accuracy of Random Forest is 0.8634666666666666

整理注: 原流程在全体训练集上预处理后再交叉验证,会让验证折信息进入缩放等步骤。正式评估应使用Pipeline,在每个训练折内拟合预处理,并仅在最终评估使用测试集。保留这些历史分数,不把它们当作无泄漏的性能证明。

(Optional) Part 3.2: Use Grid Search to Find Optimal Hyperparameters

alternative: random search

PYTHON · 仅供阅读
#Loss/cost function --> (wx + b - y) ^2 + ƛ * |w| --> ƛ is a hyperparameter
PYTHON · 仅供阅读
from sklearn.model_selection import GridSearchCV

# helper function for printing out grid search results 
def print_grid_search_metrics(gs):
    print ("Best score: " + str(gs.best_score_))
    print ("Best parameters set:")
    best_parameters = gs.best_params_
    for param_name in sorted(best_parameters.keys()):
        print(param_name + ':' + str(best_parameters[param_name]))

Part 3.2.1: Find Optimal Hyperparameters - LogisticRegression

PYTHON · 仅供阅读
# Possible hyperparamter options for Logistic Regression Regularization
# Penalty is choosed from L1 or L2
# C is the 1/lambda value(weight) for L1 and L2
# solver: algorithm to find the weights that minimize the cost function

# ('l1', 0.01)('l1', 0.05) ('l1', 0.1) ('l1', 0.2)('l1', 1)
# ('12', 0.01)('l2', 0.05) ('l2', 0.1) ('l2', 0.2)('l2', 1)
parameters = {
    'penalty':('l1', 'l2'), 
    'C':(0.01, 0.05, 0.1, 0.2, 1)  # C=1/lambada 
}
Grid_LR = GridSearchCV(LogisticRegression(solver='liblinear'),parameters, cv=5)
Grid_LR.fit(X_train, y_train)
原笔记输出 · 本次未执行
GridSearchCV(cv=5, estimator=LogisticRegression(solver='liblinear'),
             param_grid={'C': (0.01, 0.05, 0.1, 0.2, 1),
                         'penalty': ('l1', 'l2')})
PYTHON · 仅供阅读
# the best hyperparameter combination
# C = 1/lambda
print_grid_search_metrics(Grid_LR)
原笔记输出 · 本次未执行
Best score: 0.8125333333333333
Best parameters set:
C:1
penalty:l1
PYTHON · 仅供阅读
# best model
best_LR_model = Grid_LR.best_estimator_
PYTHON · 仅供阅读
best_LR_model.predict(X_test)
原笔记输出 · 本次未执行
array([0, 0, 0, ..., 0, 0, 0], dtype=int64)
PYTHON · 仅供阅读
best_LR_model.score(X_test, y_test)
原笔记输出 · 本次未执行
0.8092
PYTHON · 仅供阅读
LR_models = pd.DataFrame(Grid_LR.cv_results_)
PYTHON · 仅供阅读
res = (LR_models.pivot(index='param_penalty', columns='param_C', values='mean_test_score'))
PYTHON · 仅供阅读
_ = sns.heatmap(res, cmap='viridis')
原笔记输出 · 本次未执行
<Figure size 432x288 with 2 Axes>

输出图整理: 参数网格按C与penalty排列、颜色为交叉验证均分;最优参数与分数已由前文原输出直接给出,不重建未知网格单元。

Part 3.2.2: Find Optimal Hyperparameters: KNN

PYTHON · 仅供阅读
# Possible hyperparamter options for KNN
# Choose k
parameters = {
    'n_neighbors':[1,3,5,7,9]
}
Grid_KNN = GridSearchCV(KNeighborsClassifier(),parameters, cv=5)
Grid_KNN.fit(X_train, y_train)
原笔记输出 · 本次未执行
GridSearchCV(cv=5, estimator=KNeighborsClassifier(),
             param_grid={'n_neighbors': [1, 3, 5, 7, 9]})
PYTHON · 仅供阅读
# best k
print_grid_search_metrics(Grid_KNN)
原笔记输出 · 本次未执行
Best score: 0.8433333333333334
Best parameters set:
n_neighbors:9
PYTHON · 仅供阅读
best_KNN_model = Grid_KNN.best_estimator_

Part 3.2.3: Find Optimal Hyperparameters: Random Forest

PYTHON · 仅供阅读
# Possible hyperparamter options for Random Forest
# Choose the number of trees
parameters = {
    'n_estimators' : [60,80,100],
    'max_depth': [1,5,10]
}
Grid_RF = GridSearchCV(RandomForestClassifier(),parameters, cv=5)
Grid_RF.fit(X_train, y_train)
原笔记输出 · 本次未执行
GridSearchCV(cv=5, estimator=RandomForestClassifier(),
             param_grid={'max_depth': [1, 5, 10],
                         'n_estimators': [60, 80, 100]})
PYTHON · 仅供阅读
# best number of tress
print_grid_search_metrics(Grid_RF)
原笔记输出 · 本次未执行
Best score: 0.8652000000000001
Best parameters set:
max_depth:10
n_estimators:100
PYTHON · 仅供阅读
# best random forest
best_RF_model = Grid_RF.best_estimator_
PYTHON · 仅供阅读
best_RF_model
原笔记输出 · 本次未执行
RandomForestClassifier(max_depth=10)

Part 3.3: Model Evaluation - Confusion Matrix (Precision, Recall, Accuracy)

class of interest as positive

TP: correctly labeled real churn

Precision(PPV, positive predictive value): tp / (tp + fp); Total number of true predictive churn divided by the total number of predictive churn; High Precision means low fp, not many return users were predicted as churn users.

Recall(sensitivity, hit rate, true positive rate): tp / (tp + fn) Predict most postive or churn user correctly. High recall means low fn, not many churn users were predicted as return users.

PYTHON · 仅供阅读
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score

# calculate accuracy, precision and recall, [[tn, fp],[]]
def cal_evaluation(classifier, cm):
    tn = cm[0][0]
    fp = cm[0][1]
    fn = cm[1][0]
    tp = cm[1][1]
    accuracy  = (tp + tn) / (tp + fp + fn + tn + 0.0)
    precision = tp / (tp + fp + 0.0)
    recall = tp / (tp + fn + 0.0)
    print (classifier)
    print ("Accuracy is: " + str(accuracy))
    print ("precision is: " + str(precision))
    print ("recall is: " + str(recall))
    print ()

# print out confusion matrices
def draw_confusion_matrices(confusion_matricies):
    class_names = ['Not','Churn']
    for cm in confusion_matricies:
        classifier, cm = cm[0], cm[1]
        cal_evaluation(classifier, cm)
PYTHON · 仅供阅读
# Confusion matrix, accuracy, precison and recall for random forest and logistic regression
confusion_matrices = [
    ("Random Forest", confusion_matrix(y_test, best_RF_model.predict(X_test))),
    ("Logistic Regression", confusion_matrix(y_test, best_LR_model.predict(X_test))),
    ("K nearest neighbor", confusion_matrix(y_test, best_KNN_model.predict(X_test)))
]

draw_confusion_matrices(confusion_matrices)
原笔记输出 · 本次未执行
Random Forest
Accuracy is: 0.8604
precision is: 0.8007518796992481
recall is: 0.41846758349705304

Logistic Regression
Accuracy is: 0.8092
precision is: 0.5963855421686747
recall is: 0.1944990176817289

K nearest neighbor
Accuracy is: 0.8428
precision is: 0.7283464566929134
recall is: 0.36345776031434185

Part 3.4: Model Evaluation - ROC & AUC

RandomForestClassifier, KNeighborsClassifier and LogisticRegression have predict_proba() function

Part 3.4.1: ROC of RF Model

PYTHON · 仅供阅读
from sklearn.metrics import roc_curve
from sklearn import metrics

# Use predict_proba to get the probability results of Random Forest
y_pred_rf = best_RF_model.predict_proba(X_test)[:, 1]
fpr_rf, tpr_rf, _ = roc_curve(y_test, y_pred_rf)
PYTHON · 仅供阅读
best_RF_model.predict_proba(X_test)
原笔记输出 · 本次未执行
array([[0.72334455, 0.27665545],
       [0.94044979, 0.05955021],
       [0.71299029, 0.28700971],
       ...,
       [0.85805324, 0.14194676],
       [0.93865888, 0.06134112],
       [0.92207141, 0.07792859]])
PYTHON · 仅供阅读
# ROC curve of Random Forest result
import matplotlib.pyplot as plt
plt.figure(1)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_rf, tpr_rf, label='RF')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve - RF model')
plt.legend(loc='best')
plt.show()
原笔记输出 · 本次未执行
<Figure size 432x288 with 1 Axes>

输出图整理: ROC横轴FPR、纵轴TPR,RF历史AUC为下一单元的0.8498015。保留标量原结果与坐标含义,不用猜测点拼成伪实验曲线。

PYTHON · 仅供阅读
from sklearn import metrics

# AUC score
metrics.auc(fpr_rf,tpr_rf)
原笔记输出 · 本次未执行
0.8498015134904714

Part 3.4.2: ROC of LR Model

PYTHON · 仅供阅读
# Use predict_proba to get the probability results of Logistic Regression
y_pred_lr = best_LR_model.predict_proba(X_test)[:, 1]
fpr_lr, tpr_lr, thresh = roc_curve(y_test, y_pred_lr)
PYTHON · 仅供阅读
best_LR_model.predict_proba(X_test)
原笔记输出 · 本次未执行
array([[0.82436956, 0.17563044],
       [0.93171861, 0.06828139],
       [0.85520979, 0.14479021],
       ...,
       [0.7145062 , 0.2854938 ],
       [0.89279134, 0.10720866],
       [0.85561176, 0.14438824]])
PYTHON · 仅供阅读
# ROC Curve
plt.figure(1)
plt.plot([0, 1], [0, 1], 'k--')
plt.plot(fpr_lr, tpr_lr, label='LR')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('ROC curve - LR Model')
plt.legend(loc='best')
plt.show()
原笔记输出 · 本次未执行
<Figure size 432x288 with 1 Axes>

输出图整理: LR历史ROC的AUC为0.7721999,坐标定义同前。原采样点未保存在文本中,因此以指标与方法解释替换,不伪造重现。

PYTHON · 仅供阅读
# AUC score
metrics.auc(fpr_lr,tpr_lr)
原笔记输出 · 本次未执行
0.7721998502100316

Part 4: Model Extra Functionality

Part 4.1: Logistic Regression Model

The corelated features that we are interested in

PYTHON · 仅供阅读
X_with_corr = X.copy()

X_with_corr = OneHotEncoding(X_with_corr, enc_ohe, ['Geography'])
X_with_corr['Gender'] = enc_oe.transform(X_with_corr[['Gender']])
X_with_corr['SalaryInRMB'] = X_with_corr['EstimatedSalary'] * 6.4
X_with_corr.head()
原笔记输出 · 本次未执行
   CreditScore  Gender  Age  Tenure    Balance  NumOfProducts  HasCrCard  \
0          619     0.0   42       2       0.00              1          1   
1          608     0.0   41       1   83807.86              1          0   
2          502     0.0   42       8  159660.80              3          1   
3          699     0.0   39       1       0.00              2          0   
4          850     0.0   43       2  125510.82              1          1   

   IsActiveMember  EstimatedSalary  Geography_France  Geography_Germany  \
0               1        101348.88               1.0                0.0   
1               1        112542.58               0.0                0.0   
2               0        113931.57               1.0                0.0   
3               0         93826.63               1.0                0.0   
4               1         79084.10               0.0                0.0   

   Geography_Spain  SalaryInRMB  
0              0.0   648632.832  
1              1.0   720272.512  
2              0.0   729162.048  
3              0.0   600490.432  
4              1.0   506138.240
PYTHON · 仅供阅读
# add L1 regularization to logistic regression
# check the coef for feature selection
scaler = StandardScaler()
X_l1 = scaler.fit_transform(X_with_corr)
LRmodel_l1 = LogisticRegression(penalty="l1", C = 0.04, solver='liblinear')
LRmodel_l1.fit(X_l1, y)

indices = np.argsort(abs(LRmodel_l1.coef_[0]))[::-1]

print ("Logistic Regression (L1) Coefficients")
for ind in range(X_with_corr.shape[1]):
    print ("{0} : {1}".format(X_with_corr.columns[indices[ind]],round(LRmodel_l1.coef_[0][indices[ind]], 4)))
原笔记输出 · 本次未执行
Logistic Regression (L1) Coefficients
Age : 0.7307
IsActiveMember : -0.5046
Geography_Germany : 0.312
Gender : -0.2409
Balance : 0.1509
CreditScore : -0.0457
NumOfProducts : -0.0439
Tenure : -0.0271
EstimatedSalary : 0.0091
Geography_France : -0.0043
HasCrCard : -0.0022
SalaryInRMB : 0.0001
Geography_Spain : 0.0
PYTHON · 仅供阅读
# add L2 regularization to logistic regression
# check the coef for feature selection
np.random.seed()
scaler = StandardScaler()
X_l2 = scaler.fit_transform(X_with_corr)
LRmodel_l2 = LogisticRegression(penalty="l2", C = 0.1, solver='liblinear', random_state=42)
LRmodel_l2.fit(X_l2, y)
LRmodel_l2.coef_[0]

indices = np.argsort(abs(LRmodel_l2.coef_[0]))[::-1]

print ("Logistic Regression (L2) Coefficients")
for ind in range(X_with_corr.shape[1]):
    print ("{0} : {1}".format(X_with_corr.columns[indices[ind]],round(LRmodel_l2.coef_[0][indices[ind]], 4)))
原笔记输出 · 本次未执行
Logistic Regression (L2) Coefficients
Age : 0.751
IsActiveMember : -0.5272
Gender : -0.2591
Geography_Germany : 0.2279
Balance : 0.162
Geography_France : -0.1207
Geography_Spain : -0.089
CreditScore : -0.0637
NumOfProducts : -0.0586
Tenure : -0.0452
HasCrCard : -0.0199
SalaryInRMB : 0.0137
EstimatedSalary : 0.0137

Part 4.2: Random Forest Model - Feature Importance Discussion

PYTHON · 仅供阅读
X_RF = X.copy()

X_RF = OneHotEncoding(X_RF, enc_ohe, ['Geography'])
X_RF['Gender'] = enc_oe.transform(X_RF[['Gender']])

X_RF.head()
原笔记输出 · 本次未执行
   CreditScore  Gender  Age  Tenure    Balance  NumOfProducts  HasCrCard  \
0          619     0.0   42       2       0.00              1          1   
1          608     0.0   41       1   83807.86              1          0   
2          502     0.0   42       8  159660.80              3          1   
3          699     0.0   39       1       0.00              2          0   
4          850     0.0   43       2  125510.82              1          1   

   IsActiveMember  EstimatedSalary  Geography_France  Geography_Germany  \
0               1        101348.88               1.0                0.0   
1               1        112542.58               0.0                0.0   
2               0        113931.57               1.0                0.0   
3               0         93826.63               1.0                0.0   
4               1         79084.10               0.0                0.0   

   Geography_Spain  
0              0.0  
1              1.0  
2              0.0  
3              0.0  
4              1.0
PYTHON · 仅供阅读
# check feature importance of random forest for feature selection
forest = RandomForestClassifier()
forest.fit(X_RF, y)

importances = forest.feature_importances_

indices = np.argsort(importances)[::-1]

# Print the feature ranking
print("Feature importance ranking by Random Forest Model:")
for ind in range(X.shape[1]):
    print ("{0} : {1}".format(X_RF.columns[indices[ind]],round(importances[indices[ind]], 4)))
原笔记输出 · 本次未执行
Feature importance ranking by Random Forest Model:
Age : 0.2358
EstimatedSalary : 0.1477
CreditScore : 0.1423
Balance : 0.1416
NumOfProducts : 0.1312
Tenure : 0.0835
IsActiveMember : 0.0427
Geography_Germany : 0.0203
Gender : 0.0183
HasCrCard : 0.0183

整理注: 原循环只打印X的列数,但X_RF独热编码后有更多列;应按X_RF.shape[1]打印完整排名。这里保留历史节选,不凭空补新分数。

整理参考资料