-
Notifications
You must be signed in to change notification settings - Fork 2
/
knn_recommender.py
59 lines (52 loc) · 2.7 KB
/
knn_recommender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from sklearn.neighbors import NearestNeighbors
from fuzzywuzzy import fuzz
import numpy as np
class Recommender:
def __init__(self, metric, algorithm, k, data, decode_id_song):
self.metric = metric
self.algorithm = algorithm
self.k = k
self.data = data
self.decode_id_song = decode_id_song
self.data = data
self.model = self._recommender().fit(data)
def make_recommendation(self, new_song, n_recommendations):
recommended = self._recommend(new_song=new_song, n_recommendations=n_recommendations)
print("... Done")
return recommended
def _recommender(self):
return NearestNeighbors(metric=self.metric, algorithm=self.algorithm, n_neighbors=self.k, n_jobs=-1)
def _recommend(self, new_song, n_recommendations):
# Get the id of the recommended songs
recommendations = []
recommendation_ids = self._get_recommendations(new_song=new_song, n_recommendations=n_recommendations)
# return the name of the song using a mapping dictionary
recommendations_map = self._map_indeces_to_song_title(recommendation_ids)
# Translate this recommendations into the ranking of song titles recommended
for i, (idx, dist) in enumerate(recommendation_ids):
recommendations.append(recommendations_map[idx])
return recommendations
def _get_recommendations(self, new_song, n_recommendations):
# Get the id of the song according to the text
recom_song_id = self._fuzzy_matching(song=new_song)
# Start the recommendation process
print(f"Starting the recommendation process for {new_song} ...")
# Return the n neighbors for the song id
distances, indices = self.model.kneighbors(self.data[recom_song_id], n_neighbors=n_recommendations+1)
return sorted(list(zip(indices.squeeze().tolist(), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1]
def _map_indeces_to_song_title(self, recommendation_ids):
# get reverse mapper
return {song_id: song_title for song_title, song_id in self.decode_id_song.items()}
def _fuzzy_matching(self, song):
match_tuple = []
# get match
for title, idx in self.decode_id_song.items():
ratio = fuzz.ratio(title.lower(), song.lower())
if ratio >= 60:
match_tuple.append((title, idx, ratio))
# sort
match_tuple = sorted(match_tuple, key=lambda x: x[2])[::-1]
if not match_tuple:
print(f"The recommendation system could not find a match for {song}")
return
return match_tuple[0][1]