---
title: "Simple Neural Network Classifiers"
author: "Shane T. Mueller shanem@mtu.edu"
date: "`r Sys.Date()`"
output:
  rmdformats::readthedown:
    gallery: yes
    highlight: kate
    self_contained: no
  html_document:
    
    df_print: paged
  pdf_document: default
  word_document:
    reference_docx: ../template.docx
always_allow_html: yes
---


```{r knitr_init, echo=FALSE, cache=FALSE}
library(knitr)
library(rmdformats)

## Global options
options(max.print="75")
opts_chunk$set(echo=TRUE,
	             cache=TRUE,
               prompt=FALSE,
               tidy=TRUE,
               comment=NA,
               message=FALSE,
               warning=FALSE)
opts_knit$set(width=75)
```


Artificial Neural Networks have been used by researchers since at least the 1950s, and rose in prominence when computing resources became widely available.  There have been at least 3-4 eras of ANN, with each success and exuberance followed by a quiescence and failure or replacement by other tools. There has always been an intetrplay in this area between computational neuroscientists, computational vision, machine learning, psychology, computer science, and statisticians, with many advances coming by modeling human processes and then applying these algorithms to real-life problems.

* In the 1950s, notions of the ANN were introduced (Perceptron, McCollough & Pitts)
* In the 1960s, inadequacy of these methods were found (XOR problems), and 
* In the 1970s and 1980s, back-propagation provided a reasonable learning approach for multi-layer neural networks for supervised classification problems (Rumelhart & McClelland).
* In the 1970s-1990s, other advances in self-organizing maps, un-supervised learning and hebbian networks provided alternate means for representing knowledge.
* In the 1990s-2000s, other machine learning approaches appeared to take precedence, with lines blurring between ANNs, machine classification, reinforcement learning, and several approaches that linked supervised and unsupervised models (O'Reilly, HTMs, Grossberg).
* In the 2000s, Bayesian approaches were foremost 
* In the 2010s, we have seen a resurgence with so-called "deep learnin"g methods. The advances here have been driven by (1) advances in software that allow us to use GPU (graphics cards) to efficiently train and use networks (2) large data labeled data sets, often generated through amazon mechanical turk or as a byproduct of CAPTCHA systems; (3) using 15+ hidden layers; (4) effective use of specific types of layer architectures, including convolutional networks that de-localize patterns from their position in an image.

A simple two-layer neural network can be considered that is essentially what our multinomial regression or logistic regression model is doing.  Inputs include a set of features, and output nodes (possibly one per class) are classifications that are learned. Alterately, a pattern can be learned by the output nodes.  The main issue here is estimating weights, which are done with heuristic error-propagation approaches rather than MLE or least squares.  This is inefficient for two-layer problems, but the heuristic approach will pay off for more complex problems.

The main advance of the late 1970s and early 1980s was adoption of 'hidden layer' ANNs.  These hidden layers permit solving the XOR problem: when a class is associated with an exclusive or logic. The category structure is stored in a distributed fashion across all nodes, but there is a sense in which the number of hidden nodes controls how complex the classification structure that is possible. With a hidden layer, optimization is difficult with traditional means, but the heuristic approaches generally work reasonably well.

We will start with an image processing example. We will take two images (S and X) and sample features from them to make exemplars:

```{r}

#library(imager)
#s <-load.image("s.data.bmp")
#x <- load.image("x.bmp")
#svec <- as.vector(s)
#xvec <- as.vector(x)
#write.csv(svec,"s.csv")
#write.csv(xvec,"x.csv")

##here, the lower the value, the darker the image.
svec <- read.csv("s.csv")
xvec <- read.csv("x.csv")

##reverse the numbers
svec$x <- 255-svec$x
xvec$x <- 255-xvec$x

par(mfrow=c(1,2))

image(matrix(svec$x,10,10,byrow=T),col=grey(100:0/100))
image(matrix(xvec$x,10,10,byrow=T),col=grey(100:0/100))
```
To train the model, we will sample 500 examples of each template:
```{r,fig.width=6,fig.height=10}

dataX<- matrix(0,ncol=100,nrow=250)
dataS <- matrix(0,ncol=100,nrow=250)
letter <- rep(c("x","s"),each=250)

par(mfrow=c(4,2))

for(i in 1:250)
{
  x  <- rep(0,100)
  xtmp <- table(sample(1:100,size=50,prob=as.matrix(xvec$x),replace=T))
  x[as.numeric(names(xtmp))] <- xtmp/max(xtmp)

  s  <- rep(0,100)
  stmp <- table(sample(1:100,size=50,prob=as.matrix(svec$x),replace=T))
  s[as.numeric(names(stmp))] <- stmp/max(stmp)

  if(i<=4)
   {
    image(matrix(s,10,10,byrow=T),main = "S example",col=grey(100:0/100))
    image(matrix(x,10,10,byrow=T),main  = "X example",col=grey(100:0/100))
  }
  
   dataX[i,] <- x
   dataS[i,] <- s
}

data <- rbind(dataX,dataS)
```

Let's train a neural network on these. Note that we could probably have trained it on the prototypes--maybe from the MNIST library examined in earlier chapters.
```{r}

library(nnet)
options(warn=2)
#model <- nnet(letter~data,size=2) #This doesn't work.  

#Let's transform the letter to a numeric value
model <- nnet(y=as.numeric(letter=="s"),x=data,size=2)
model

#alternately, try using letter as a factor, and use a formula. This
#also plays with some of the learning parameters
merged <- data.frame(letter=as.factor(letter),data)
model2  <- nnet(letter~.,data=merged,size=2,rang=.1,decay=.0001,maxit=500,trace=T)


```

### Examining the model

The model contains a lot of information, including some parameters it is constructed under, and all of the fitted parameters.  
We can see when using summary() that we really have two really large regressions from the 100 input features to 2 hidden nodes, and a single model with an intercept (b=bias) and two parameters from each hidden node to the output node.  The default is 'logistic output units', which means this last model is essentially a logistic regression.  


```{r}
str(model)
summary(model)



```

Some of the arguments we can control are:

* How the final output classifier works (options involve ```linout```, ```entropy```, ```softmax```, ```censored```).  These control fitting algorithms and approaches, and may impact speed of convergence.  The default settings look like they are essentially using least-squared to fit individual nodes.
* ```subset```: allowing you to train on a subset for cross-validation
* ```mask```: allowing only some of the input features to be trained.
* ```Wts```: initial parameter settings.   You could train a model on some data, and use those weights to then re-train on new data, for example.
* ```decay```: this probably controls how far back data in a series are examined. It may allow for a model to adapt to a changing environment better.
* ```maxit``` and ```trace```: fitting arguments.
* ```weights```: strength of each case. You may have some cases you want to train on more strongly/often.
* ```skip```: if TRUE, this is a single-layer network.  This is essentially a logistic regression model.


## Obtaining predicted response

When we use predict, by default it gives us the 'raw' values--activation values returned by the trained network. Because the final layer of this network has just  one node (100-2-1), it is just an activation value indicating the class (0 for X and 1 for S). The values are not exactly 0 and 1--they are floating point values very close.
```{r}
out1 <- predict(model,newdata=data)
plot(out1)
```

If there were a combined example that was hard to distinguish we would get a different value:

```{r}

test <- (data[3,] + data[255,])/2

par(mfrow=c(1,3))
image(matrix(data[3,],10),col=grey(100:0/100))
image(matrix(data[255,],10),col=grey(100:0/100))
image(matrix(test,10),col=grey(100:0/100))

predict(model,newdata=data[3,]+data[4,])
predict(model,newdata=data[255,])
predict(model,newdata=test)
```

In this case, the X shows up as a strong X, the S shows up as an S, but the combined version is a slightly weaker S.

We can get classifications using type="class":

```{r}
predict(model2,type="class")

table(letter,predict(model2,type="class"))
```

## Training with very limited/noisy examples

This classification is actually perfect, but there was a lot of information available. Let's sample just 5 points out to create the pattern:

```{r,fig.width=6,fig.height=10}

dataX<- matrix(0,ncol=100,nrow=250)
dataS <- matrix(0,ncol=100,nrow=250)
letter <- rep(c("x","s"),each=250)


par(mfrow=c(4,2))

for(i in 1:250)
{
  x  <- rep(0,100)
  xtmp <- table(sample(1:100,size=5,prob=as.matrix(xvec$x),replace=T))
  x[as.numeric(names(xtmp))] <- xtmp/max(xtmp)

  s  <- rep(0,100)
  stmp <- table(sample(1:100,size=5,prob=as.matrix(svec$x),replace=T))
  s[as.numeric(names(stmp))] <- stmp/max(stmp)

  ##plot the first few examples:
  if(i<=4)
   {
     image(matrix(s,10,10,byrow=T),main="S example",col=grey(100:0/100))
     image(matrix(x,10,10,byrow=T),main  = "X example",col=grey(100:0/100))
    }
   dataX[i,] <- x
   dataS[i,] <- s
}
data <- rbind(dataX,dataS)



merged <- data.frame(letter=as.factor(letter),data)
model3  <- nnet(letter~.,data=merged,size=2,rarg=.1,decay=.0001,maxit=500)


table(letter,predict(model3,type="class"))

```

It still does very well, with a few errors, for very sparse data. In fact, it might be doing TOO well.  That is, in a sense, it is picking up on arbitrary but highly diagnostic features.  A human observer would never be confident in the outcome, because the information is too sparse, but in this limited world, a single pixel is enough to make a good guess.



## Neural Networks and the XOR problem

Neural networks became popular when researchers realized that networks with a hidden layer could solve 'XOR classification problems'. Early on, researchers recognized that a simple perception (2-layer) neural network could be used for AND or OR combinations, but not  XOR, as these are not linearly separable. XOR classification maps onto many real-world interaction problems. For example, two safe pharmaceuticals might be dangerous when taken together, and a simple neural network could never detect this state--if one is good, and the other is good, both must be better.  An XOR problem is one in which one feature or another (but not both or neither) indicate class membership. In order to perform classification with this logic, a hidden layer is required.

Here is a class defined by an XOR structure:

```{r}
library(MASS)
library(DAAG)
feature1 <- rnorm(200)
feature2 <- rnorm(200)
outcome <- as.factor((feature1 > .6 & feature2 > .3) | (feature1>.6 & feature2<.3))
outcome <- as.factor((feature1 * (-feature2) + rnorm(200))>0)
```

The linear discriminant model fails to discriminate (at least without an interaction)
```{r}
lmodel <-  lda(outcome~feature1+feature2)

confusion(outcome,predict(lmodel)$class)

lmodel2 <-  lda(outcome~feature1*feature2)

confusion(outcome,predict(lmodel2)$class)

```

Similarly, the neural networks with an empty single layer (skip=TRUE) are not great at discriminating, but with a few hidden nodes they work well.  Note that the size argument essentially overrides the skip argument, as n2 and n3 are both 2-3-1 networks:

```{r}
n1 <- nnet(outcome~feature1+feature2,size=0,skip=TRUE)
confusion(outcome,factor(predict(n1,type="class"),levels=c(TRUE,FALSE)))

n2 <- nnet(outcome~feature1+feature2,size=3,skip=TRUE)
confusion(outcome,factor(predict(n2,type="class"),levels=c(FALSE,TRUE)))

n3 <- nnet(outcome~feature1+feature2,size=3,skip=FALSE)
confusion(outcome,factor(predict(n3,type="class"),levels=c(FALSE,TRUE)))


```

Because we have the XOR structure, the simple neural network without a hidden layer is essentially LDA, and in fact often gets a similar level of accuracy (53%).

## IPhone Data using the NNet

To model the iphone data set, we need to decide on how large of a model we want. We need to also remember that training a model like this is not deterministic--every time we do it the situation will be a little different.   Because we have just two classes, maybe a 2-layer hidden network would work. 

By fitting the model several times, we can see that it performs differently every time.  At times, the model does reasonably well.  This does about as well as any of the best classification models. Curiously, this particular model has a bias toward Android accuracy.


```{r}

phone <- read.csv("data_study1.csv")
phone$Smartphone <- (as.factor(phone$Smartphone))
phone$Gender <- as.numeric(as.factor(phone$Gender))
set.seed(100)
phonemodel <- nnet(Smartphone~.,size=3,data=phone)
confusion(phone$Smartphone,factor(predict(phonemodel,newdata=phone,type="class",levels=c("Android","iPhone"))))
```

Other times, it does poorly: Here, it calls everything an iPhone:

```{r}

set.seed(101)
phonemodel2 <- nnet(Smartphone~.,data=phone,size=2)
confusion(phone$Smartphone,factor(predict(phonemodel2,newdata=phone,type="class"),levels=c("Android","iPhone")))
```

In this case, it called everything in iPhone, resulting in 58.6% accuracy.  Like many of our approaches, we are doing heuristic optimization and so may end up in local optima. It is thus useful to run the model many several times and look for the best model. Running this many times, the best models seem to get around 370-390 correct, which is in the low 70% for accuracy.  

```{r,echo=TRUE, message=FALSE, warning=FALSE,error=FALSE,results=FALSE}
preds <- matrix(0,100)
for(i in 1:100)
{
  phonemodel3 <- nnet(Smartphone~.,data=phone,size=2)
  preds[i] <- confusion(phone$Smartphone,factor(predict(phonemodel3,newdata=phone,type="class"),levels=c("Android","iPhone")))$overall
  
}

hist(preds,col="gold",main="Accuracy of 100 fitted models (2 hidden nodes)",xlim=c(0,1))
```
Do we do any better, on average, with more hidden nodes?
```{r,echo=TRUE, message=FALSE, warning=FALSE,error=FALSE,results=FALSE}
preds <- matrix(0,100)
for(i in 1:100)
{
  phonemodel3 <- nnet(Smartphone~.,data=phone,size=6, trace=FALSE)
#  preds[i] <- confusion(phone$Smartphone,factor(predict(phonemodel3,newdata=phone,type="class"),levels=c("Android","iPhone")))$overall
 tab <- table(phone$Smartphone,factor(predict(phonemodel3,newdata=phone,type="class"),levels=c("Android","iPhone")))
 preds[i] <- sum(diag(tab))/sum(tab)
}

hist(preds,col="gold",main="Accuracy of 100 fitted models (6 hidden nodes)",xlim=c(0,1))
```
This seems to be more consistent, and do better overall--usually above 70% accuracy.  But like every model we have examined, the best models are likely to be over-fitting, and getting lucky at re-predicting their own data. It would also be important to implement a cross-validation scheme. On its own, it might just tell us if we are overfitting.  We could use it to help select the number of hidden nodes, or to select variables for exclusion.

There is no built-in cross-validation here, but you can implement one using subset functions.

```{r,echo=TRUE, message=FALSE, warning=FALSE}
train <- rep(FALSE,nrow(phone))
train[sample(1:nrow(phone),size=300)] <- TRUE
test <- !train

phonemodel2 <- nnet(Smartphone~.,data=phone,size=6,subset=train)
confusion(phone$Smartphone[test],
      predict(phonemodel2,newdata=phone[test,],type="class"))

```


We can try this 100 times and see how well it does on the cross-validation set:
```{r,echo=TRUE, message=FALSE, warning=FALSE,results=FALSE}
preds <- rep(0,100)

for(i in 1:100)
{
   train <- rep(FALSE,nrow(phone))
   train[sample(1:nrow(phone),size=300)] <- TRUE
   test <- !train

phonemodel2 <- nnet(Smartphone~.,data=phone,size=6,subset=train,trace=FALSE)

tab <- table(phone$Smartphone[test],factor(predict(phonemodel2,newdata=phone[test,],type="class"),levels=c("Android","iPhone")))
preds[i] <- sum(diag(tab))/sum(tab)
 
# preds[i] <-  confusion(phone$Smartphone[test],factor(predict(phonemodel2,newdata=phone[test,],type="class"),levels=c("Android","iPhone")))$overall

}

hist(preds,col="gold",main="Accuracy of 100 cross-validated models (6 hidden nodes)",xlim=c(0,1))

```

The cross-validation scores are typically a bit lower, with models getting around 60% on average, and up to 70% for the best.   Now that we have built this, we could use average cross-validation accuracy to help select variables for exclusion. Here, let's just test the predictors we have found previously to be fairly good:


```{r,echo=TRUE, message=FALSE, warning=FALSE,error=FALSE,results=FALSE,}
preds <- rep(0,100)

for(i in 1:100)
{
   train <- rep(FALSE,nrow(phone))
   train[sample(1:nrow(phone),size=300)] <- TRUE
   test <- !train

phonemodel2 <- nnet(Smartphone~Gender+Avoidance.Similarity+Phone.as.status.object+Age,
                    data=phone,size=6,subset=train,trace=F)

tab <- table(phone$Smartphone[test],factor(predict(phonemodel2,newdata=phone[test,],type="class"),levels=c("Android","iPhone")))
preds[i] <- sum(diag(tab))/sum(tab)
 

}

hist(preds,col="gold",main="Accuracy of 100 cross-validated models (6 hidden nodes)",xlim=c(0,1))
```

Most of these are better than chance, and it seems to do about as well as the full set of predictors as well.


## The ```neuralnet``` library

The neuralnet library is perhaps a more flexible implementation, with multiple hidden layers. Here we have 2 hidden layers with two nodes each.  When fitting it, it seemed to get stuck frequently and not converge or have some other error, but it does give a nice graphical visualization of the network.  It seems to used more advanced backprop algorithms and activation functions.  Here we have two hidden layers with two nodes each. The network does not make a lot of sense, but the model fails to converge under many larger network conditions.


```{r}
library(neuralnet)
set.seed(10313)
   train <- rep(FALSE,nrow(phone))
   train[sample(1:nrow(phone),size=300)] <- TRUE
   test <- !train

phonemodel3 <- neuralnet(Smartphone~.,
                    hidden=c(2,2), 
                    data=phone[train,])

pred <- apply(predict(phonemodel3,newdata=phone[test,]),1,which.max)
ptest <- phone[test,]
acc <- (sum(ptest[pred==1,]$Smartphone=="Android") + sum(ptest[pred==2,]$Smartphone=="iPhone") )/sum(test)  
print(acc)


plot(phonemodel3,rep="best")
```


# Classifying handwritten characters using a neural net

The ```neuralnet``` library is a bit more powerful, and allows multiple layers. Let's try it for a larger data set--mnist handwritten characters.  I've included 10,000 cases inn mnist_test.csv, but this gets a bit difficult to build a model, so let's consider three characters that are similar: 4,  7, and 9. This results in about 3000 cases, so lets fit the data on a subset of 1000, using 10 hidden nodes.

```{r, cache=FALSE}
library(neuralnet)
library(DAAG)
##10K examples of 0 to 9
mnistdat <-read.csv("mnist_test.csv")
mnistdat$label <- factor(mnistdat$label) ## this needs to be a factor if it has more than 2 levels

mnist47 <- mnistdat[mnistdat$label==4 | mnistdat$label==7| mnistdat$label==9,]

train <- mnist47[sample(1:nrow(mnist47),1000),]  #train on some examples
set.seed(100)
mnist <- neuralnet(label~.,
                    hidden=c(4), 
                    data=train)

##examine predictions on the the trained data:
table(train$label,c(4,7,9)[apply(mnist$response,1,which.max)])

```

It essentially predicts the trained data perfectly.  Let's see how it does on the held-out data.  We will use the ```predict``` function to get the activation values, and then use the ```which.max``` function to get the predicted class.  We will then compare the predicted class to the actual class.



```{r}
##examine held-out data:
p2 <- predict(mnist,newdata=mnist47)
pred <- c(4,7,9)[apply(p2,1,which.max)]

table(mnist47$label,pred)
mean(mnist47$label==pred)
```


Errors of 4 categorized as a 7:

```{r}
error47 <- mnist47[mnist47$label==4 & pred==7,]
cols <- grey(100:1/100)
par(mfrow=c(2,4))
image((matrix(as.numeric(error47[1,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[2,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[3,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[4,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[5,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[6,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[7,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error47[8,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")

```

Errors of 4 categorized as a 9:
```{r}
error49 <- mnist47[mnist47$label==4 & pred==9,]
cols <- grey(100:1/100)
par(mfrow=c(2,4))
image((matrix(as.numeric(error49[1,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[2,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[3,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[4,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[5,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[6,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[7,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")
image((matrix(as.numeric(error49[8,-1]),nrow=28,ncol=28))[,28:1],xaxt="n",yaxt="n",col=cols,main="4s called 7s")

```
We can maybe see some patterns here for what kinds of errors are being made.


This is just the tip of the iceberg for neural network models. Modern deep networks use a mixture of different kinds of sublayers that are specialized for handling specific kinds of data (e.g., recurrent,  convolutional, etc.), and they also use 15+ layers.  These require substantial compute power to fit, and huge data sets of labeled data--often labeled by humans.  But this is the basis for many of the recent advances in artificial  intelligence.