1. iris 품종을 분류하는 분석 전체 코드
library(dplyr)
library(ggplot2)
# knn 분류모델을 위한 패키지 임포트
library(class)
df <- read.csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv")
summary(df)
df_new <- df
# Min-Max 정규화
normal <- function(x){
return((x-min(x))/(max(x)-min(x)))
}
df_new[1:4] <- as.data.frame(lapply(df_new[,-5],normal))
# train, test 분리 (8:2)
set.seed(123)
idx <- sample(1:nrow(df_new),0.8*nrow(df_new))
train <- df_new[idx,-5] # 독립변수
test <- df_new[-idx,-5] # 독립변수
train_sp <- df_new[idx,5] # 종속변수
test_sp <- df_new[-idx,5] # 종속변수
# knn 함수를 이용한 knn 학습
model <- knn(train=train,test=test,cl=train_sp,k=3) # ★ predict() 사용 안함!
table(factor(model)) # 분류결과 확인
# 모델평가 - 혼동행렬
cm <- table(test_sp,model)
cm
# 모델평가 - 정확도
acc <- (cm[1,1] + cm[2,2] + cm[3,3]) / nrow(test)
2. 타이타닉 생존자를 분류하는 분석 전체 코드
library(dplyr)
library(ggplot2)
library(class)
titanic<- read.csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv",stringsAsFactors=TRUE)
summary(titanic)
df <- titanic
# 데이터 전처리
# 결측값 대치
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 <- ifelse(df$Sex=="female",2,1)
df$Embarked <- as.numeric(factor(df$Embarked),level=c("C","Q","S"))
# 파생변수 Familysize 생성
df$Familysize <- df$SibSp + df$Parch
# 분석을 위한 컬럼 선택
df <- df[,c("Survived","Pclass","Sex","Age","Familysize","Fare","Embarked")]
# train, test 분리 (8:2)
set.seed(123)
idx <- sample(1:nrow(df), 0.8*nrow(df))
train <- df[idx,-1] # 독립변수
test <- df[-idx,-1] # 독립변수
train_sp <- df[idx,1] # 종속변수
test_sp <- df[-idx,1] # 종속변수
# knn 함수를 이용한 knn 알고리즘 학습
model <- knn(train=train, test=test, cl=train_sp, k=3)
table(factor(model))
# 모델평가
cm <- table(test_sp,model)
acc <- (cm[1,1]+cm[2,2]) / nrow(test)
acc
- KNN 분류모델을 위한 라이브러리 : library(class)
- KNN 분류모델을 위한 함수 : knn()
- 모델 훈련시 독립변수와 종속변수를 분리하여 넣는다 !!!
- 의사결정나무 분류와 다르게 predict( ) 함수를 사용하지 않음.