#종속변수 : Type
nrow(Glass) #214
ncol(Glass) #10
colSums(is.na(Glass)) #결측치 확인
# 2. 종속변수의 데이터 비율
table(Glass$Type)
# 1 2 3 5 6 7
# 70 76 17 13 9 29
prop.table(table(Glass$Type))
# 1 2 3 5 6 7
# 0.32710280 0.35514019 0.07943925 0.06074766 0.04205607 0.13551402
# 3. 데이터 스케일링 (최대최소 정규화)
Glass2 <- Glass[, c(-10)] # 정답type 제외 (-10왜?******)
normalize <- function(x) { return((x - min(x)) / (max(x) - min(x))) }
Glass_n <- as.data.frame(lapply(Glass2, normalize))
summary(Glass_n)
# 3단계: 모델 훈련
# 훈련 데이터와 테스트 데이터를 분리합니다. 90% 학습, 10% 시험
set.seed(10)
train_indx <- createDataPartition(iris$Species, p = 0.9, list = FALSE)
train_indx
# 기계를 학습 시킬 훈련 데이터와 테스트 데이터 생성
Glass_train <- Glass_n[train_indx, ]
Glass_test <- Glass_n[-train_indx, ]
nrow(Glass_train) # 135
nrow(Glass_test) # 79
# 기계를 학습 시킬 훈련 데이터의 정답과 테스트 데이터의 정답 생성
Glass_train_label <- Glass$Type[train_indx]
Glass_test_label <- Glass$Type[-train_indx]
length(Glass_train_label) # 161
length(Glass_test_label) # 16
# 4단계: 모델 성능 평가
accuracies <- data.frame(k = integer(), accuracy = numeric())
set.seed(20)
for (i in seq(1, 57, 2)) {
result1 <- knn(train = Glass_train, test = Glass_test, cl = Glass_train_label, k = i)
accuracy <- sum(result1 == Glass_test_label) / length(Glass_test_label) * 100
accuracies <- rbind(accuracies, data.frame(k = i, accuracy = accuracy))
print(paste(i, '개 일때 정확도 ', accuracy)) }
# 정확도 데이터 프레임 확인
accuracies
# plotly로 라인 그래프 시각화
fig <- plot_ly(accuracies, x = ~k, y = ~accuracy, type = 'scatter', mode = 'lines+markers', line = list(color = 'tomato'))
fig <- fig %>% layout(title = "K 값에 따른 정확도",
xaxis = list(title = "K 값"),
yaxis = list(title = "정확도"))
fig