# Three-layered neural network model
# with backpropagation learning algorithm

# Learning XOR rule

# Set up inputs
input<-matrix(c(1,1,
                1,0,
                0,1,
                0,0),4,2,byrow=T)

# Set up targets
target<-matrix(c(0,1,1,0),1,4)

# Set up associative weights between input and hidden layers
set.seed(123)
W<-matrix(runif(6,-0.5,0.5),3,2)
# Set up associative weights between hidden and output layers
Z<-matrix(runif(3,-0.5,0.5),1,3)
# Set up number of iteration
nit<-1000

# Set up learning rate
eta<-0.25

# Set up error vector
E<-rep(-1,nit)

# Start training

for(i in 1:nit){
  # Feed forward to hidden layer
  h<-W%*%t(input)
  # Sigmoid function as activation function
  H<-1/(1+exp(-h))
  #H<-rbind(H,-1)
  # Feed forward to output layer
  o<-Z%*%H
  #O<-ifelse(o>0,o,0)
  # Compute error
  #e<-target-O
  e<-target-o
  E[i]<-0.5*sum(e^2)
  # Gradient descent for Z
  dZ<--eta*e%*%t(H)
  #Z<-Z-dZ
  # gradient descent for W
  # error signal on hidden nodes
  eH<-t(e)%*%Z
  dW<--eta*(t(eH)*H*(1-H))%*%input
  W<-W-dW
  Z<-Z-dZ
}
plot(1:nit,E,type='l')
o
W
Z
