Matrix

This section presents the code used to produce the User-Movie Matrix X discussed in the text and the examples of the SVD/LDA analyses:

# generate the user-movies matrix
library(Matrix)
M<-sparseMatrix(i=c(3,4,7,3,4,5,7,1,2,7,1,2,7,5,6,5,6), 
                j=c(1,1,1,2,2,2,2,3,3,3,4,4,4,5,5,6,6), x=1)
rownames(M)<-c("Noah", "Emma", "Mason", "Sophia", "William", "James", "Tom")
colnames(M)<-c("True Romance", "Pretty Woman", "Aliens", 
               "Star Wars", "Due Date", "Hangover")
M

# SVD analysis
library(irlba)
Msvd <- irlba(M,nu = 3, nv=3) #svd() would work as well with small data

# varimax rotation
Msvd$v_rot <- unclass(varimax(Msvd$v)$loadings)
Msvd$u_rot <- as.matrix(M %*%Msvd$v_rot)
# or, in fact: Msvd$u_rot <- M %*% as.matrix(sweep(Msvd$v_rot,2, Msvd$d,"/"))

# round and print the results
Msvd <- lapply(Msvd, round,2) 
Msvd

# SVD on a centered matrix; svd() would work as well with small data
Mc<-scale(M, center = TRUE, scale = F)
Mcsvd<-irlba(Mc,nu = 3, nv=3)

# varimax rotation
Mcsvd$v_rot <- unclass(varimax(Mcsvd$v)$loadings)
Mcsvd$u_rot <- as.matrix(Mc %*%Mcsvd$v_rot)

# round and print the results
Mcsvd <- lapply(Mcsvd, round,2) 
Mcsvd

# LDA analysis
library(topicmodels)

# default alpha
Mlda<-LDA(M, k=3,method="Gibbs")
gamma <- Mlda@gamma
beta <- exp(Mlda@beta)
str(Mlda)

# print the results
round(gamma,2)
round(beta,2)

# low alpha
Mlda2<-LDA(M, k=3, control=list(alpha=.01, delta=.01), method = "Gibbs")
gamma2 <- Mlda2@gamma
beta2 <- exp(Mlda2@beta)

round(posterior(Mlda2, M)$topics,2)

# print the results
round(gamma2,2)
round(beta2,2)