1: predict.knnMF <- function(recoOut,newCase,k=5) { W <- recoOut$P H <- t(recoOut$Q) H[is.nan(H)] <- 0 userID <- newCase[1] itemID <- newCase[2] nrw <- nrow(W) cosines <- vector(length = nrw) for (i in 1:nrw) { cosines[i] <- cosdist(W[userID,],W[i,]) } nearby <- order(cosines,decreasing=TRUE)[1:k] preds <- W[nearby,] %*% H[,itemID] mean(preds) } cosdist <- function(x,y) { x %*% y / (l2a(x) * l2a(y)) } l2a <- function(x) sqrt(x %*% x) library(rectools) load('~/ML100K') ud <- udata[,1:3] set.seed(9999) # important! z <- trainReco(ud,nmf=T) print(predict.knnMF(z,c(5,12)))