iris 품종을 분류하는 분석 전체 코드
library(dplyr)
library(ggplot2)
library(nnet)
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[1:4],normal))
str(df_new)
# train, test 데이터셋 분리
set.seed(123)
idx <- sample(1:nrow(df_new),0.8*nrow(df_new))
train <- df_new[idx,] # 독립변수 + 종속변수
test <- df_new[-idx,] # 독립변수 + 종속변수
# 로지스틱 회귀모델 학습
model <- multinom(formula=species~.,data = train) # ★ 로지스틱 회귀모델 : multinom 함수
fitted(model)
# 모델평가 - 오차행렬
pred <- predict(model, newdata=test, type="class")
correct_model <- sum(pred == test$species) / nrow(test)
cm <- xtabs(~pred + test$species)
cm
# 모델평가 - 정확도
acc <- (cm[1,1] + cm[2,2] + cm[3,3]) / nrow(test)
혼동행렬
- 로지스틱 회귀분류를 위한 패키지 : library(nnet)
- 로지스틱 회귀분석을 위한 함수 : multinom()
- 모델훈련에 (독립변수 + 종속변수) 데이터셋을 사용한다.
- xtabs() 를 이용하여 혼동행렬을 구한다.