본문 바로가기

자격증/빅데이터 분석기사

랜덤포레스트 in R

 

 

타이타닉 생존자를 분류하는 분석 전체 코드

library(dplyr)
library(ggplot2)
# install.packages("randomForest")
library(randomForest)

df <- read.csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv",stringsAsFactors=TRUE)

# 데이터 전처리
df$Age <- ifelse(is.na(df$Age),mean(df$Age,na.rm=TRUE),df$Age)
df$Embarked <- replace(df$Embarked,df$Embarked=="","S")
df$Sex <- as.numeric(factor(df$Sex),level=c("male","female"))   # male = 1, female = 2 로 레이블 인코딩
df$Embarked <- as.numeric(factor(df$Embarked),level=c("C","Q","S"))

df$Familysize <- df$SibSp + df$Parch

# 데이터셋 재구성
df <- df[,c("Survived","Pclass","Sex","Age","Fare","Embarked","Familysize")]

# trian, test 분리
set.seed(123)
idx <- sample(1:nrow(df),0.8 * nrow(df))

train <- df[idx,]     # 독립변수 + 종속변수
test <- df[-idx,]     # 독립변수 + 종속변수


# 모델 적합
train$Survived <- as.factor(train$Survived)    # ★ train 의 Survived 값을 as.factor()를 통해 범주화 한다 !!!!
model <- randomForest(Survived~.,data=train)
pred <- predict(model,newdata=test,type="class")    #  ★ 랜덤포레스트 예측할 때, type = "class" 지정 !!

cm <- table(test$Survived,pred)
cm

acc <- (cm[1,1] + cm[2,2]) / nrow(test)
acc

 

혼동행렬과 정확도

 

 

  • 랜덤포레스트 분류모델을 위한 패키지 : library(randomForest)
  • 랜덤포레스트 분류모델을 위한 함수 : randomForest( )
  • 범주형 변수 레이블 인코딩 수행
  • 모델 학습시 (독립변수 + 종속변수) 데이터셋 사용
  • 모델 학습 전에 train 데이터셋의 Survived 변수에 대해 as.factor 함수를 적용한다.
  • 모델 예측시, type = "class" 지정

 

 

type ="class" 는 type="response" 와 같다 !!

분류에 사용되는 랜덤포레스트는 type 에 "reponse"를 지정해준다.

 

참고 : https://search.r-project.org/CRAN/refmans/randomForest/html/predict.randomForest.html

'자격증 > 빅데이터 분석기사' 카테고리의 다른 글

다중선형회귀분석 in R  (0) 2022.11.26
단순선형회귀분석 in R  (0) 2022.11.26
로지스틱회귀(분류) in R  (0) 2022.11.25
SVM in R  (0) 2022.11.25
KNN in R  (0) 2022.11.25