R Markdown
library(tidyverse)
## ── 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.4.4 ✔ 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(randomForest)
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
##
## Attaching package: 'randomForest'
##
## The following object is masked from 'package:dplyr':
##
## combine
##
## The following object is masked from 'package:ggplot2':
##
## margin
library(gmodels)
CreditCardData_1_ <- read_csv("Downloads/CreditCardData(1).csv")
## Rows: 10127 Columns: 21
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (6): Attrition_Flag, Gender, Education_Level, Marital_Status, Income_Ca...
## dbl (15): CLIENTNUM, Customer_Age, Dependent_count, Months_on_book, Total_Re...
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
CreditCardData2 <- CreditCardData_1_ %>%
mutate(random = runif(10127) ,
Attrition_Flag = as.factor(Attrition_Flag)) %>%
select(-CLIENTNUM)
train <- CreditCardData2 %>%
filter(random < .7) %>%
select(-random)
val <- CreditCardData2 %>%
filter(random >= .7) %>%
select(-random)
rf <- randomForest(Attrition_Flag ~. ,
type = 'classification' ,
data = train ,
importance = T)
val$predicted_Attrition_Flag <- predict(rf , val)
CrossTable(val$predicted_Attrition_Flag , val$predicted_Attrition_Flag)
##
##
## Cell Contents
## |-------------------------|
## | N |
## | Chi-square contribution |
## | N / Row Total |
## | N / Col Total |
## | N / Table Total |
## |-------------------------|
##
##
## Total Observations in Table: 3080
##
##
## | val$predicted_Attrition_Flag
## val$predicted_Attrition_Flag | Attrited Customer | Existing Customer | Row Total |
## -----------------------------|-------------------|-------------------|-------------------|
## Attrited Customer | 452 | 0 | 452 |
## | 2242.332 | 385.668 | |
## | 1.000 | 0.000 | 0.147 |
## | 1.000 | 0.000 | |
## | 0.147 | 0.000 | |
## -----------------------------|-------------------|-------------------|-------------------|
## Existing Customer | 0 | 2628 | 2628 |
## | 385.668 | 66.332 | |
## | 0.000 | 1.000 | 0.853 |
## | 0.000 | 1.000 | |
## | 0.000 | 0.853 | |
## -----------------------------|-------------------|-------------------|-------------------|
## Column Total | 452 | 2628 | 3080 |
## | 0.147 | 0.853 | |
## -----------------------------|-------------------|-------------------|-------------------|
##
##