Skip to content

Instantly share code, notes, and snippets.

View victorkohler's full-sized avatar

Victor Köhler victorkohler

View GitHub Profile
# Let's say we want to recommend artists for user with ID 2023
user_id = 2023
#------------------------------
# GET ITEMS CONSUMED BY USER
#------------------------------
# Let's print out what the user has listened to
consumed_idx = data_sparse[user_id,:].nonzero()[1].astype(str)
#------------------------------
# FIND SIMILAR ITEMS
#------------------------------
# Let's find similar artists to Jay-Z.
# Note that this ID might be different for you if you're using
# the full dataset or if you've sliced it somehow.
item_id = 10277
def nonzeros(m, row):
for index in xrange(m.indptr[row], m.indptr[row+1]):
yield m.indices[index], m.data[index]
def implicit_als_cg(Cui, features=20, iterations=20, lambda_val=0.1):
user_size, item_size = Cui.shape
X = np.random.rand(user_size, features) * 0.01
import sys
import pandas as pd
import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import spsolve
import random
from sklearn.preprocessing import MinMaxScaler
import implicit # The Cython library
import sys
import pandas as pd
import numpy as np
import scipy.sparse as sparse
from scipy.sparse.linalg import spsolve
import random
from sklearn.preprocessing import MinMaxScaler
import implicit
import tensorflow as tf
import pandas as pd
import numpy as np
import scipy.sparse as sp
from tqdm import tqdm
#---------------------------
# LOAD AND PREPARE THE DATA
#---------------------------
#-------------
# HYPERPARAMS
#-------------
epochs = 50
batches = 30
num_factors = 64 # Number of latent features
# Independent lambda regularization values
#-------------------------
# TENSORFLOW GRAPH
#-------------------------
# Set up our Tensorflow graph
graph = tf.Graph()
def init_variable(size, dim, name=None):
'''
with graph.as_default():
'''
Loss function:
-SUM ln σ(xui - xuj) + λ(w1)**2 + λ(w2)**2 + λ(w3)**2 ...
ln = the natural log
σ(xuij) = the sigmoid function of xuij.
λ = lambda regularization value.
||W||**2 = the squared L2 norm of our model parameters.
#------------------
# GRAPH EXECUTION
#------------------
# Run the session.
session = tf.Session(config=None, graph=graph)
session.run(init)
# This has noting to do with tensorflow but gives