소품집

[Kaggle] 채무 불이행자 searching - ing (4) 본문

AI

[Kaggle] 채무 불이행자 searching - ing (4)

sodayeong 2020. 8. 31. 16:44

getwd()
setwd('/Users/dayeong/Desktop/reserch/data')

Encoding('UTF-8')

# Kaggle - DAY4
# Kaggle Loan data binary classification

# Data import 
library(readr)         # Data input with readr::read_csv()

# EDA : 탐색적 데이터 분석, 데이터 확인
library(VIM)           # Missing values with VIM::aggr()
library(descr)         # descr::CrossTable() - Factor data의 범주별 빈도수, 비율 확인 
library(DT)            # DT::datatable() - All data assesment with web chart 
library(corrplot)      # Correlation coefficient 확인 

# Visuallization : 시각화 
library(GGally)        # 모든 변수에 대한 다양한 시각화
library(ggplot2)       # Visuallization 
library(RColorBrewer)  # plot의 color 설정 
library(scales)        # plot setting - x, y 축 설정

# Feature engineering, Pre-processing : 데이터 전처리 
# library(tidyverse)   # ggplot2, dplyr, purrr, etc ...
library(dplyr)         # Used for almost all data handling 
library(lubridate)     # Time series data Pre-processing 

# Machine learning modeling : 기계학습 모델 생성
library(e1071)         # Support Vector Machine
library(rpart)         # Decision Tree
library(rpart.plot)    # Decision Tree plotting 
library(randomForest)  # Random Forest
library(glmnet)        # LASSO, Ridge 

# Model validation : 모델 검증, 성능 확인 
library(caret)         # confusionM


##
loan <- read.csv('Loan payments data.csv')
summary(loan)

# charater 속성으로 저장된 컬럼을 factor로 변환해주자
loan <- loan %>%
  mutate(Loan_ID = factor(Loan_ID),
         loan_status = factor(loan_status),
         effective_date = factor(effective_date),
         due_date = factor(due_date),
         paid_off_time = factor(paid_off_time),
         education = factor(education),
         Gender = factor(Gender))

summary(loan) # 시계열 데이터인 effective_date 와 due_date를 제외하고는 factor 형으로 나온다. 
View(loan)

##
# Simple operation 
# 이번 Binary classification에 사용할 변수만 선택해, 추출한 후 변수속성 변환하기.
loan <- loan %>%
  # classification 에 사용할 변수 추출
  select('loan_status', 'Principal', 'terms','effective_date',
         'due_date','age','education', 'Gender') %>%
  # change feature type / 변수 타입 변환
  # target feature인 loan_status를 2개 범주로 변환
  mutate(loan_status = factor(ifelse(loan_status == 'PAIDOFF', 'Success', 'Failure')),
         # Date 속성으로 변환할 변수들 - effective_date, due_date
         effective_date = mdy(effective_date),
         due_date = mdy(due_date),
         # 학력과 성별도 범주형 변수로 변환
         education = factor(education), 
         Gender = factor(Gender))
  

##
# 탐색적 데이터 분석 (EDA)
summary(loan)
str(loan)

# 1. Missing values - VIM packages
aggr(loan, prop=F, combined = TRUE,
     number=TRUE, sortVars=TRUE,
     sortCombs = TRUE)

# 2. 시각화
# loan status 
loan %>%
  ggplot(aes(x=loan_status)) + geom_bar() +
  labs(title='Bar plot', subtitle = 'Failure or Sucess') 
# 정해진 기한 내에 대출금을 상환한 고객이 (300:200)임을 알 수 있음

# Principal (대출금이 얼마인지)
ggplot(data = loan, aes(Principal)) + 
  geom_histogram(breaks = seq(from=300, to=1000, by=10),
  col='yellow', fill='blue', alpha=.5) +
  labs(title = 'First histogram of principal', subtitle = '고객이 빌린 대출금은 얼마나?') +
  theme_bw(base_family = "AppleGothic")

loan <- loan %>% 
  # Double 속성인 Principal을 Factor로 변환 
  mutate(Principal = factor(Principal))

loan %>% 
  mutate(Prinicipal = factor(Principal)) %>% 
  group_by(Principal) %>%
  summarize(Count=n()) %>%
  arrange(desc(Count))

loan %>% 
  mutate(Principal = factor(Principal)) %>% 
  group_by(Principal) %>% 
  summarize(Count = n()) %>% 
  ggplot(aes(Principal, Count)) +
  geom_col() +
  labs(x = "Principal", y = "Count",
       title = "Bar plot by Principal",
       subtitle = "고객들이 빌린 대출금은?") +
  geom_text(aes(label=Count)) +
  theme_bw(base_family = 'AppleGothic') # 800과 1000을 대출받은 고객들이 가장 많음을 알 수 있다.


# 대출금별로 상환에 성공한 고객과 실패하 고객의 빈도수와 비율을 한 화면에 같이 플랏팅 하기 

principal.p1 <- loan %>% 
  # Dbl 속성인 Principal feature를 Factor 속성으로 변환 
  mutate(Principal = factor(Principal)) %>% 
  # ggplot aesthetic setting - x = Principal, y = loan_status
  ggplot(aes(Principal, fill = loan_status)) +
  # loan_status 별로 따로 빈도수 막대 그래프 그리게 설정 
  geom_bar(position = "dodge") + 
  # Bar 내부의 색상 설정 
  scale_fill_brewer(palette = "Set1") + 
  # Plots x, y axis, main title and sub title setting 
  labs(x = "Principal", y = "Count",
       title='Frequency bar plot', subtitle = '대출금, 상환 여부 빈도수 막대그래프') +
  theme_bw(base_family = 'AppleGothic')

principal.p2 <- loan %>% 
  mutate(Principal = factor(Principal)) %>% 
  ggplot(aes(Principal, fill = loan_status)) +
  geom_bar(position = "fill") + 
  scale_fill_brewer(palette = "Set1") +
  # Y axis output을 %로 나오게 설정 
  scale_y_continuous(labels = percent) +
  labs(x = "Principal", y = "Rate",
       title = "Ratio bar plot", subtitle = "대출금, 상환 여부 비율 막대 그래프",
       caption = "Source : Kaggle Loan data") +
  theme_bw(base_family = 'AppleGothic')

# Multiplots layout setting wuth matrix(), rep()
par(mfrow=c(1,2))

# terms(연속형)
# 고객이 은행과 계약한 이후, 대출금을 지급받기까지 걸린 시간을 나타낸 변수. 
# 대출금을 지급받기 까지 7,14, 30일이 걸린 고객들만 존재함을 알 수 있음. 
# 따라서, Principal과 유사하게 terms의 속성을 factor로 변환하고 빈도수 막대 그래프와 비율 막대ㄹ그래프를 그려보자.
loan %>%
  ggplot(aes(terms)) +
  geom_histogram(breaks=seq(from=7, to=30, by=1), col='yellow', fill='blue', alpha=0.8) +
  labs(caption = 'Source : Kaggle Loan data')

# Console window에 terms 범주별 빈도수 추출 
loan %>% 
  mutate(terms = factor(terms)) %>%
  group_by(terms) %>%
  summarise(Count=n()) %>%
  arrange(desc(Count))
  
# term 1st visualization - 빈도수 막대 그래프 
terms.p1 <- loan %>%
  mutate(terms = factor(terms)) %>%
  ggplot(aes(terms), fill=loan_status) +
  geom_bar(position='dodge') + 
  scale_fill_brewer(palette = 'Set1') +
  labs(x='Terms', y='Count', title = 'Frequency bar plot by terms', subtitle = '범주별 성공/실패 여부') +
  theme_bw(base_family = 'AppleGothic')


# term 2nd visualization - 비율 막대 그래프
terms.p2 <- loan %>%
  mutate(terms = factor(terms)) %>%
  ggplot(aes(terms, fill= loan_status)) +
  geom_bar(position = 'fill') +
  scale_fill_brewer(palette = 'Set1') +
  scale_y_continuous(labels=percent) +
  labs(title='Ration bar plot by terms', subtitle = '범주별 성공/실패 비율 막대 그래프')

multiplot(terms.p1, terms.p2)

multiplot <- function(..., plotlist = NULL, file, cols = 1, layout = NULL) {
  library(grid)
  
  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)
  
  numPlots = length(plots)
  
  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }
  
  if (numPlots==1) {
    print(plots[[1]])
    
  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
    
    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
      
      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}






















오늘은 ,, 인턴 교육 때 틈틈히 했지만 아직 끝내진 못하여

내일 이어서 마저 하겠습니다!~!

 

 

출처 : redhorse046.tistory.com/15

 

728x90
Comments