Last active
April 17, 2018 22:14
-
-
Save giuseppebonaccorso/65eed3fb5f745d7b4e13fb99b263ac2e to your computer and use it in GitHub Desktop.
A model-free collaborative recommendation system in 20 lines of Python
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
from scipy.sparse import dok_matrix | |
from sklearn.metrics.pairwise import pairwise_distances | |
import numpy as np | |
# Set random seed (for reproducibility) | |
np.random.seed(1000) | |
# Create a dummy user-item dataset | |
nb_users = 1000 | |
nb_products = 2500 | |
max_rating = 5 | |
max_rated_products = 500 | |
X_preferences = dok_matrix((nb_users, nb_products), dtype=np.uint8) | |
for i in range(nb_users): | |
# Extract n random products | |
n_products = np.random.randint(0, max_rated_products+1) | |
products = np.random.randint(0, nb_products, size=n_products) | |
# Populate preference sparse matrix | |
for p in products: | |
X_preferences[i, p] = np.random.randint(0, max_rating+1) | |
# Compute pairwise distances | |
distance_matrix = pairwise_distances(X_preferences, metric='euclidean') | |
# Sort distances | |
sorted_distances = np.argsort(distance_matrix, axis=1) |
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
test_user=500 | |
# Take the top-10 simular users | |
for d in sorted_distances[test_user][::-1][0:10]: | |
print(d) |
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
630 | |
189 | |
781 | |
199 | |
789 | |
697 | |
689 | |
105 | |
889 | |
893 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
please, can you tell me how to call sorted_distance in test.py without import model_free_collaborative_filtering.py
and how to put the output in text file?