inst/findAlphBet.R

# multiplicative random effects model:  the rating Y, 0 or 1, is
# generated by
# 
# EY_ij = b0 = b1 alpha_i beta_j 

# for unobservable alpha, beta having means 1.0, 
# and unknown constants b0, b1 

# this is a very simple model, whose virtue is simplicity and quick
# computation

# arguments:

#   ratingsIn: input data, with first cols (userID,itemID,rating,
#              covariates); data frame

# value:

#   S3 class of type "MMmultiplic", with components:

#      alphavec: the alpha_i
#      betavec: the beta_j

trainMultiplic<- function(ratingsIn) {
   usrs = ratingsIn[,1] 
   itms = ratingsIn[,2] 
   ratings = ratingsIn[,3] 
   yd <- findYdotsMM(ratingsIn)
   ydi <- yd$usrMeans
   ydj <- yd$itmMeans
   nu <- yd$grandMean
   ### alph <- ydi / nu
   ### bet <- ydj / nu
   alph <- ydi 
   bet <- ydj 
   ratingsInAlphs <- alph[usrs]
   ratingsInBets <- bet[itms]
   alphbet <- alph[usrs] * bet[itms]
   coefs <- coef(lm(ratingsIn[,3] ~ alphbet))
   res <- list(alph=alph,bet=bet,nu=nu,coefs=coefs)
   class(res) <- 'MMmultiplic'
   res
} 

# predict() method for the 'MMmultiplic' class

# testSet in same form as ratingsIn above, except that there 
# is no ratings column (that column can be present, but only columns 1
# and 2) are used

# MMmultiplic is the output of findAlphBet()

# returns vector of predicted values for testSet, i.e. estimated
# probabilities of rating = 1

# currently predicts only on users/items in the training set, i.e.
# predicts the missing values in the users/items/ratings matrix

predict.MMmultiplic = function(multiplicObj,testSet) {
   usrs <- testSet[,1]
   itms <- testSet[,2]
   alphbet <- 
      multiplicObj$alph[usrs] * 
      multiplicObj$bet[itms] 
   tmp <- cbind(1,alphbet) %*% multiplicObj$coefs
   tmp <- pmin(tmp,1)
   tmp <- pmax(tmp,0)
   cbind(tmp,round(tmp))
}
matloff/rectools documentation built on March 31, 2022, 12:09 p.m.