# 2025-06-12
# install.packages("sparsevctrs", dependencies = TRUE)
# install.packages("hardhat", dependencies = TRUE)
# install.packages("recipes", dependencies = TRUE)
# install.packages("caret", dependencies = TRUE)
library(caret)
## Loading required package: ggplot2
## Loading required package: lattice
# 1. 필요한 패키지 로드
library(mlbench)
# Sonar 데이터셋
library(caret)
library(rpart)
# 2. 데이터 로드
data(Sonar)
# 모델 학습 및 평가
# 의사결정나무 모델
set.seed(123) # 재현 가능성 확보
# 3. 데이터 분할 (75% train, 25% test)
index <- createDataPartition(Sonar$Class, p = 0.75, list = FALSE)
train_data <- Sonar[index, ]
test_data <- Sonar[-index, ]
# 4. 분류 모델 학습 (의사결정나무 사용)
model <- train(Class ~ ., data = train_data, method = "rpart")
# 5. 예측
pred <- predict(model, newdata = test_data)
# 6. 혼동행렬 생성
conf_matrix <- confusionMatrix(pred, test_data$Class)
print(conf_matrix)
## Confusion Matrix and Statistics
##
## Reference
## Prediction M R
## M 19 7
## R 8 17
##
## Accuracy : 0.7059
## 95% CI : (0.5617, 0.8251)
## No Information Rate : 0.5294
## P-Value [Acc > NIR] : 0.007812
##
## Kappa : 0.4111
##
## Mcnemar's Test P-Value : 1.000000
##
## Sensitivity : 0.7037
## Specificity : 0.7083
## Pos Pred Value : 0.7308
## Neg Pred Value : 0.6800
## Prevalence : 0.5294
## Detection Rate : 0.3725
## Detection Prevalence : 0.5098
## Balanced Accuracy : 0.7060
##
## 'Positive' Class : M
##
#TP (True Positive) = 19 : 실제 M을 M으로 정확히 예측
#FP (False Positive) = 7 : 실제 R인데 M으로 잘못 예측
#FN (False Negative) = 8 : 실제 M인데 R으로 잘못 예측
#TN (True Negative) = 17 : 실제 R을 R으로 정확히 예