def gen_func(u, v): '''R(v) = a + b * R(u)''' # cache layer try: a, b = conn.execute('SELECT a, b FROM core_func WHERE id = %d' % (u * (N_USERS + 1) + v)).fetchone() return lambda x: a + b * x except: pass # unsuccessful hit I = corate(u, v) ru = get_ratings(u, I) rv = get_ratings(v, I) return _gen_func(ru, rv)
def cache(init = False): '''caching function parameters -- a and b in R(v) = a + b * R(u)''' if init: conn.execute('DELETE FROM core_func') x = conn.execute('SELECT MAX(id) FROM core_func').fetchone()[0] / (N_USERS + 1) for i in range(x + 1, N_USERS + 1): for j in range(1, N_USERS + 1): try: I = corate(i, j) ru, rv = array(get_ratings(i, I)), array(get_ratings(j, I)) fp = lambda x, p: p[0] + p[1] * x e = lambda p, y, x: abs(fp(x, p) - y).sum() p = fmin(e, array([0, 1]), args = (rv, ru), maxiter = 10000, maxfun = 10000, disp = 0) a, b = p[0], p[1] conn.execute('INSERT INTO core_func VALUES(%d, %lf, %lf)' % (i * (N_USERS + 1) + j, a, b)) except sqlite3.IntegrityError: print 'chongfu!' print i conn.commit()