#logistic Regression # Install the 'caret' package (only run once; comment out if already installed) install.packages("caret") # Load the 'caret' package for machine learning utilities library(caret) # Load the built-in iris dataset data(iris) # Convert the problem into binary classification: # Setosa (1) vs Non-Setosa (0) iris$Label <- ifelse(iris$Species == "setosa", 1, 0) # Remove the original Species column as it's no longer needed iris <- iris[, -5] # Set seed for reproducibility set.seed(123) # Split the data: 80% for training and 20% for testing idx <- createDataPartition(iris$Label, p = 0.8, list = FALSE) train <- iris[idx, ] # Training set test <- iris[-idx, ] # Test set # Train a logistic regression model using the training data model <- glm(Label ~ ., data = train, family = "binomial") # Predict probabilities on the test set and convert to class labels (1 or 0) pred <- ifelse(predict(model, test, type = "response") > 0.5, 1, 0) # Generate a confusion matrix to evaluate model performance conf <- confusionMatrix(factor(pred), factor(test$Label)) # Display evaluation metrics cat("Precision:", round(conf$byClass["Precision"], 2), "\n") cat("Recall:", round(conf$byClass["Recall"], 2), "\n") cat("F1-score:", round(conf$byClass["F1"], 2), "\n")