Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.1 kB
1
Indexable
Never
# Load libraries
library(iris)

# Separate features and target variable
data <- iris[, 1:4]
target <- iris$Species

# Split data into training and testing sets
set.seed(123)  # for reproducibility
split_ratio <- 0.75
train_index <- sample(1:nrow(data), size = nrow(data) * split_ratio)
train_data <- data[train_index, ]
train_target <- target[train_index]
test_data <- data[-train_index, ]
test_target <- target[-train_index]

# Choose k value for KNN (experiment with different values)
k <- 5

# Train KNN model
knn_model <- knn(train = train_data, cl = train_target, k = k)

# Predict species on test data
predicted_species <- knn$predict(knn_model, newdata = test_data)

# Evaluate model accuracy
confusion_matrix <- table(test_target, predicted_species)
accuracy <- sum(diag(confusion_matrix)) / nrow(confusion_matrix)
cat("Accuracy:", round(accuracy, 3) * 100, "%")

# Predict a new flower example
new_flower <- c(4.5, 2.3, 1.3, 0.3)
predicted_species_new <- knn$predict(knn_model, newdata = new_flower)
cat("Predicted species for new flower:", predicted_species_new)
Leave a Comment