Neural Networks using the R nnet Package

I wrote an article titled “Neural Networks using the R nnet Package” in the November 2016 issue of Visual Studio Magazine. See

A neural network is a software system that can use data to make predictions. For example, a neural network classifier could predict the voting behavior (Democratic, Republican, Other) of a person based on their age, annual income, and sex.


The R language has been around for a long time and is intended mostly for ad hoc interactive analyses using classical statistics techniques such as the t-test, ANOVA, and chi-square tests. Because R is an open source language, there are hundreds of add-on libraries (called packages in R terminology). One such package is named nnet and it can create neural networks.

In my article I demonstrate how to use the nnet package on the classic Fisher’s Iris Data where the goal is to predict the species (setosa, versicolor, virginica) of an iris flower based on petal length and width and sepal (a leaf-like structure) length and width.

Some of the key commands are:

cat("\nCreating and training a neural network . . \n")

mynn = nnet(Species ~ ., data=irisdf, subset = sampidx,
  size=2, decay=1.0e-5, maxit=50)

cm = table(irisdf$Species[-sampidx], predict(mynn,
  irisdf[-sampidx, ], type="class"))

cat("\nConfusion matrix for resulting nn model is: \n")


If you’re not familiar with R, the code above probably looks pretty ugly. R is very quirky with regards to syntax and when I switch from using a common C-family language (C, C#, Java, Python, JavaScript, etc.) to R, it always takes me a while.

The R nnet package is good but not great. The main advantage is that, once you’ve gotten over a non-trivial learning curve, nnet is well-integrated with other R functions.

This entry was posted in Machine Learning, R Language. Bookmark the permalink.

2 Responses to Neural Networks using the R nnet Package

  1. Interesting article but I think you meant “add-on” libraries πŸ˜‰

Comments are closed.