<jupyter_start><jupyter_text>Nearest Neighbour<jupyter_code># df = rating_data.groupby(['user_id', 'content_id']).max('rating').reset_index()
df = rating_data.pivot(index='content_id', columns='user_id', values='rating').fillna(0)
df
from sklearn.neighbors import NearestNeighbors

knn = NearestNeighbors(metric='cosine', algorithm='brute')

knn.fit(df.values)

distances, indices = knn.kneighbors(df.values, n_neighbors=len(df))
neighbours = {}

for i in range(0, len(indices)):
    nn = indices[i]
    dist = distances[i]    
    e = nn[0]
    e_content = df.index[e]    
    neighbours[e_content] = {"nn": [df.index[n] for n in nn[1:]], "dist": [1 - x for x in dist[1:]]}
indices
recom4 = content[content['ID'].isin(indices[][1:])]
recom4
def predict_rating(user_id, content_id, neighbours):
    
    if content_id not in neighbours:
        print("no data for content_id")
        
    neighbours = neighbours[content_id]
    
    nn = neighbours['nn']
    dist = neighbours['dist']
    
    numerator = 0
    denominator = 0
    
    for i in range(0, len(nn)):
        
        content_id = nn[i]
        user_rating = df.loc[content_id, user_id]
        
        if user_rating > 0:
            
            numerator += user_rating * dist[i]
            denominator += dist[i]
            
    if denominator > 0:
        
        return numerator / denominator
    
    else: 
        
        return 0
predict_rating('1', '2', 5)<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup