library(class)
library(gmodels)
# Загрузка и нормализация данных
data(iris)
normalize <- function(x) {
(x - min(x)) / (max(x) - min(x))
}
iris_norm <- as.data.frame(lapply(iris[, 1:4], normalize))
# Разделение выборки
set.seed(123)
index <- sample(1:nrow(iris), size = 0.7 * nrow(iris))
train_data <- iris_norm[index, ]
test_data <- iris_norm[-index, ]
train_labels <- iris[index, 5]
test_labels <- iris[-index, 5]
# Обучение модели k-NN
knn_pred <- knn(train = train_data, test = test_data, cl = train_labels, k = 3)
# Оценка модели
CrossTable(x = test_labels, y = knn_pred, prop.chisq = FALSE)
##
##
## Cell Contents
## |-------------------------|
## | N |
## | N / Row Total |
## | N / Col Total |
## | N / Table Total |
## |-------------------------|
##
##
## Total Observations in Table: 45
##
##
## | knn_pred
## test_labels | setosa | versicolor | virginica | Row Total |
## -------------|------------|------------|------------|------------|
## setosa | 14 | 0 | 0 | 14 |
## | 1.000 | 0.000 | 0.000 | 0.311 |
## | 1.000 | 0.000 | 0.000 | |
## | 0.311 | 0.000 | 0.000 | |
## -------------|------------|------------|------------|------------|
## versicolor | 0 | 17 | 1 | 18 |
## | 0.000 | 0.944 | 0.056 | 0.400 |
## | 0.000 | 0.944 | 0.077 | |
## | 0.000 | 0.378 | 0.022 | |
## -------------|------------|------------|------------|------------|
## virginica | 0 | 1 | 12 | 13 |
## | 0.000 | 0.077 | 0.923 | 0.289 |
## | 0.000 | 0.056 | 0.923 | |
## | 0.000 | 0.022 | 0.267 | |
## -------------|------------|------------|------------|------------|
## Column Total | 14 | 18 | 13 | 45 |
## | 0.311 | 0.400 | 0.289 | |
## -------------|------------|------------|------------|------------|
##
##
# Матрица ошибок и диагональная точность
conf_matrix <- table(Predicted = knn_pred, Actual = test_labels)
accuracy <- sum(diag(conf_matrix)) / sum(conf_matrix)
conf_matrix
## Actual
## Predicted setosa versicolor virginica
## setosa 14 0 0
## versicolor 0 17 1
## virginica 0 1 12
cat("Прогнозирование качества диагонали:", round(accuracy, 3), "\n")
## Прогнозирование качества диагонали: 0.956
library(e1071)
# Разделение данных
set.seed(123)
index <- sample(1:nrow(iris), size = 0.7 * nrow(iris))
train <- iris[index, ]
test <- iris[-index, ]
# Линейный SVM с 10-кратной кросс-проверкой
svm_model <- svm(Species ~ ., data = train, kernel = "linear", cross = 10)
# Предсказание и оценка
svm_pred <- predict(svm_model, newdata = test)
conf_matrix_svm <- table(Predicted = svm_pred, Actual = test$Species)
accuracy_svm <- sum(diag(conf_matrix_svm)) / sum(conf_matrix_svm)
conf_matrix_svm
## Actual
## Predicted setosa versicolor virginica
## setosa 14 0 0
## versicolor 0 17 0
## virginica 0 1 13
cat("SVM Прогнозирование качества диагонали:", round(accuracy_svm, 3), "\n")
## SVM Прогнозирование качества диагонали: 0.978
library(vegan)
# PCA с использованием функции rda
iris_pca <- rda(iris[, 1:4], scale = TRUE)
# Ординационная диаграмма
plot(iris_pca, type = "n", main = "PCA of Iris Dataset")
points(iris_pca, display = "sites", col = as.numeric(iris$Species), pch = 19)
legend("topright", legend = levels(iris$Species), col = 1:3, pch = 19)
# Сводка PCA
summary(iris_pca)
##
## Call:
## rda(X = iris[, 1:4], scale = TRUE)
##
## Partitioning of correlations:
## Inertia Proportion
## Total 4 1
## Unconstrained 4 1
##
## Eigenvalues, and their contribution to the correlations
##
## Importance of components:
## PC1 PC2 PC3 PC4
## Eigenvalue 2.9185 0.9140 0.14676 0.020715
## Proportion Explained 0.7296 0.2285 0.03669 0.005179
## Cumulative Proportion 0.7296 0.9581 0.99482 1.000000
Модель k-NN продемонстрировала высокую точность классификации (более 95%).
Метод SVM с линейным ядром также показал хорошую способность к классификации, особенно после кросс-проверки.
PCA позволил визуально выделить кластеры по видам, особенно setosa, подтверждая различия между видами по морфологическим признакам.