Projet : Modelisation du risque de crédit

Author

Alfousseyni

Ensembe de données sur le risque de crédit

Cet ensemble de données contient des colonnes simulant les données d’une agence d’évaluation du crédit.

Objectif du projet

La problematique metier est de prédire le statut de prêt d’un client pendant l’octroi d’un crédit en fonction d’autres variables d’évaluation de crédit comme par exemple : l’historique de defaut de prêt d’un client ou encore son revenu annuel.

Choix de l’environnement de travail

setwd("C:/Users/Ideapad/Desktop/Valdom/Projet personnel Machine Learning/ML Risk Credit Modeling")

Importation des librairies necessaires à l’exploration des données et à la modélisation

library(tidyverse)
Warning: le package 'ggplot2' a été compilé avec la version R 4.3.3
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tidymodels)
Warning: le package 'tidymodels' a été compilé avec la version R 4.3.3
── Attaching packages ────────────────────────────────────── tidymodels 1.2.0 ──
✔ broom        1.0.5      ✔ rsample      1.2.1 
✔ dials        1.2.1      ✔ tune         1.2.1 
✔ infer        1.0.7      ✔ workflows    1.1.4 
✔ modeldata    1.3.0      ✔ workflowsets 1.1.0 
✔ parsnip      1.2.1      ✔ yardstick    1.3.1 
✔ recipes      1.0.10     
Warning: le package 'broom' a été compilé avec la version R 4.3.3
Warning: le package 'dials' a été compilé avec la version R 4.3.3
Warning: le package 'infer' a été compilé avec la version R 4.3.3
Warning: le package 'modeldata' a été compilé avec la version R 4.3.3
Warning: le package 'parsnip' a été compilé avec la version R 4.3.3
Warning: le package 'rsample' a été compilé avec la version R 4.3.3
Warning: le package 'tune' a été compilé avec la version R 4.3.3
Warning: le package 'workflows' a été compilé avec la version R 4.3.3
Warning: le package 'workflowsets' a été compilé avec la version R 4.3.3
Warning: le package 'yardstick' a été compilé avec la version R 4.3.3
── Conflicts ───────────────────────────────────────── tidymodels_conflicts() ──
✖ scales::discard() masks purrr::discard()
✖ dplyr::filter()   masks stats::filter()
✖ recipes::fixed()  masks stringr::fixed()
✖ dplyr::lag()      masks stats::lag()
✖ yardstick::spec() masks readr::spec()
✖ recipes::step()   masks stats::step()
• Use tidymodels_prefer() to resolve common conflicts.
library(nnet)
library(randomForest)
Warning: le package 'randomForest' a été compilé avec la version R 4.3.3
randomForest 4.7-1.1
Type rfNews() to see new features/changes/bug fixes.

Attachement du package : 'randomForest'

L'objet suivant est masqué depuis 'package:dplyr':

    combine

L'objet suivant est masqué depuis 'package:ggplot2':

    margin
library(ranger)
Warning: le package 'ranger' a été compilé avec la version R 4.3.3

Attachement du package : 'ranger'

L'objet suivant est masqué depuis 'package:randomForest':

    importance
library(xgboost)
Warning: le package 'xgboost' a été compilé avec la version R 4.3.3

Attachement du package : 'xgboost'

L'objet suivant est masqué depuis 'package:dplyr':

    slice
library(kknn)
Warning: le package 'kknn' a été compilé avec la version R 4.3.3
library(doParallel)
Warning: le package 'doParallel' a été compilé avec la version R 4.3.3
Le chargement a nécessité le package : foreach

Attachement du package : 'foreach'

Les objets suivants sont masqués depuis 'package:purrr':

    accumulate, when

Le chargement a nécessité le package : iterators
Le chargement a nécessité le package : parallel
library(DataExplorer)
Warning: le package 'DataExplorer' a été compilé avec la version R 4.3.3
library(vip)
Warning: le package 'vip' a été compilé avec la version R 4.3.3

Attachement du package : 'vip'

L'objet suivant est masqué depuis 'package:utils':

    vi

Importation des données

data=utils::read.csv("credit_risk_dataset.csv",header = T, sep = ",")
head(data,20)
   person_age person_income person_home_ownership person_emp_length
1          22         59000                  RENT               123
2          21          9600                   OWN                 5
3          25          9600              MORTGAGE                 1
4          23         65500                  RENT                 4
5          24         54400                  RENT                 8
6          21          9900                   OWN                 2
7          26         77100                  RENT                 8
8          24         78956                  RENT                 5
9          24         83000                  RENT                 8
10         21         10000                   OWN                 6
11         22         85000                  RENT                 6
12         21         10000                   OWN                 2
13         23         95000                  RENT                 2
14         26        108160                  RENT                 4
15         23        115000                  RENT                 2
16         23        500000              MORTGAGE                 7
17         23        120000                  RENT                 0
18         23         92111                  RENT                 7
19         23        113000                  RENT                 8
20         24         10800              MORTGAGE                 8
         loan_intent loan_grade loan_amnt loan_int_rate loan_status
1           PERSONAL          D     35000         16.02           1
2          EDUCATION          B      1000         11.14           0
3            MEDICAL          C      5500         12.87           1
4            MEDICAL          C     35000         15.23           1
5            MEDICAL          C     35000         14.27           1
6            VENTURE          A      2500          7.14           1
7          EDUCATION          B     35000         12.42           1
8            MEDICAL          B     35000         11.11           1
9           PERSONAL          A     35000          8.90           1
10           VENTURE          D      1600         14.74           1
11           VENTURE          B     35000         10.37           1
12   HOMEIMPROVEMENT          A      4500          8.63           1
13           VENTURE          A     35000          7.90           1
14         EDUCATION          E     35000         18.39           1
15         EDUCATION          A     35000          7.90           0
16 DEBTCONSOLIDATION          B     30000         10.65           0
17         EDUCATION          A     35000          7.90           0
18           MEDICAL          F     35000         20.25           1
19 DEBTCONSOLIDATION          D     35000         18.25           1
20         EDUCATION          B      1750         10.99           1
   loan_percent_income cb_person_default_on_file cb_person_cred_hist_length
1                 0.59                         Y                          3
2                 0.10                         N                          2
3                 0.57                         N                          3
4                 0.53                         N                          2
5                 0.55                         Y                          4
6                 0.25                         N                          2
7                 0.45                         N                          3
8                 0.44                         N                          4
9                 0.42                         N                          2
10                0.16                         N                          3
11                0.41                         N                          4
12                0.45                         N                          2
13                0.37                         N                          2
14                0.32                         N                          4
15                0.30                         N                          4
16                0.06                         N                          3
17                0.29                         N                          4
18                0.32                         N                          4
19                0.31                         N                          4
20                0.16                         N                          2

Manipulation des données

## Manipulation des données

# Renommer les variables 
DataRisk=data%>%dplyr::renamege=person_age, Revenu_annuel = person_income, Statut_propriétaire_logement=person_home_ownership,Durée_d_emploi=person_emp_length ,Motif_du_prêt=loan_intent, Câtegorie_du_prêt=loan_grade ,Montant_du_prêt=loan_amnt,Taux_d_intérêt=loan_int_rate, Eligibilité_au_credit=loan_status , Pourcentage_de_revenu=loan_percent_income, Decouvert_bancaire_demandeur_credit=cb_person_default_on_file, Echeance_credit_en_cours=cb_person_cred_hist_length)

# Recoder les variables categorielles
DataRisk=DataRisk%>%dplyr::mutate(`Statut_propriétaire_logement`=recode(`Statut_propriétaire_logement`, MORTGAGE="Hypothèque", OTHER="Autres cas", OWN="Proprietaire",RENT="Location"), `Motif_du_prêt`=recode(`Motif_du_prêt`, PERSONAL="Besoin personnel", EDUCATION="Scolarité", MEDICAL="Médical", VENTURE="Business", DEBTCONSOLIDATION="Rachat de credit",HOMEIMPROVEMENT="Travaux de renovation de la maison"),`Decouvert_bancaire_demandeur_credit`=recode(`Decouvert_bancaire_demandeur_credit`, Y="Oui", N="Non"),Eligibilité_au_credit=recode(Eligibilité_au_credit, "0"="Eligible au credit","1"="Non Eligible au credit"))

# Factoriser toutes les variables qualitatives: changer les character en factor       
DataRisk=DataRisk%>%dplyr::mutate_if(is.character,as.factor)

# Changer la position de la variable statut_du_prêt
DataRisk=DataRisk%>%dplyr::relocate(`Eligibilité_au_credit`,.after = `Echeance_credit_en_cours`)

#anyNA.data.frame(DataRisk)# il y a t il au moins une valeur manquante ?
summary(DataRisk) # Statistique descriptive sur les données
      Âge         Revenu_annuel     Statut_propriétaire_logement
 Min.   : 20.00   Min.   :   4000   Autres cas  :  107          
 1st Qu.: 23.00   1st Qu.:  38500   Hypothèque  :13444          
 Median : 26.00   Median :  55000   Location    :16446          
 Mean   : 27.73   Mean   :  66075   Proprietaire: 2584          
 3rd Qu.: 30.00   3rd Qu.:  79200                               
 Max.   :144.00   Max.   :6000000                               
                                                                
 Durée_d_emploi                              Motif_du_prêt  Câtegorie_du_prêt
 Min.   :  0.00   Besoin personnel                  :5521   A:10777          
 1st Qu.:  2.00   Business                          :5719   B:10451          
 Median :  4.00   Médical                           :6071   C: 6458          
 Mean   :  4.79   Rachat de credit                  :5212   D: 3626          
 3rd Qu.:  7.00   Scolarité                         :6453   E:  964          
 Max.   :123.00   Travaux de renovation de la maison:3605   F:  241          
 NA's   :895                                                G:   64          
 Montant_du_prêt Taux_d_intérêt  Pourcentage_de_revenu
 Min.   :  500   Min.   : 5.42   Min.   :0.0000       
 1st Qu.: 5000   1st Qu.: 7.90   1st Qu.:0.0900       
 Median : 8000   Median :10.99   Median :0.1500       
 Mean   : 9589   Mean   :11.01   Mean   :0.1702       
 3rd Qu.:12200   3rd Qu.:13.47   3rd Qu.:0.2300       
 Max.   :35000   Max.   :23.22   Max.   :0.8300       
                 NA's   :3116                         
 Decouvert_bancaire_demandeur_credit Echeance_credit_en_cours
 Non:26836                           Min.   : 2.000          
 Oui: 5745                           1st Qu.: 3.000          
                                     Median : 4.000          
                                     Mean   : 5.804          
                                     3rd Qu.: 8.000          
                                     Max.   :30.000          
                                                             
            Eligibilité_au_credit
 Eligible au credit    :25473    
 Non Eligible au credit: 7108    
                                 
                                 
                                 
                                 
                                 
head(DataRisk,10)# Afficher les premières observations
   Âge Revenu_annuel Statut_propriétaire_logement Durée_d_emploi
1   22         59000                     Location            123
2   21          9600                 Proprietaire              5
3   25          9600                   Hypothèque              1
4   23         65500                     Location              4
5   24         54400                     Location              8
6   21          9900                 Proprietaire              2
7   26         77100                     Location              8
8   24         78956                     Location              5
9   24         83000                     Location              8
10  21         10000                 Proprietaire              6
      Motif_du_prêt Câtegorie_du_prêt Montant_du_prêt Taux_d_intérêt
1  Besoin personnel                 D           35000          16.02
2         Scolarité                 B            1000          11.14
3           Médical                 C            5500          12.87
4           Médical                 C           35000          15.23
5           Médical                 C           35000          14.27
6          Business                 A            2500           7.14
7         Scolarité                 B           35000          12.42
8           Médical                 B           35000          11.11
9  Besoin personnel                 A           35000           8.90
10         Business                 D            1600          14.74
   Pourcentage_de_revenu Decouvert_bancaire_demandeur_credit
1                   0.59                                 Oui
2                   0.10                                 Non
3                   0.57                                 Non
4                   0.53                                 Non
5                   0.55                                 Oui
6                   0.25                                 Non
7                   0.45                                 Non
8                   0.44                                 Non
9                   0.42                                 Non
10                  0.16                                 Non
   Echeance_credit_en_cours  Eligibilité_au_credit
1                         3 Non Eligible au credit
2                         2     Eligible au credit
3                         3 Non Eligible au credit
4                         2 Non Eligible au credit
5                         4 Non Eligible au credit
6                         2 Non Eligible au credit
7                         3 Non Eligible au credit
8                         4 Non Eligible au credit
9                         2 Non Eligible au credit
10                        3 Non Eligible au credit

Analyse Exploratoire de Données avec le package DataExplorer

Analyse exploratoire de la structure des données

introduce(DataRisk)
   rows columns discrete_columns continuous_columns all_missing_columns
1 32581      12                5                  7                   0
  total_missing_values complete_rows total_observations memory_usage
1                 4011         28638             390972      1962096
plot_intro(DataRisk)

plot_str(DataRisk)

Analyse exploratoire des données manquantes

plot_missing(DataRisk)

profile_missing(DataRisk)
                               feature num_missing pct_missing
1                                  Âge           0  0.00000000
2                        Revenu_annuel           0  0.00000000
3         Statut_propriétaire_logement           0  0.00000000
4                       Durée_d_emploi         895  0.02747000
5                        Motif_du_prêt           0  0.00000000
6                    Câtegorie_du_prêt           0  0.00000000
7                      Montant_du_prêt           0  0.00000000
8                       Taux_d_intérêt        3116  0.09563856
9                Pourcentage_de_revenu           0  0.00000000
10 Decouvert_bancaire_demandeur_credit           0  0.00000000
11            Echeance_credit_en_cours           0  0.00000000
12               Eligibilité_au_credit           0  0.00000000

Analyses exploratoires de la distribution des variables

plot_bar(DataRisk) # Diagramme en bar pour les variables quanlitatives

plot_histogram(DataRisk) # Diagramme en bâton pour les variables quantitatives

Exploration des relations entre les variables

# Correlation entre les variables dicrètes, categorielles, qualitatives
plot_correlation(DataRisk, cor_args = list("use" = "pairwise.complete.obs"), type="d") 

# Correlation entre les variables continues, quantitatives
plot_correlation(DataRisk, cor_args = list("use" = "pairwise.complete.obs"), type="c")

Rapport automatisé des analyses exploratoires

create_report(DataRisk)


processing file: report.rmd

  |                                           
  |                                     |   0%
  |                                           
  |.                                    |   2%                                 
  |                                           
  |..                                   |   5% [global_options]                
  |                                           
  |...                                  |   7%                                 
  |                                           
  |....                                 |  10% [introduce]                     
  |                                           
  |....                                 |  12%                                 
  |                                           
  |.....                                |  14% [plot_intro]                    
  |                                           
  |......                               |  17%                                 
  |                                           
  |.......                              |  19% [data_structure]                
  |                                           
  |........                             |  21%                                 
  |                                           
  |.........                            |  24% [missing_profile]               
  |                                           
  |..........                           |  26%                                 
  |                                           
  |...........                          |  29% [univariate_distribution_header]
  |                                           
  |...........                          |  31%                                 
  |                                           
  |............                         |  33% [plot_histogram]                
  |                                           
  |.............                        |  36%                                 
  |                                           
  |..............                       |  38% [plot_density]                  
  |                                           
  |...............                      |  40%                                 
  |                                           
  |................                     |  43% [plot_frequency_bar]            
  |                                           
  |.................                    |  45%                                 
  |                                           
  |..................                   |  48% [plot_response_bar]             
  |                                           
  |..................                   |  50%                                 
  |                                           
  |...................                  |  52% [plot_with_bar]                 
  |                                           
  |....................                 |  55%                                 
  |                                           
  |.....................                |  57% [plot_normal_qq]                
  |                                           
  |......................               |  60%                                 
  |                                           
  |.......................              |  62% [plot_response_qq]              
  |                                           
  |........................             |  64%                                 
  |                                           
  |.........................            |  67% [plot_by_qq]                    
  |                                           
  |..........................           |  69%                                 
  |                                           
  |..........................           |  71% [correlation_analysis]          
  |                                           
  |...........................          |  74%                                 
  |                                           
  |............................         |  76% [principal_component_analysis]  
  |                                           
  |.............................        |  79%                                 
  |                                           
  |..............................       |  81% [bivariate_distribution_header] 
  |                                           
  |...............................      |  83%                                 
  |                                           
  |................................     |  86% [plot_response_boxplot]         
  |                                           
  |.................................    |  88%                                 
  |                                           
  |.................................    |  90% [plot_by_boxplot]               
  |                                           
  |..................................   |  93%                                 
  |                                           
  |...................................  |  95% [plot_response_scatterplot]     
  |                                           
  |.................................... |  98%                                 
  |                                           
  |.....................................| 100% [plot_by_scatterplot]           
                                                                                                                           
output file: C:/Users/Ideapad/Desktop/Valdom/Projet personnel Machine Learning/ML Risk Credit Modeling/report.knit.md
"C:/Program Files/RStudio/resources/app/bin/quarto/bin/tools/pandoc" +RTS -K512m -RTS "C:\Users\Ideapad\Desktop\Valdom\PROJET~1\MLRISK~1\REPORT~1.MD" --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output pandoc13545a4a5e38.html --lua-filter "C:\Users\Ideapad\AppData\Local\R\win-library\4.3\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\Ideapad\AppData\Local\R\win-library\4.3\rmarkdown\rmarkdown\lua\latex-div.lua" --embed-resources --standalone --variable bs3=TRUE --section-divs --table-of-contents --toc-depth 6 --template "C:\Users\Ideapad\AppData\Local\R\win-library\4.3\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable theme=yeti --mathjax --variable "mathjax-url=https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" --include-in-header "C:\Users\Ideapad\AppData\Local\Temp\Rtmp8sZwsq\rmarkdown-str1354277c2562.html" 

Output created: report.html

Modélisation du risque de credit (Machine Learning)

Partitionnement de données

# Train/Test
set.seed(1000) # Fixer l'aleatoire
Split_Index=DataRisk%>%rsample::initial_split(prop = 3/4,strata = Eligibilité_au_credit)

DataRisk_Train=Split_Index%>%rsample::training()
DataRisk_Test=Split_Index%>%rsample::testing()

# Cross Validation split of training data 
set.seed(123)
cv_folds=vfold_cv(data = DataRisk_Train, v=10)
print(cv_folds)
#  10-fold cross-validation 
# A tibble: 10 × 2
   splits               id    
   <list>               <chr> 
 1 <split [21991/2444]> Fold01
 2 <split [21991/2444]> Fold02
 3 <split [21991/2444]> Fold03
 4 <split [21991/2444]> Fold04
 5 <split [21991/2444]> Fold05
 6 <split [21992/2443]> Fold06
 7 <split [21992/2443]> Fold07
 8 <split [21992/2443]> Fold08
 9 <split [21992/2443]> Fold09
10 <split [21992/2443]> Fold10
print(Split_Index)
<Training/Testing/Total>
<24435/8146/32581>

Definir la fonction de prétraitement recipe

 DataRisk_Recipe= recipes::recipe(Eligibilité_au_credit ~.,data=DataRisk_Train)%>%
  step_impute_knn(all_predictors())%>% # Imputation des valeurs manquantes 
  step_dummy(all_nominal_predictors())%>% # Encoder les variables qualitatives
  step_normalize(all_numeric_predictors()) # Centrer et Reduire les Variables les predicteurs numériques
DataRisk_Recipe
── Recipe ──────────────────────────────────────────────────────────────────────
── Inputs 
Number of variables by role
outcome:    1
predictor: 11
── Operations 
• K-nearest neighbor imputation for: all_predictors()
• Dummy variables from: all_nominal_predictors()
• Centering and scaling for: all_numeric_predictors()
#DataRisk_Recipe%>%prep()%>%bake(new_data = NULL)  

Modélisation par les algorithmes de classification

# Regression Logistique
Model_RegLog=logistic_reg()%>%
  set_mode("classification")%>%
  set_engine("glm")
  

# Arbre de decison
Model_DecTree=decision_tree()%>%
  set_mode("classification")%>%
  set_engine("rpart")

# Forêt aleatoire 
Model_RandForest=rand_forest()%>%
     set_mode("classification")%>%
     set_engine("ranger")

# Boosting
Model_boosting = boost_tree()%>%
set_mode("classification")%>%
set_engine("xgboost") 

## reseau de neurones mulptiple perceptron
#Model_mlp <- mlp()%>%
#set_mode("classification") %>% 
#set_engine("nnet") 

## k voisins les plus proches
#Model_knn = nearest_neighbor()%>%
#set_mode("classification")%>%
#set_engine("kknn") 

## Support Vecteur  Machine
#Model_svm <- svm_poly()%>%
#set_mode("classification")%>% 
#set_engine("kernlab") 

Model_RegLog
Logistic Regression Model Specification (classification)

Computational engine: glm 
Model_DecTree
Decision Tree Model Specification (classification)

Computational engine: rpart 
Model_RandForest
Random Forest Model Specification (classification)

Computational engine: ranger 
Model_boosting
Boosted Tree Model Specification (classification)

Computational engine: xgboost 
#Model_mlp
#Model_knn
#Model_svm

Definition Workflow_set (pretraitement + ensemble de modèle)

Wf_set = workflowsets::workflow_set(preproc = list(DataRisk_Recipe),
                                      models = list(Model_RegLog,Model_DecTree,Model_RandForest,Model_boosting))

Wf_set
# A workflow set/tibble: 4 × 4
  wflow_id             info             option    result    
  <chr>                <list>           <list>    <list>    
1 recipe_logistic_reg  <tibble [1 × 4]> <opts[0]> <list [0]>
2 recipe_decision_tree <tibble [1 × 4]> <opts[0]> <list [0]>
3 recipe_rand_forest   <tibble [1 × 4]> <opts[0]> <list [0]>
4 recipe_boost_tree    <tibble [1 × 4]> <opts[0]> <list [0]>

Entrainement et évaluation de l’ensemble des workflow (Workflow_set) par la technique de la validation croisée sur les données d’entrainement. (Entrainement par réechantillonage)

doParallel::registerDoParallel()
  
Wf_set_fit=workflow_map(Wf_set,"fit_resamples",resamples=cv_folds, seed = 22)
Wf_set_fit
# A workflow set/tibble: 4 × 4
  wflow_id             info             option    result   
  <chr>                <list>           <list>    <list>   
1 recipe_logistic_reg  <tibble [1 × 4]> <opts[1]> <rsmp[+]>
2 recipe_decision_tree <tibble [1 × 4]> <opts[1]> <rsmp[+]>
3 recipe_rand_forest   <tibble [1 × 4]> <opts[1]> <rsmp[+]>
4 recipe_boost_tree    <tibble [1 × 4]> <opts[1]> <rsmp[+]>

Comparaison et choix du meilleur Workflow !

autoplot(Wf_set_fit)

collect_metrics(Wf_set_fit)
# A tibble: 12 × 9
   wflow_id        .config preproc model .metric .estimator   mean     n std_err
   <chr>           <chr>   <chr>   <chr> <chr>   <chr>       <dbl> <int>   <dbl>
 1 recipe_logisti… Prepro… recipe  logi… accura… binary     0.867     10 0.00254
 2 recipe_logisti… Prepro… recipe  logi… brier_… binary     0.102     10 0.00125
 3 recipe_logisti… Prepro… recipe  logi… roc_auc binary     0.869     10 0.00304
 4 recipe_decisio… Prepro… recipe  deci… accura… binary     0.913     10 0.00224
 5 recipe_decisio… Prepro… recipe  deci… brier_… binary     0.0756    10 0.00185
 6 recipe_decisio… Prepro… recipe  deci… roc_auc binary     0.851     10 0.00452
 7 recipe_rand_fo… Prepro… recipe  rand… accura… binary     0.933     10 0.00259
 8 recipe_rand_fo… Prepro… recipe  rand… brier_… binary     0.0580    10 0.00167
 9 recipe_rand_fo… Prepro… recipe  rand… roc_auc binary     0.934     10 0.00302
10 recipe_boost_t… Prepro… recipe  boos… accura… binary     0.935     10 0.00240
11 recipe_boost_t… Prepro… recipe  boos… brier_… binary     0.0561    10 0.00182
12 recipe_boost_t… Prepro… recipe  boos… roc_auc binary     0.937     10 0.00296
rank_results(Wf_set_fit,rank_metric = "accuracy",select_best = TRUE )
# A tibble: 12 × 9
   wflow_id        .config .metric   mean std_err     n preprocessor model  rank
   <chr>           <chr>   <chr>    <dbl>   <dbl> <int> <chr>        <chr> <int>
 1 recipe_boost_t… Prepro… accura… 0.935  0.00240    10 recipe       boos…     1
 2 recipe_boost_t… Prepro… brier_… 0.0561 0.00182    10 recipe       boos…     1
 3 recipe_boost_t… Prepro… roc_auc 0.937  0.00296    10 recipe       boos…     1
 4 recipe_rand_fo… Prepro… accura… 0.933  0.00259    10 recipe       rand…     2
 5 recipe_rand_fo… Prepro… brier_… 0.0580 0.00167    10 recipe       rand…     2
 6 recipe_rand_fo… Prepro… roc_auc 0.934  0.00302    10 recipe       rand…     2
 7 recipe_decisio… Prepro… accura… 0.913  0.00224    10 recipe       deci…     3
 8 recipe_decisio… Prepro… brier_… 0.0756 0.00185    10 recipe       deci…     3
 9 recipe_decisio… Prepro… roc_auc 0.851  0.00452    10 recipe       deci…     3
10 recipe_logisti… Prepro… accura… 0.867  0.00254    10 recipe       logi…     4
11 recipe_logisti… Prepro… brier_… 0.102  0.00125    10 recipe       logi…     4
12 recipe_logisti… Prepro… roc_auc 0.869  0.00304    10 recipe       logi…     4

Extraire et entraîner le meilleur Workflow sur l’integralité des données d’entraînement puis l’évaluer directement sur les données Test.

# Extraire le meilleur workflow XGBoosting
Wf_final=extract_workflow(Wf_set_fit,id="recipe_boost_tree")
Wf_final
══ Workflow ════════════════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: boost_tree()

── Preprocessor ────────────────────────────────────────────────────────────────
3 Recipe Steps

• step_impute_knn()
• step_dummy()
• step_normalize()

── Model ───────────────────────────────────────────────────────────────────────
Boosted Tree Model Specification (classification)

Computational engine: xgboost 
#Entrainer et evaluer le meilleur modèle avec la fonction last_fit
Wf_final_fit=last_fit(Wf_final,Split_Index)
Wf_final_fit
# Resampling results
# Manual resampling 
# A tibble: 1 × 6
  splits               id              .metrics .notes   .predictions .workflow 
  <list>               <chr>           <list>   <list>   <list>       <list>    
1 <split [24435/8146]> train/test spl… <tibble> <tibble> <tibble>     <workflow>
collect_metrics(Wf_final_fit)
# A tibble: 3 × 4
  .metric     .estimator .estimate .config             
  <chr>       <chr>          <dbl> <chr>               
1 accuracy    binary        0.930  Preprocessor1_Model1
2 roc_auc     binary        0.930  Preprocessor1_Model1
3 brier_class binary        0.0596 Preprocessor1_Model1
collect_predictions(Wf_final_fit)
# A tibble: 8,146 × 7
   .pred_class         .pred_Eligible au cr…¹ .pred_Non Eligible a…² id     .row
   <fct>                                <dbl>                  <dbl> <chr> <int>
 1 Non Eligible au cr…                0.0303                  0.970  trai…     4
 2 Non Eligible au cr…                0.00836                 0.992  trai…     6
 3 Non Eligible au cr…                0.0560                  0.944  trai…    14
 4 Eligible au credit                 0.972                   0.0281 trai…    15
 5 Eligible au credit                 0.972                   0.0281 trai…    17
 6 Non Eligible au cr…                0.0755                  0.924  trai…    23
 7 Non Eligible au cr…                0.0190                  0.981  trai…    36
 8 Non Eligible au cr…                0.0662                  0.934  trai…    39
 9 Eligible au credit                 0.815                   0.185  trai…    60
10 Eligible au credit                 0.852                   0.148  trai…    68
# ℹ 8,136 more rows
# ℹ abbreviated names: ¹​`.pred_Eligible au credit`,
#   ²​`.pred_Non Eligible au credit`
# ℹ 2 more variables: Eligibilité_au_credit <fct>, .config <chr>
#Entrainement sur l'ensemble des données avec la fontion fit
Last_Wf = fit(Wf_final,DataRisk)
Last_Wf
══ Workflow [trained] ══════════════════════════════════════════════════════════
Preprocessor: Recipe
Model: boost_tree()

── Preprocessor ────────────────────────────────────────────────────────────────
3 Recipe Steps

• step_impute_knn()
• step_dummy()
• step_normalize()

── Model ───────────────────────────────────────────────────────────────────────
##### xgb.Booster
raw: 51.3 Kb 
call:
  xgboost::xgb.train(params = list(eta = 0.3, max_depth = 6, gamma = 0, 
    colsample_bytree = 1, colsample_bynode = 1, min_child_weight = 1, 
    subsample = 1), data = x$data, nrounds = 15, watchlist = x$watchlist, 
    verbose = 0, nthread = 1, objective = "binary:logistic")
params (as set within xgb.train):
  eta = "0.3", max_depth = "6", gamma = "0", colsample_bytree = "1", colsample_bynode = "1", min_child_weight = "1", subsample = "1", nthread = "1", objective = "binary:logistic", validate_parameters = "TRUE"
xgb.attributes:
  niter
callbacks:
  cb.evaluation.log()
# of features: 22 
niter: 15
nfeatures : 22 
evaluation_log:
     iter training_logloss
    <num>            <num>
        1        0.5038673
        2        0.4015599
---                       
       14        0.2014229
       15        0.1990482
Essai=data.framege =60, 
                 Revenu_annuel=10000,
                 Statut_propriétaire_logement="Hypothèque",
                 Durée_d_emploi=5,
                 Motif_du_prêt="Besoin personnel",
                 Câtegorie_du_prêt="D",
                 Montant_du_prêt=8000000,
                 Taux_d_intérêt=10,
                 Pourcentage_de_revenu=0.01, 
                 Decouvert_bancaire_demandeur_credit="Oui",
                  Echeance_credit_en_cours=3)
Essai=Essai%>%dplyr::mutate_if(is.character,as.factor)
summary(Essai)
      Âge     Revenu_annuel   Statut_propriétaire_logement Durée_d_emploi
 Min.   :60   Min.   :10000   Hypothèque:1                 Min.   :5     
 1st Qu.:60   1st Qu.:10000                                1st Qu.:5     
 Median :60   Median :10000                                Median :5     
 Mean   :60   Mean   :10000                                Mean   :5     
 3rd Qu.:60   3rd Qu.:10000                                3rd Qu.:5     
 Max.   :60   Max.   :10000                                Max.   :5     
          Motif_du_prêt Câtegorie_du_prêt Montant_du_prêt Taux_d_intérêt
 Besoin personnel:1     D:1               Min.   :8e+06   Min.   :10    
                                          1st Qu.:8e+06   1st Qu.:10    
                                          Median :8e+06   Median :10    
                                          Mean   :8e+06   Mean   :10    
                                          3rd Qu.:8e+06   3rd Qu.:10    
                                          Max.   :8e+06   Max.   :10    
 Pourcentage_de_revenu Decouvert_bancaire_demandeur_credit
 Min.   :0.01          Oui:1                              
 1st Qu.:0.01                                             
 Median :0.01                                             
 Mean   :0.01                                             
 3rd Qu.:0.01                                             
 Max.   :0.01                                             
 Echeance_credit_en_cours
 Min.   :3               
 1st Qu.:3               
 Median :3               
 Mean   :3               
 3rd Qu.:3               
 Max.   :3               
Pred_prob=predict(Last_Wf,Essai,type="prob")
Pred_class=predict(Last_Wf,Essai,type="class")
# Pour faire la prediction, on extrait le modèle du workflow puis on applique la fonction de pretraitement aux nouvelles données. 
#Pred_prob=predict(extract_fit_parsnip(Wf_final_fit), new_data = DataRisk_Recipe%>%prep()%>%bake(new_data = Essai), type = "prob" )
#Pred_prob$`.pred_Eligible au credit`
#Pred_class=predict(extract_fit_parsnip(Wf_final_fit), new_data = DataRisk_Recipe%>%prep()%>%bake(new_data = Essai), type = "class" )
#Pred_class

Sauvegarde du meilleur modèle

saveRDS(Last_Wf, file="C:/Users/Ideapad/Desktop/Valdom/Projet personnel Application Shiny/DashboardCreditRisk/Final.rds")

Quelques informations du meilleur modèle

mod=extract_fit_parsnip(Wf_final_fit)
print(attributes(mod))
$names
[1] "lvl"          "spec"         "fit"          "preproc"      "elapsed"     
[6] "censor_probs"

$class
[1] "_xgb.Booster" "model_fit"   
vip(mod) # importance des variables dans la modelisation