Skip to content

Instantly share code, notes, and snippets.

@dstein64
Last active September 2, 2016 15:32
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 dstein64/69ef1d3f1e65b66e171981c378446220 to your computer and use it in GitHub Desktop.
Save dstein64/69ef1d3f1e65b66e171981c378446220 to your computer and use it in GitHub Desktop.
import numpy as np
import numpy.ma as ma
import theano
from theano import tensor as T
floatX = theano.config.floatX
def getmask(D):
return ma.getmaskarray(D) if ma.isMA(D) else np.zeros(D.shape, dtype=bool)
def matrix_factorization_bgd(
D, P, Q, steps=5000, alpha=0.0002, beta=0.02):
P = theano.shared(P.astype(floatX))
Q = theano.shared(Q.astype(floatX))
X = T.matrix()
error = T.sum(T.sqr(~getmask(D) * (P.dot(Q) - X)))
regularization = (beta/2.0) * (T.sum(T.sqr(P)) + T.sum(T.sqr(Q)))
cost = error + regularization
gp, gq = T.grad(cost=cost, wrt=[P, Q])
train = theano.function(inputs=[X],
updates=[(P, P - gp * alpha), (Q, Q - gq * alpha)])
for _ in xrange(steps):
train(D)
return P.get_value(), Q.get_value()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment