Created
August 13, 2017 17:37
-
-
Save victorkohler/e22b52a78e43115ea9fea8a6a0fda6fe 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
def implicit_als(sparse_data, alpha_val=40, iterations=10, lambda_val=0.1, features=10): | |
""" Implementation of Alternating Least Squares with implicit data. We iteratively | |
compute the user (x_u) and item (y_i) vectors using the following formulas: | |
x_u = ((Y.T*Y + Y.T*(Cu - I) * Y) + lambda*I)^-1 * (X.T * Cu * p(u)) | |
y_i = ((X.T*X + X.T*(Ci - I) * X) + lambda*I)^-1 * (Y.T * Ci * p(i)) | |
Args: | |
sparse_data (csr_matrix): Our sparse user-by-item matrix | |
alpha_val (int): The rate in which we'll increase our confidence | |
in a preference with more interactions. | |
iterations (int): How many times we alternate between fixing and | |
updating our user and item vectors | |
lambda_val (float): Regularization value | |
features (int): How many latent features we want to compute. | |
Returns: | |
X (csr_matrix): user vectors of size users-by-features | |
Y (csr_matrix): item vectors of size items-by-features | |
""" | |
# Calculate the foncidence for each value in our data | |
confidence = sparse_data * alpha_val | |
# Get the size of user rows and item columns | |
user_size, item_size = sparse_data.shape | |
# We create the user vectors X of size users-by-features, the item vectors | |
# Y of size items-by-features and randomly assign the values. | |
X = sparse.csr_matrix(np.random.normal(size = (user_size, features))) | |
Y = sparse.csr_matrix(np.random.normal(size = (item_size, features))) | |
#Precompute I and lambda * I | |
X_I = sparse.eye(user_size) | |
Y_I = sparse.eye(item_size) | |
I = sparse.eye(features) | |
lI = lambda_val * I |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment