반전공자

R 데이터 분석 프로젝트 - Titanic (Decision tree) 본문

데이터분석/R

R 데이터 분석 프로젝트 - Titanic (Decision tree)

하연01 2021. 6. 9. 07:02

R에서 기본적으로 제공하는 데이터는 결측치를 처리하는 등 전처리 과정이 길기 때문에 

교수님께서 제공해주신 어느정도 전처리가 되어 있는 데이터로 실습을 진행하도록 한다.

 

titanic = read.csv("titanic_clean.csv", header = TRUE, sep = ",")
str(titanic)

→ 데이터 형식이 맞지 않는 것들을 다시 정비해준다. 

pclass : 1, 2, 3등석 → factor

survived : 생존 / 사망 → factor

sex : 여성 / 남성 → factor

 

< 데이터 전처리 >

# data cleaning 
titanic$pclass=as.factor(titanic$pclass)
titanic$survived=factor(titanic$survived, levels=c(0,1))
titanic$sex=as.factor(titanic$sex)

기존에 맞지 않던 데이터 형식을 모두 맞춰주었다. 

as.factor() : 데이터 형식을 factor로 변경 

 

 

< 그래프 그려서 이해하기 > 

# understanding data: by plot
ggplot(titanic, aes(x=factor(pclass), fill=factor(sex))) + 
  geom_bar(position="dodge")
ggplot(titanic, aes(x=factor(pclass), fill=factor(sex))) +
  geom_bar(position = "dodge")+
  facet_grid(". ~ survived")

01

등석, 성별 기준으로 사람의 수를 그래프로 그려보고, 

사망과 생존으로 나누어 두 그래프를 그리고 그 안에 있는 그래프를 살펴보면

→ 남성이 많이 사망했고 3등석의 남성은 더더욱 많이 사망했다. 

→  여성은 많이 생존했고, 큰 차이는 없지만 1등석의 여성이 많이 생존했다. 

 

 

< 흩어진 정도를 나타내는 그래프 >

- 등석, 성별, 나이 별 생존여부

posn.j = position_jitter(0.3, 0) # width = 0.3
ggplot(titanic, aes(x=factor(pclass), y=age, col=factor(sex))) +
  geom_jitter(size=3, alpha=0.5, position = posn.j) +
  facet_grid(". ~ survived")

알파값을 0.5로 지정함으로써 포인트를 반투명으로 표시한다. 

 

▶ 3등석의 남성이 가장 많이 사망했으며 나이대는 10대 후반 ~ 40대 사이에 분포되어 있다. 

▶ 1등석의 여성이 가장 많이 생존했으며 나이대는 20대 ~ 60대 사이에 분포되어있다. 

→ 그 시대, 여성과 아이를 먼저 살리는 영국인들의 생각이 반영된 결과가 아닐까?

 

 

< 모자이크 그래프 >

mosaicplot(survived~pclass+sex, main="pclass and sex", data=titanic, color=TRUE)

 

한눈에 분포를 살펴볼 수 있다. 

검은색 : 생존 / 회색 : 사망 

▶ 3등석 남성이 가장 많이 사망 / 1등석 여성이 가장 많이 생존 

 

 

 

< Hmisc - summary >

더욱 상세한 summary 

library(Hmisc)
summary(survived~pclass+sex+age+sibsp+parch+fare+embarked, data=titanic, method="reverse")

01

변수 별로 사망과 생존의 비율을 한눈에 볼 수 있게 하는 표 

 

 

< Data 분할 >

8 : 2 로 데이터를 분할

# train the Titanic Classification Model 
library(rpart)
library(rpart.plot)

set.seed(100)
trainingRowIndex = sample(1:nrow(titanic), 0.8*nrow(titanic))
trainingData = titanic[trainingRowIndex,]
testData = titanic[-trainingRowIndex,]

100개의 번호를 뽑아놓고 , 80개의 데이터를 trainingData(학습)로 , 나머지는 testData(예측)로 분할한다.

 

 

 

< Decision tree 구축, 시각화 >

dt1 = rpart(survived~pclass+sex+age+sibsp+parch+fare+embarked,
            data = trainingData)
prp(dt1, type=0, extra=2, digits = 4) # Decision tree 시각화

pclass, sex, age, sibsp(형제의 수), parch(부모, 자녀), fare(요금), embarked(승선위치)를 가지고

survived를 구분하는 Decision Tree를 만든다.

가장 처음 분류의 기준인 sex는 gini index 계산 결과, 가장 낮은 변수이기 때문에 처음의 기준으로 지정되었을 것이다. 

( Decision tree에서 사용한 알고리즘이 CART인데 이 알고리즘에서는 gini index를 사용한다.)

 

 

< 예측 > 

# prediction 
prediction = predict(dt1, testData, type = "class")

Decision tree를 기반으로 테스트 데이터를 생존/사망으로 분류하는 예측을 실행한다.

 

< 정확도 확인 >

# check accuracy 
table(ifelse(testData$survived==prediction, "yes", "no"))

예측과 실제가 맞은 개수를 테이블로 보여달라. 

▶ 맞은 데이터는 215개, 틀린 데이터는 47개

 

'데이터분석 > R' 카테고리의 다른 글

R - < 회귀분석 >  (0) 2021.06.15
R - Outlier 찾아내기  (0) 2021.06.11
R # airquality - 선형회귀모델  (0) 2021.05.27
R - ANOVA(아노바) / PlantGrowth (ANOVA, Tukey HSD)  (0) 2021.05.23
R - 비율검정  (0) 2021.05.13