Skip to content

Commit d192bee

Browse files
committed
ENH Improve code readability
This is likely to be slightly slower, but it's easier to explain and this code is to teach the concepts, not raw speed.
1 parent 83d426c commit d192bee

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

‎ch08/corrneighbours.py‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,25 @@ def predict(otrain):
1818
norm=NormalizePositive()
1919
train=norm.fit_transform(otrain.T).T
2020

21-
proximity=distance.pdist(binary, 'correlation')
22-
proximity=distance.squareform(proximity)
21+
dists=distance.pdist(binary, 'correlation')
22+
dists=distance.squareform(dists)
2323

24-
neighbors=proximity.argsort(axis=1)
24+
neighbors=dists.argsort(axis=1)
2525
filled=train.copy()
2626
foruinrange(filled.shape[0]):
27+
# n_u are the neighbors of user
2728
n_u=neighbors[u, 1:]
28-
t_u=train[n_u].T
29-
b_u=binary[n_u].T
3029
forminrange(filled.shape[1]):
31-
revs=t_u[m]
32-
brevs=b_u[m]
33-
revs=revs[brevs]
30+
# This code could be faster using numpy indexing trickery as the
31+
# cost of readibility (this is left as an exercise to the reader):
32+
revs= [train[neigh, m]
33+
forneighinn_u
34+
ifbinary[neigh, m]]
3435
iflen(revs):
35-
revs=revs[:len(revs)//2+1]
36+
n=len(revs)
37+
n//=2
38+
n+=1
39+
revs=revs[:n]
3640
filled[u,m] =revs.mean()
3741

3842
returnnorm.inverse_transform(filled.T).T

0 commit comments

Comments
(0)