<jupyter_start><jupyter_text>Jaccard Similarity> Implementation of jaccard similarity based recommender model.<jupyter_code>#export
import pandas as pd
import operator
#export
class JaccardSimilarity:
    """Using the Jaccard Index, we can retrieve top-k similar items to a given item. 
    This provides a way to recommend items of a user which are similar to the 
    items that the user has history with.
    """
    def fit(self, df, user_col='user_id', item_col='item_id'):
        self.item_col = item_col
        self.item_sets = dict((item, set(users)) for item, users in df.groupby(item_col)[user_col])

    def _jaccard(self, item1, item2):
        a = self.item_sets[item1]
        b = self.item_sets[item2]
        intersection = float(len(a.intersection(b)))
        return intersection / (len(a) + len(b) - intersection)

    def recommend(self, itemid, top_k=5):
        jaccard_dict = {x: self._jaccard(x, itemid) for x in self.item_sets}
        ranked_items = sorted(jaccard_dict.items(), key=operator.itemgetter(1), reverse=True)[1:top_k+1]
        return ranked_items<jupyter_output><empty_output><jupyter_text>Example<jupyter_code>rating_df = pd.read_csv('https://raw.githubusercontent.com/sparsh-ai/rec-data-public/master/ml-other/ml100k_ratings.csv', sep=',', header=0)
model = JaccardSimilarity()

model.fit(df=rating_df, user_col='userId', item_col='movieId')
model.recommend(itemid=10)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11866759195003469, 'fraction_numerical': 0.009715475364330326, 'mean_word_length': 4.5038167938931295, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 10, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '344105', 'license': 'Apache-2.0', 'n_tokens_mistral': 504, 'n_tokens_neox': 490, 'n_words': 111, 'path': 'nbs/models/models.jaccard_similarity.ipynb', 'repo_name': 'sparsh-ai/recohut', 'size': '1441'}