Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save giuseppebonaccorso/65eed3fb5f745d7b4e13fb99b263ac2e to your computer and use it in GitHub Desktop.
Save giuseppebonaccorso/65eed3fb5f745d7b4e13fb99b263ac2e to your computer and use it in GitHub Desktop.
A model-free collaborative recommendation system in 20 lines of Python
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)
test_user=500
# Take the top-10 simular users
for d in sorted_distances[test_user][::-1][0:10]:
print(d)
630
189
781
199
789
697
689
105
889
893
@alshimaamoner
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment