library(nnet)

Ex. 1 – Use the nnet package to analyze the iris dataset. Use 80% of the 150 samples as the training data and the rest for validation. Discuss the results.

set.seed(1212)

train_index <- sample(seq_len(150), size =120) #generate random index separating iris into specified samples
train <- iris[train_index,] #training data
test <- iris[-train_index,] #test data

test_cat <- iris[-train_index, 5]  #true designations for test

iris_m <- nnet(formula = Species ~., data = iris, size = 1) #size is the number of units in the hidden layer
## # weights:  11
## initial  value 162.824356 
## iter  10 value 50.964172
## iter  20 value 15.565706
## iter  30 value 7.675196
## iter  40 value 6.366598
## iter  50 value 5.978327
## iter  60 value 5.973796
## iter  70 value 5.963804
## iter  80 value 5.963678
## iter  90 value 5.963136
## final  value 5.962275 
## converged
iris_predict <- predict(iris_m, test, type = 'class')


100*round(table(iris_predict, test_cat)/30,3)
##             test_cat
## iris_predict setosa versicolor virginica
##   setosa       36.7        0.0       0.0
##   versicolor    0.0       40.0       0.0
##   virginica     0.0        0.0      23.3

Using only 1 hidden layer, the neural net model generated by nnet offers a very accurate model.