-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pearson's r.py
138 lines (60 loc) · 1.73 KB
/
Pearson's r.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#!/usr/bin/env python
# coding: utf-8
# In[7]:
import pandas as pd
import numpy as np
# In[8]:
movies = pd.read_csv('movies.csv')
ratings = pd.read_csv('ratings.csv')
# In[9]:
ratings.drop(['timestamp'], axis=1, inplace=True)
# In[10]:
movies.head()
# In[11]:
ratings.head()
# In[12]:
def replace_name(x):
return movies[movies['movieId']==x].title.values[0]
ratings.movieId = ratings.movieId.map(replace_name)
# In[13]:
ratings.head()
# In[14]:
M = ratings.pivot_table(index=['userId'],columns=['movieId'],values='rating')
# In[15]:
M.shape
# In[16]:
M
# In[17]:
def pearson(s1,s2):
s1_c = s1 - s1.mean()
s2_c = s2 - s2.mean()
return np.sum(s1_c * s2_c) / np.sqrt(np.sum(s1_c **2) * np.sum(s2_c**2))
# In[18]:
pearson(M['\'burbs, The (1989)'], M['10 Things I Hate About You (1999)'])
# In[19]:
pearson(M['Harry Potter and the Sorcerer\'s Stone (a.k.a. Harry Potter and the Philosopher\'s Stone) (2001)'],
M['Harry Potter and the Half-Blood Prince (2009)'])
# In[20]:
pearson(M['Mission: Impossible II (2000)'],M['Children of the Corn IV: The Gathering (1996)'])
# In[22]:
def get_recs(movie_name, M, num):
import numpy as np
reviews=[]
for title in M.columns:
if title == movie_name:
continue
cor = pearson(M[movie_name], M[title])
if np.isnan(cor):
continue
else :
reviews.append((title,cor))
reviews.sort(key=lambda tup: tup[1], reverse = True)
return reviews[:num]
# In[23]:
recs = get_recs('Toy Story (1995)', M ,10)
# In[24]:
recs[:10]
# In[25]:
anti_recs = get_recs('Toy Story (1995)',M,8551)
anti_recs[-10:]
# In[ ]: