Question: What's wrong with my R code? # Load necessary package library ( neuralnet ) # Load the spam data ( assuming the file is in

What's wrong with my R code? # Load necessary package
library(neuralnet)
# Load the spam data (assuming the file is in the current working directory)
data <- read.csv("spam_train.csv", header = TRUE, stringsAsFactors = FALSE)
# ------------------
# Data processing
# ------------------
# No specific columns need to be removed
# Ensure the features are scaled for better neural network performance
data[,1:8]<- scale(data[,1:8])
# Build a formula for the neural network
n <- names(data)
f <- as.formula(paste("spam ~", paste(n[!n %in% "spam"], collapse ="+")))
# -------------------
# Question 1: One hidden layer with 5 neurons
# -------------------
nn.fit1<- neuralnet(f, data = data, hidden =5, linear.output = FALSE)
plot(nn.fit1) # Plot the first network
# -------------------
# Question 2: Two hidden layers with 5 and 3 neurons
# -------------------
nn.fit2<- neuralnet(f, data = data, hidden = c(5,3,3), linear.output = FALSE, stepmax =1e6)
plot(nn.fit2) # Plot the second network
# If you encounter issues with convergence, try reducing the complexity of the network:
# Simplified network for better convergence:
# nn.fit2<- neuralnet(f, data = data, hidden = c(5,3), linear.output = FALSE, stepmax =1e6, threshold =0.01)
# -------------------
# Evaluate the second network on the training data
# -------------------
pred <- compute(nn.fit2, data[,1:8])$net.result
# Convert probabilities to binary output
pred1<- ifelse(pred >0.5,1,0)
# Calculate True Positive Rate (TPR) and False Positive Rate (FPR)
TP.case <- which(pred1+ data$spam ==2)
TP <- length(TP.case)
T.case <- which(data$spam ==1)
T.actual <- length(T.case)
TP.rate <- TP / T.actual
FP.case <- which(pred1- data$spam ==1)
FP <- length(FP.case)
F.case <- which(data$spam ==0)
F.actual <- length(F.case)
FP.rate <- FP / F.actual
# Output the performance metrics
TP.rate
FP.rate
Purpose: Question 1. Construct an ANN with one hidden layer, and the hidden layer has 5 nodes. Plot the
constructed network below:
Question 2
Construct another ANN with two hidden layers. The first hidden layer has 5 nodes and
the second hidden layer has 5 nodes. Do you think the second ANN will perform better
than the first ANN constructed in Question 1? And why?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!