ls()
## character(0)
rm(list = ls())
getwd()
## [1] "D:/data"
library(dplyr)
## Warning: 패키지 'dplyr'는 R 버전 4.1.3에서 작성되었습니다
## 
## 다음의 패키지를 부착합니다: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
read.delim("titanic3.txt",header=TRUE,sep=',')->full
full %>% glimpse
## Rows: 1,309
## Columns: 14
## $ pclass    <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ~
## $ survived  <int> 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, ~
## $ name      <chr> "Allen, Miss. Elisabeth Walton", "Allison, Master. Hudson Tr~
## $ sex       <chr> "female", "male", "female", "male", "female", "male", "femal~
## $ age       <dbl> 29.00, 0.92, 2.00, 30.00, 25.00, 48.00, 63.00, 39.00, 53.00,~
## $ sibsp     <int> 0, 1, 1, 1, 1, 0, 1, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, ~
## $ parch     <int> 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, ~
## $ ticket    <chr> "24160", "113781", "113781", "113781", "113781", "19952", "1~
## $ fare      <dbl> 211.3375, 151.5500, 151.5500, 151.5500, 151.5500, 26.5500, 7~
## $ cabin     <chr> "B5", "C22 C26", "C22 C26", "C22 C26", "C22 C26", "E12", "D7~
## $ embarked  <chr> "S", "S", "S", "S", "S", "S", "S", "S", "S", "C", "C", "C", ~
## $ boat      <chr> "2", "11", "", "", "", "3", "10", "", "D", "", "", "4", "9",~
## $ body      <int> NA, NA, NA, 135, NA, NA, NA, NA, NA, 22, 124, NA, NA, NA, NA~
## $ home.dest <chr> "St Louis, MO", "Montreal, PQ / Chesterville, ON", "Montreal~
library(caret)
## 필요한 패키지를 로딩중입니다: ggplot2
## 필요한 패키지를 로딩중입니다: lattice
set.seed(123)

train_list<-createDataPartition(y=full$survived,p=0.7,list=FALSE)
#full 데이터 가운데 70%(=0.7)를 학습용으로 (자연스레 나머지 30%를 시험용) 골라내 이를 train_list라는 변수에 넣으라는 뜻

full_train<-full[train_list,]
full_test<-full[-train_list,]
NROW(full_train)
## [1] 917
train<-full_train
test<-full_test

#train파일에 index 변수를 생성하고 train이라고 채워라
train %>% mutate(index='train')->train
test %>% mutate(index='test')->test

bind_rows(train,test)->full
full %>% select(-boat,-body,-home.dest)->full
full %>% glimpse
## Rows: 1,309
## Columns: 12
## $ pclass   <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1~
## $ survived <int> 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1~
## $ name     <chr> "Allison, Master. Hudson Trevor", "Allison, Miss. Helen Lorai~
## $ sex      <chr> "male", "female", "female", "male", "male", "female", "male",~
## $ age      <dbl> 0.92, 2.00, 25.00, 48.00, 39.00, 53.00, 71.00, 47.00, 24.00, ~
## $ sibsp    <int> 1, 1, 1, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0~
## $ parch    <int> 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0~
## $ ticket   <chr> "113781", "113781", "113781", "19952", "112050", "11769", "PC~
## $ fare     <dbl> 151.5500, 151.5500, 151.5500, 26.5500, 0.0000, 51.4792, 49.50~
## $ cabin    <chr> "C22 C26", "C22 C26", "C22 C26", "E12", "A36", "C101", "", "C~
## $ embarked <chr> "S", "S", "S", "S", "S", "S", "C", "C", "C", "S", "C", "C", "~
## $ index    <chr> "train", "train", "train", "train", "train", "train", "train"~
full$survived<-ifelse(full$survived==0,"생존","사망")
full$survived<-as.factor(full$survived)
table(full$embarked)
## 
##       C   Q   S 
##   2 270 123 914
summary(is.na(full))
##    pclass         survived          name            sex         
##  Mode :logical   Mode :logical   Mode :logical   Mode :logical  
##  FALSE:1309      FALSE:1309      FALSE:1309      FALSE:1309     
##                                                                 
##     age            sibsp           parch           ticket       
##  Mode :logical   Mode :logical   Mode :logical   Mode :logical  
##  FALSE:1046      FALSE:1309      FALSE:1309      FALSE:1309     
##  TRUE :263                                                      
##     fare           cabin          embarked         index        
##  Mode :logical   Mode :logical   Mode :logical   Mode :logical  
##  FALSE:1308      FALSE:1309      FALSE:1309      FALSE:1309     
##  TRUE :1
#full 에서 결치값을 확인하라
full$pclass<-as.factor(full$pclass)
full$sex<-as.factor(full$sex)
full$embarked<-as.factor(full$embarked)
#fac형 데이터로 변환
summary(full)
##  pclass  survived       name               sex           age       
##  1:323   사망:500   Length:1309        female:466   Min.   : 0.17  
##  2:277   생존:809   Class :character   male  :843   1st Qu.:21.00  
##  3:709              Mode  :character                Median :28.00  
##                                                     Mean   :29.88  
##                                                     3rd Qu.:39.00  
##                                                     Max.   :80.00  
##                                                     NA's   :263    
##      sibsp            parch          ticket               fare        
##  Min.   :0.0000   Min.   :0.000   Length:1309        Min.   :  0.000  
##  1st Qu.:0.0000   1st Qu.:0.000   Class :character   1st Qu.:  7.896  
##  Median :0.0000   Median :0.000   Mode  :character   Median : 14.454  
##  Mean   :0.4989   Mean   :0.385                      Mean   : 33.295  
##  3rd Qu.:1.0000   3rd Qu.:0.000                      3rd Qu.: 31.275  
##  Max.   :8.0000   Max.   :9.000                      Max.   :512.329  
##                                                      NA's   :1        
##     cabin           embarked    index          
##  Length:1309         :  2    Length:1309       
##  Class :character   C:270    Class :character  
##  Mode  :character   Q:123    Mode  :character  
##                     S:914                      
##                                                
##                                                
## 
#결치값 확인
full %>% glimpse
## Rows: 1,309
## Columns: 12
## $ pclass   <fct> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1~
## $ survived <fct> 사망, 생존, 생존, 사망, 생존, 사망, 생존, 생존, 사망, 생존, ~
## $ name     <chr> "Allison, Master. Hudson Trevor", "Allison, Miss. Helen Lorai~
## $ sex      <fct> male, female, female, male, male, female, male, male, female,~
## $ age      <dbl> 0.92, 2.00, 25.00, 48.00, 39.00, 53.00, 71.00, 47.00, 24.00, ~
## $ sibsp    <int> 1, 1, 1, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0~
## $ parch    <int> 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0~
## $ ticket   <chr> "113781", "113781", "113781", "19952", "112050", "11769", "PC~
## $ fare     <dbl> 151.5500, 151.5500, 151.5500, 26.5500, 0.0000, 51.4792, 49.50~
## $ cabin    <chr> "C22 C26", "C22 C26", "C22 C26", "E12", "A36", "C101", "", "C~
## $ embarked <fct> S, S, S, S, S, S, C, C, C, S, C, C, C, C, C, C, S, C, C, C, S~
## $ index    <chr> "train", "train", "train", "train", "train", "train", "train"~
#fac형 변환 확인
levels(full$embarked)
## [1] ""  "C" "Q" "S"
#embarked는 c,q,s 3개로 분류 확인

#full$surviver의 1번 레벨(즉, 결치값)을 NA로 채워라
levels(full$embarked)[1]<-NA
table(full$embarked,useNA="always")
## 
##    C    Q    S <NA> 
##  270  123  914    2
full %>% filter(!is.na(age)&!is.na(fare)&!is.na(embarked))->full
#full 데이터에서 age+fare+embarked의 결치값을 제외하고 full로 저장하라
colSums(is.na(full))
##   pclass survived     name      sex      age    sibsp    parch   ticket 
##        0        0        0        0        0        0        0        0 
##     fare    cabin embarked    index 
##        0        0        0        0
#full 데이터에서 결치값을 확인한다 -> 없음

library(recipes)
## Warning: 패키지 'recipes'는 R 버전 4.1.3에서 작성되었습니다
## 
## 다음의 패키지를 부착합니다: 'recipes'
## The following object is masked from 'package:stats':
## 
##     step
#모형을 만들 때는 이렇게 공식만 입력하는 게 아니라 결측값을 제거하고, 이상점(outlier)을 처리하고, 다중공선성이 나타나는 변수를 제거하고, 척도를 조정해 각 자료를 정규화하고, 가변수(dummy 변수)를 만드는 작업 등이 필요합니다.
#tidymodels에서는 step_*() 함수로 이 작업을 진행합니다. 그리고 prep() 함수로 실제 준비를 마칩니다.
#우리는 step_corr() 함수로 상관관계가 지나치게 큰 변수를 제거하고, step_center()와 step_scale() 함수를 써서 평균을 0으로 하는 척도를 만들어 보겠습니다.
#center : 평균이 0이 되게함, scale : 분산이 1이 되게 함
recipe(survived~.,data=full) %>% step_YeoJohnson(age,sibsp,parch,fare) %>% 
  step_center(age,sibsp,parch,fare) %>% 
  step_scale(age,sibsp,parch,fare) %>%
  prep() %>% juice()->full
#full 데이터의 survived를 기준으로 (age+sibsp+parch+fare)의 데이터 분포를 수정하고,

#불필요한 변수 제거
full %>% filter(index=="train") %>% select(-index,-ticket,-cabin)->train
full %>% filter(index=="test") %>% select(-index,-ticket,-cabin)->test

#마지막으로,다른성능평가측도를선택하려면trainControl()함수에추가옵션을사용한다. 
#summaryFunction= 옵션은 관측값과예측값을취하여성능측도를추정하는함수에서사용된다.
#두개의함수defaultSummary와twoClassSummary가이미패키지에포함되어있다.
#후자는ROC곡선아래의면적,민감도및특이도와같은2-집단(class)문제에대한측도를계산한다. 
#ROC곡선은예측된클래스확률(자동으로계산되지않음)을기반으로하므로다른옵션이필요하다.
#classProbs=TRUE 옵션은이러한계산을포함하는데사용된다.
ctrl<-trainControl(method="cv",summaryFunction = twoClassSummary,
                   classProbs = TRUE)

train(survived~.,data=train,
      method="rpart",metric='ROC',
      trControl=ctrl)->rffit
rffit
## CART 
## 
## 722 samples
##   8 predictor
##   2 classes: '사망', '생존' 
## 
## No pre-processing
## Resampling: Cross-Validated (10 fold) 
## Summary of sample sizes: 650, 650, 649, 649, 650, 650, ... 
## Resampling results across tuning parameters:
## 
##   cp          ROC        Sens       Spec     
##   0.02678571  0.7978806  0.5392857  0.9637879
##   0.06071429  0.7698368  0.5678571  0.8956061
##   0.41428571  0.6037734  0.3071429  0.9004040
## 
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was cp = 0.02678571.
predict(rffit,test,type="prob")->rffit1
predict(rffit,test,type="raw")->rffit2
head(rffit2)
## [1] 사망 생존 사망 사망 사망 생존
## Levels: 사망 생존
head(rffit1)
##        사망       생존
## 1 0.9079755 0.09202454
## 2 0.1951754 0.80482456
## 3 0.9079755 0.09202454
## 4 0.9079755 0.09202454
## 5 0.9079755 0.09202454
## 6 0.1951754 0.80482456
levels(test$survived)
## [1] "사망" "생존"
test$survived<-as.factor(test$survived)
confusionMatrix(rffit2,test$survived)
## Confusion Matrix and Statistics
## 
##           Reference
## Prediction 사망 생존
##       사망   70    1
##       생존   75  175
##                                           
##                Accuracy : 0.7632          
##                  95% CI : (0.7129, 0.8087)
##     No Information Rate : 0.5483          
##     P-Value [Acc > NIR] : 1.115e-15       
##                                           
##                   Kappa : 0.4995          
##                                           
##  Mcnemar's Test P-Value : < 2.2e-16       
##                                           
##             Sensitivity : 0.4828          
##             Specificity : 0.9943          
##          Pos Pred Value : 0.9859          
##          Neg Pred Value : 0.7000          
##              Prevalence : 0.4517          
##          Detection Rate : 0.2181          
##    Detection Prevalence : 0.2212          
##       Balanced Accuracy : 0.7385          
##                                           
##        'Positive' Class : 사망            
## 
#https://kuduz.tistory.com/1202