How to implement simulated annealing in R

r
simulated_annealing

#1

hello,

While trying to implement recommenders through R,I came across some piece of code:

ratingMatrix <- as.data.frame(rbind(c(5,5,0,1),c(4,0,0,1),c(1,1,0,5),c(1,0,0,4),c(0,1,5,4)))
#Naming the columns:
names(ratingMatrix) = c('P1','P2','P3','P4')
#Naming the rows:
rownames(ratingMatrix) = paste("U",1:5,sep = "")
rownames(ratingMatrix)
#Converting to simple triplet matrix to retain only non-zero values and their index values:
p = slam::as.simple_triplet_matrix(ratingMatrix)
#Simulated Annealing:
#Initialisation of Parameters
par = rep(1,18)#There are a total of 18 values in U and M matrices together.
#Forming objective function:
fnc = function(par){
  u = matrix(par[1:10],nrow = 5,byrow = T)#U matrix
  #initialisation:
  m = matrix(par[11:18],nrow = 2,byrow = T)#transposed M
  #matrix initialisation
  R = u %*% m
  Rv = sapply(1:13,function(x)R[p$i[x],p$j[x]])
  sum((p$v-Rv)^2)#Sum of square of error which is to be minimized
}

library(GenSA)
set.seed(1234);
val = GenSA(par,fnc,lower = rep(0,18),upper = rep(4,18),
                        control = list(threshold.stop = 0.0001))
#Final rating matrix after optimization
matrix(val$par[1:10],nrow = 5,byrow = T)%*%matrix(val$par[11:18],nrow = 2,byrow = T)

The final matrix that is returned is:

I am not being able to understand the Simulated Annealing part.
Can someone please help me with this??