This repository has been archived by the owner on Jan 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheuristic.py
68 lines (59 loc) · 2.42 KB
/
heuristic.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
60
61
62
63
64
65
66
67
68
import numpy as np
import pandas as pd
class Heuristic:
"""This class contains some heuristics algorithms for a graph recommendation system."""
def __init__(self, graph):
self.graph = graph
def __col_fil_movies(self, user, item):
"""Calculates possible rating using collaborative filtering technique."""
k = 0
sim_r = 0
for edge in self.graph.edges([user['label']], data=True):
if self.graph.nodes[edge[0]]['type'] == 'movie':
movie = self.graph.nodes[edge[0]]
elif self.graph.nodes[edge[1]]['type'] == 'movie':
movie = self.graph.nodes[edge[1]]
else:
continue
data = self.graph.get_edge_data(movie['label'], item['label'])
# print(data)
if data is None:
continue
# print(edge, data)
k += data['similarity']
sim_r += data['similarity'] * edge[2]['rating']
return (1 / k) * sim_r if k else 0
def __col_fil_users(self, user, item):
"""Calculates possible rating using collaborative filtering technique."""
k = 0
sim_r = 0
for edge in self.graph.edges([item['label']], data=True):
if self.graph.nodes[edge[0]]['type'] == 'user':
user_1 = self.graph.nodes[edge[0]]
elif self.graph.nodes[edge[1]]['type'] == 'user':
user_1 = self.graph.nodes[edge[1]]
else:
continue
data = self.graph.get_edge_data(user_1['label'], user['label'])
# print(data)
if data is None:
continue
# print(edge, data)
k += data['similarity']
sim_r += data['similarity'] * edge[2]['rating']
return (1 / k) * sim_r if k else 0
def collaborative_filtering(self, edges, mode='movies'):
"""Movie collaborative filtering algorithm"""
r = []
for edge in edges:
if self.graph.nodes[edge[0]]['type'] == 'user':
user = self.graph.nodes[edge[0]]
movie = self.graph.nodes[edge[1]]
else:
user = self.graph.nodes[edge[1]]
movie = self.graph.nodes[edge[0]]
if mode == 'movies':
r.append(self.__col_fil_movies(user, movie))
else:
r.append(self.__col_fil_users(user, movie))
return np.array(r)