library(imager) library(dplyr) library(caret) library(nnet) library(ggplot2) library(lattice)
base_path <-“C:/Users/admin/OneDrive/Documents/DATASET/Data” folders <- c(“CRAB”, “JELLYFISH”, “LOBSTER”, “OCTOPUS”,“PENGUIN”,“SHARK”,“STARFISH”,“WHALE”)
load_images <- function(folder) { folder_path <- file.path(base_path, folder) # Construct full path to the folder images <- list.files(folder_path, pattern = “\.jpg\(|\\.png\)”, full.names = TRUE) # List all images
# Standard dimensions for resizing standard_width <- 64 standard_height <- 64
image_list <- lapply(images, function(img_path) { img <- load.image(img_path) # Load the image
# Convert to grayscale if the image has 3 channels (RGB)
if (spectrum(img) == 3) {
img <- grayscale(img)
}
# Resize the image to standard dimensions (64x64)
img <- resize(img, standard_width, standard_height)
# Flatten the image into a single vector for further processing
as.vector(img)
})
# Combine image vectors into a matrix and add corresponding labels image_data <- do.call(rbind, image_list) labels <- rep(folder, length(images)) # Create a label for each image return(data.frame(image_data, label = labels, stringsAsFactors = FALSE)) # Return as data frame }
CRAB_data <- load_images(“Crabs”) JELLYFISH_data <- load_images(“JellyFish”) LOBSTER_data <- load_images(“Lobster”) OCTOPUS_data <- load_images(“OCTOPUS”) SHARK_data <- load_images(“SHARKs”) STARFISH_data <- load_images(“STARFISH”) WHALE_data <- load_images(“WHALE”)
str(CRAB_data) # Replace with any other data frame as needed na_rows <- sapply(CRAB_data[, 1:4097], function(x) any(is.na(as.numeric(x)))) na_columns <- which(na_rows) na_columns
CRAB_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255 JELLYFISH_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255 LOBSTER_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255 OCTOPUS_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255 SHARK_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255 STARFISH_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255 WHALE_data_numeric <- as.data.frame(lapply(CRAB_data[, 1:4097], function(x) suppressWarnings(as.numeric(x)))) / 255
CRAB_data_numeric <- CRAB_data_numeric[, 1:4097] JELLYFISH_data_numeric <- JELLYFISH_data_numeric[, 1:4097] LOBSTER_data_numeric <- LOBSTER_data_numeric[, 1:4097] OCTOPUS_data_numeric <- OCTOPUS_data_numeric[, 1:4097] SHARK_data_numeric <- SHARK_data_numeric[, 1:4097] STARFISH_data_numeric <- STARFISH_data_numeric[, 1:4097] WHALE_data_numeric <- WHALE_data_numeric[, 1:4097]
colnames(CRAB_data_numeric) <- paste0(“X”, 1:4096) colnames(JELLYFISH_data_numeric) <- paste0(“X”, 1:4096) colnames(LOBSTER_data_numeric) <- paste0(“X”, 1:4096) colnames(OCTOPUS_data_numeric) <- paste0(“X”, 1:4096) colnames(SHARK_data_numeric) <- paste0(“X”, 1:4096) colnames(STARFISH_data_numeric) <- paste0(“X”, 1:4096) colnames(WHALE_data_numeric) <- paste0(“X”, 1:4096)
combined_data <- rbind(CRAB_data_numeric, JELLYFISH_data_numeric, LOBSTER_data_numeric, OCTOPUS_data_numeric, SHARK_data_numeric, STARFISH_data_numeric, WHALE_data_numeric)
dim(combined_data) # Should reflect total number of images and 4096 features
combined_data$label <- factor(c(rep(“Crab”, nrow(CRAB_data_numeric)), rep(“Jellyfish”, nrow(JELLYFISH_data_numeric)), rep(“Lobster”, nrow(LOBSTER_data_numeric)), rep(“Octopus”, nrow(OCTOPUS_data_numeric)), rep(“Shark”, nrow(SHARK_data_numeric)), rep(“Starfish”, nrow(STARFISH_data_numeric)), rep(“Whale”, nrow(WHALE_data_numeric))))
set.seed(123)
train_indices <- sample(1:nrow(combined_data), size = 0.7 * nrow(combined_data)) train_data <- combined_data[train_indices, ] # Training data test_data <- combined_data[-train_indices, ] # Test data
train_data <- as.data.frame(lapply(train_data, function(x) if(is.character(x)) factor(x) else x))
train_data[, -which(names(train_data) == “label”)] <- lapply(train_data[, -which(names(train_data) == “label”)], as.numeric)
train_data\(label <- as.factor(train_data\)label)
train_data\(label <- as.factor(train_data\)label) test_data\(label <- as.factor(test_data\)label)
logistic_model <- glm(label ~ ., data = train_data, family = “binomial”)
summary(logistic_model)
predicted_probabilities <- predict(logistic_model, newdata = test_data, type = “response”)
predicted_classes <- ifelse(predicted_probabilities > 0.5, “1”, “0”) # Adjust thresholds as necessary
confusion_matrix <- table(test_data$label, predicted_classes) print(confusion_matrix)
accuracy <- sum(diag(confusion_matrix)) / sum(confusion_matrix) print(paste(“Accuracy:”, round(accuracy * 100, 2), “%”))
pca_result <- prcomp(train_data[, -which(names(train_data) == “label”)], center = TRUE, scale. = TRUE)
zero_variance_cols_final <- sapply(train_data_filtered[, -which(names(train_data_filtered) == “label”)], function(x) var(x, na.rm = TRUE) == 0) zero_variance_column_names_final <- names(train_data_filtered)[-which(names(train_data_filtered) == “label”)][zero_variance_cols_final]
print(zero_variance_column_names_final)
if (length(zero_variance_column_names_final) > 0) { train_data_filtered <- train_data_filtered[, !(names(train_data_filtered) %in% zero_variance_column_names_final)] }
zero_variance_cols_after_removal <- sapply(train_data_filtered[, -which(names(train_data_filtered) == “label”)], function(x) var(x, na.rm = TRUE) == 0) zero_variance_column_names_after_removal <- names(train_data_filtered)[-which(names(train_data_filtered) == “label”)][zero_variance_cols_after_removal]
print(zero_variance_column_names_after_removal)
if (length(zero_variance_column_names_after_removal) == 0) { pca_result <- prcomp(train_data_filtered[, -which(names(train_data_filtered) == “label”)], center = TRUE, scale. = TRUE) } else { stop(“There are still zero variance columns in the dataset. PCA cannot be performed.”) }
pca_variance <- cumsum(pca_result\(sdev^2) / sum(pca_result\)sdev^2)
plot(pca_variance, xlab = “Number of Components”, ylab = “Cumulative Explained Variance”, type = “b”, main = “Cumulative Explained Variance by Principal Components”)
train_data_pca <- data.frame(pca_result\(x[, 1:20]) # Use the first 20 principal components train_data_pca\)label <- train_data$label # Add back the label
test_data_pca <- predict(pca_result, newdata = test_data[, -which(names(test_data) == “label”)]) test_data_pca <- data.frame(test_data_pca[, 1:20]) # Use the same number of components as training data test_data_pca\(label <- test_data\)label # Add back the label for evaluation
model <- multinom(label ~ ., data = train_data)
summary(model)
predicted_probabilities <- predict(model, newdata = test_data_pca, type = “prob”)
predicted_classes <- apply(predicted_probabilities, 1, function(x) { levels(train_data_pca$label)[which.max(x)] })
predicted_classes <- factor(predicted_classes, levels = levels(test_data$label))
actual_labels <- factor(test_data\(label, levels = levels(test_data\)label))
confusion_matrix <- table(actual_labels, predicted_classes)
confusion_results <- confusionMatrix(predicted_classes, actual_labels) print(confusion_results)
accuracy <- sum(diag(confusion_matrix)) / sum(confusion_matrix) print(paste(“Accuracy:”, accuracy))
precision <- numeric(nrow(confusion_matrix)) recall <- numeric(nrow(confusion_matrix)) f1_score <- numeric(nrow(confusion_matrix))
for (i in 1:nrow(confusion_matrix)) { TP <- confusion_matrix[i, i] # True Positives FP <- sum(confusion_matrix[, i]) - TP # False Positives FN <- sum(confusion_matrix[i, ]) - TP # False Negatives
precision[i] <- TP / (TP + FP) # Calculate precision recall[i] <- TP / (TP + FN) # Calculate recall
# Calculate F1 Score f1_score[i] <- 2 * (precision[i] * recall[i]) / (precision[i] + recall[i]) }
for (i in 1:nrow(confusion_matrix)) { cat(“:”, rownames(confusion_matrix)[i], “”) cat(“Precision:”, precision[i], “”) cat(“Recall:”, recall[i], “”) cat(“F1 Score:”, f1_score[i], “”) }
macro_f1 <- mean(f1_score, na.rm = TRUE) cat(“F1 Score:”, macro_f1, “”)