A neural network is a computational system frequently employed in machine learning to create predictions based on existing data.
A typical neural network consists of:
- Input layers: Layers that take inputs based on existing data
- Hidden layers: Layers that use backpropagation to optimise the weights of the input variables in order to improve the predictive power of the model
- Output layers: Output of predictions based on the data from the input and hidden layers
Model Background
The below neural network is used to predict sales figures, using the following input variables:
- Income
- Age
- Gender
- Relationship
- Education
Firstly, the data is loaded into R:
#Directory
setwd("directory")
mydata <- read.csv("file path")
attach(mydata)
Since our data for variables such as Gender is in text format, i.e. "Male", "Female", these variables are converted into numerical format as per the below:
#Numerical Labelling
GenderN<-as.numeric(Gender)
RelationshipN<-as.numeric(Relationship)
EducationN<-as.numeric(Education)
#Data Frame
df<-data.frame(Sales,Age,GenderN,EducationN,RelationshipN,Income)
Data Normalization
One of the most important procedures when forming a neural network is normalization of the data, i.e. adjusting the data to a common scale so that the predicted values of the neural network can be accurately compared to that of the actual data. Failure to normalize the data will typically result in the prediction value remaining the same across all observations regardless of the input. To prevent this, the data must be normalized.
We can choose to do this in two ways in R:
- Scale the data frame automatically using the scale function in R
- Transform the data using what is called a max-min normalization technique
For the purposes of this tutorial, both are run but we choose to use the max-min normalization technique.
#Scaled Normalization
scaleddata<-scale(df)
#Max-Min Normalization
salesscaled=(Sales-min(Sales))/(max(Sales)-min(Sales))
agescaled=(Age-min(Age))/(max(Age)-min(Age))
incomescaled=(Income-min(Income))/(max(Income)-min(Income))
genderscaled=(GenderN-min(GenderN))/(max(GenderN)-min(GenderN))
educationscaled=(EducationN-min(EducationN))/(max(EducationN)-min(EducationN))
relationshipscaled=(RelationshipN-min(RelationshipN))/(max(RelationshipN)-min(RelationshipN))
maxmindata<-data.frame(salesscaled,incomescaled,agescaled,genderscaled,educationscaled,
relationshipscaled)
Using sales as an example, scaling the variable with max-min normalisation has rescaled our sales variable to a number between 0 and 1:
Training and Test Data
With a neural network (as with most other machine learning techniques), the purpose of any machine learning algorithm is to 1) create predictions based on a dataset and 2) test the accuracy of those predictions against a control dataset.
The control dataset is set up by splitting the whole dataset into two. Our training data (trainset) is based on the first 500 observations, and the test data (testset) is based on the remainder of observations.
#Training and Test Data
trainset <- maxmindata[1:500, ]
testset <- maxmindata[501:963, ]
Neural Network
To set up the neural network, the neuralnet library is loaded into R and from the code below, observe that we are:
- Using neuralnet to "regress" the dependent salesscaled variable against the other independent variables
- Setting the number of hidden layers to 2 based on the hidden=2 formula
- The linear.output variable is set to FALSE, given the impact of the independent variables on the dependent variable (sales) is assumed to be non-linear
Note that the process of deciding on the number of hidden layers in a neural network is not an exact science. As a matter of fact, there are instances where accuracy will likely be higher without any hidden layers. Therefore, trial and error plays a significant role in choosing the number of hidden layers. One possibility is to compare how the accuracy of the predictions change as the number of hidden layers are modified, resulting in a more systematic means of accurately choosing the number of hidden layers.
#Neural Network
library(neuralnet)
salesscalednet <- neuralnet(salesscaled~incomescaled+genderscaled+agescaled+
educationscaled+relationshipscaled, data=trainset, hidden=2, linear.output=FALSE,
threshold=0.1)
salesscalednet$result.matrix
plot(salesscalednet)
Our neural network looks like this:
Moreover, the error of the neural network model as well as the weights between the inputs, hidden layers, and outputs are also printed:
Accuracy Testing
As already mentioned, our neural network has been created on the training data, which is then compared to the test data to gauge the accuracy of the neural network forecast. In the below:
- The "subset" function is used to eliminate the dependent variable from the test data
- The "compute" function then creates the prediction variable
- A "results" variable then compares the predicted data with the actual data
- A confusion matrix is then created with the table function to compare the number of true/false positives and negatives
#Test the resulting output
temp_test <- subset(testset, select =c("incomescaled","genderscaled","agescaled","educationscaled","relationshipscaled"))
head(temp_test)
salesscalednet.results <- compute(salesscalednet, temp_test)
#Accuracy
results <- data.frame(actual = testset$salesscaled, prediction = salesscalednet.results$net.result)
results
roundedresults<-sapply(results,round,digits=0)
roundedresultsdf=data.frame(roundedresults)
attach(roundedresultsdf)
table(actual,prediction)
The predicted results are compared to the actual results:
Then, a confusion matrix is created to compare the number of true/false positives and negatives:
Conclusion
Ultimately, certain types of datasets will be more suited to neural networking than others. For instance, in the results that were obtained above, the number of true positives and negatives constituted roughly 60% of all the predictions.
While experimenting with the data through modifying the number of hidden layers, this accuracy rate was more or less consistent. Therefore, there are situations where a certain segment of data might show better predictive power with another model, e.g. logistic regression. However, certain types of data could be highly suited to a neural network and therefore show much higher accuracy rates.
Ultimately, making predictions using neural network analysis involves a lot of trial and error, and you will invariably find that certain data is better suited to this forecasting method than others.









