Skip to content

Instantly share code, notes, and snippets.

@benfred
Created March 1, 2017 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfred/5816442fcae644724c2bb46b1270014d to your computer and use it in GitHub Desktop.
Save benfred/5816442fcae644724c2bb46b1270014d to your computer and use it in GitHub Desktop.
# A Simple Julia Version of the algorithm described in the paper Collaborative Filtering for Implicit Feedback Datasets
# http://yifanhu.net/PUB/cf.pdf
# This was mainly an experiment for me in learning Julia, unfortunately the code below ended up
# being about the same speed as my pure python version here https://github.com/benfred/implicit
# and much much slower than the Cython version I included there.
# (fwiw The slowness is probably because I don't understand the language as well as I do Python)
function alternatingLeastSquares(input, factors, regularization)
rows, cols = size(input)
# initialize factors randomly
colFactors = randn(factors, cols)
rowFactors = randn(factors, rows)
# transpose once for fast access
inputT = input'
for iteration = 1: 20
println(iteration)
leastSquares(input, colFactors, rowFactors, regularization)
leastSquares(inputT, rowFactors, colFactors, regularization)
end
rowFactors, colFactors
end
function leastSquares(Cui, X, Y, regularization)
factors, users = size(X)
rows = rowvals(Cui)
vals = nonzeros(Cui)
YtY = Y * Y'
for u = 1: users
A = YtY + regularization * eye(factors)
b = zeros(factors)
for i in nzrange(Cui, u)
factor = Y[:, rows[i]]
b += (vals[i] + 1) * factor
A += factor * vals[i] * factor'
end
X[:, u] = A\b
end
end
using MatrixMarket
m = MatrixMarket.mmread("small.mtx")
@time alternatingLeastSquares(m, 50, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment