Skip to content

Instantly share code, notes, and snippets.

@BioSciEconomist
Created October 31, 2016 01:35
Show Gist options
  • Save BioSciEconomist/337f76f66eaefa7c9d06dd447fc6c2a5 to your computer and use it in GitHub Desktop.
Save BioSciEconomist/337f76f66eaefa7c9d06dd447fc6c2a5 to your computer and use it in GitHub Desktop.
Nonnegative Matrix Factorization and Recommendor Systems
# r code to support post:http://econometricsense.blogspot.com/2012/10/nonnegative-matrix-factorization-and.html
# ------------------------------------------------------------------
# | PROGRAM NAME: R nmf example
# | DATE: 10/20/12
# | CREATED BY: MATT BOGARD
# | PROJECT FILE: /Users/wkuuser/Desktop/Briefcase/R Programs
# |----------------------------------------------------------------
# | PURPOSE: very basic example of a recommendor system based on
# | non-negative matrix factorization
# |
# |
# |------------------------------------------------------------------
library(NMF)
# X ~ WH'
# X is an n x p matrix
# W = n x r user feature matrix
# H = r x p movie feature matrix
# get ratings for 5 users on 4 movies
x1 <- c(5,4,1,1)
x2 <- c(4,5,1,1)
x3 <- c(1,1,5,5)
x4 <- c(1,1,4,5)
x5 <- c(1,1,5,4)
R <- as.matrix(rbind(x1,x2,x3,x4,x5)) # n = 5 rows p = 4 columns
set.seed(12345)
res <- nmf(R, 4,"lee") # lee & seung method
V.hat <- fitted(res)
print(V.hat) # estimated target matrix
w <- basis(res) # W user feature matrix matrix
dim(w) # n x r (n= 5 r = 4)
print(w)
h <- coef(res) # H movie feature matrix
dim(h) # r x p (r = 4 p = 4)
print(h)
# recommendor system via clustering based on vectors in H
movies <- data.frame(t(h))
features <- cbind(movies$X1,movies$X2)
plot(features)
title("Movie Feature Plot")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment