Ex1 Use the nnet package to analyze the iris data set. Use 80% of the 150 samples as the training data and the rest for validation. Discuss the results.

# Load the nnet package
library(nnet)
## Warning: package 'nnet' was built under R version 4.2.2
# Load the Iris dataset
data(iris)

# Set the seed for reproducibility
set.seed(42)

# Split the data into training and validation sets
train_indices <- sample(1:nrow(iris), 0.8 * nrow(iris))
train_data <- iris[train_indices, ]
validation_data <- iris[-train_indices, ]

# Train the neural network
model <- nnet(Species ~ ., data = train_data, size = 5)
## # weights:  43
## initial  value 150.821363 
## iter  10 value 40.019733
## iter  20 value 4.662065
## iter  30 value 2.510986
## iter  40 value 0.359209
## iter  50 value 0.099650
## iter  60 value 0.002319
## final  value 0.000030 
## converged
# Predict the classes for the validation set
predicted_classes <- predict(model, newdata = validation_data, type = "class")

# Compare the predicted classes to the actual classes
accuracy <- sum(predicted_classes == validation_data$Species) / nrow(validation_data)
print(paste("Validation Accuracy:", accuracy))
## [1] "Validation Accuracy: 0.933333333333333"

The model was good enough and can say that it was to accurate predict the species well. It is not as high though as KNN which was at 96%.