Last active
September 2, 2016 15:32
-
-
Save dstein64/69ef1d3f1e65b66e171981c378446220 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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