-
Notifications
You must be signed in to change notification settings - Fork 1
/
udacourse3.py
2663 lines (2228 loc) · 102 KB
/
udacourse3.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import libraries
import numpy as np
import pandas as pd
import scipy.stats as stats
import udacourse3 #my library
import progressbar
import pickle
#graphs
import seaborn as sns
import matplotlib.patches as mpatches
import matplotlib.style as mstyles
import matplotlib.pyplot as mpyplots
#% matplotlib inline
#from matplotlib.pyplot import hist
#from matplotlib.figure import Figure
#First part
from statsmodels.stats import proportion as proptests
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
from time import time
#second part
from scipy.stats import spearmanr
from scipy.stats import kendalltau
from scipy.sparse import csr_matrix
from collections import defaultdict
from IPython.display import HTML
###Recomendation Engines - Collaborative Filter#################################
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_all_recommendation_collab(df_dist,
df_user_movie,
df_movie,
num_rec=10,
limit=100,
min_rating=7,
sort=False,
verbose=False):
'''This function creates a dictionnary for possible recommendations for
a set of users, preprocessed at df_dist dataset.
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering -Recommendations with
MovieTweetings - Collaborative Filtering
Input:
- df_dist (mandatory) - a preprocessed dataset wit the euclidian distancies
between two users (Pandas dataset)
- df_user_movie (mandatory) - dataset in the shape user by movie -
(Pandas dataset)
- df_movie (mandatory) - dataset in the shape for movies -
(Pandas dataset)
- num_rec (optional) - (int) number of recommended movies to return
- limit (optional) - extra parameter for fn_find_closest_neighbor -
it limits the number of neighbors (normally 100 is more than enough)
- min_rating (optional) - extra parameter for fn_movie_liked2() - it is
the worst score for considering a movie as liked (normally rate 7 is
enough)
- sort (optional) - extra parameter for fn_movie_liked2() - if you want
to show the best rated movies first (in this algorithm it is useless)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- all_recs - a dictionary where each key is a user_id and the value is
an array of recommended movie titles
'''
if verbose:
print('###function all_recommendations started')
begin = time()
#take all the unique users from df_dist dataset
user_all = np.unique(df_dist['user1'])
n_user_all = len(user_all)
if verbose:
print('*taken {} users to find recommendations'.format(n_user_all))
#create a dictionnary for keeping all recommendations for each user
all_rec = dict()
#iterate users calling the function for recommendations
for user in user_all:
if verbose:
print('*making recommendations for user', user)
filt_dist=df_dist[df_dist['user1'] == user]
all_rec[user] = udacourse3.fn_make_recommendation_collab(
filt_dist=filt_dist,
df_user_movie=df_user_movie,
df_movie=df_movie,
num_rec=num_rec,
limit=limit,
min_rating=min_rating,
sort=sort,
verbose=verbose)
end = time()
if verbose:
print('elapsed time: {:.4f}s'.format(end-begin))
return all_rec
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_calculate_distance(x,
y,
dist_type=None,
verbose=False):
'''This function calculates the euclidian distance between two points,
considering that X and Y are gived as fractions of distance.
Source: Udacity Data Science Course - Lesson 6 - Recomendation Engines -
Class 14 - Third Notebook - More Personalized Ways - Collaborative Filtering
& Content Based - Measuring Similarity
Inputs:
- x (mandatory) - an array of matching length to array y
- y (mandatory - an array of matching length to array x
- dist_type (mandatory) - if none is informed, returns False and nothing
is calculated:
* 'euclidean' - calculates the euclidean distance (you pass through
squares or edifices, as Superman)
* 'manhattan' - calculates the manhattan distance (so you need to turn
squares and yoy are not Superman!)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- distance - the euclidean distance between X and Y.
'''
if verbose:
print('###function calculate distances started')
begin = time()
if dist_type == None:
if verbose:
print('nothing was calculated, type was not informed')
return False
elif dist_type == 'euclidean':
if verbose:
print('calculating euclidian distance')
distance = np.linalg.norm(x - y)
elif dist_type == 'manhattan':
if verbose:
print('calculating manhattan distance')
distance = sum(abs(e - s) for s, e in zip(x, y))
end = time()
if verbose:
print('{} distance: {}'.format(dist_type, distance))
print('elapsed time: {:.4f}s'.format(end-begin))
return distance
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_compute_correlation(x,
y,
corr_type=None,
verbose=False):
'''This function calculates correlation between two variables A negative
value means an inverse correlation. Nearer to 1 or -1, stronger is the
correlation. More data you have, lower tends to be the error. Two points
give us a 1 or -1 value.
No correlation = 0 (a straight line). p-value is important too. A small
p-value means greater confidence in our guess.
Source: Udacity Data Science Course - Lesson 6 - Recomendation Engines -
Class 14 - Third Notebook - More Personalized Ways - Collaborative Filtering
& Content Based - Measuring Similarity
Inputs:
- x (mandatory) - an array of matching length to array y (numpy Array)
- y (mandatory) - an array of matching length to array x (numpy Array)
- corr_ype (mandatory) - {'kendall_tau', 'pearson', 'spearman'}
(default: None)
* 'kendall_tau' - Kendall´s Tau correlation coefficient. It uses a more
advancet technique and offers less variability on larger datasets.
It is not so computional efficient, as it runs on O(n^2).
* 'pearson' - is the most basic correlation coefficient. The denominator
just normalizes the raw coorelation value. Even for quadratic it keeps
suggesting a relationship.
* 'spearman' - Spearman Correlation can deal easily with outliers, as
it uses ranked data. It don´t follow normal distribution, or binomial,
and is an example of non-parametric function. Runs on basis O(nLog(n)).
from Udacity course notes:
"Spearman's correlation can have perfect relationships e.g.:(-1, 1)
that aren't linear. Even for quadratic it keeps
suggesting a relationship.
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output
- correlation_spearman - the Spearman correlation coefficient for comparing
x and y.values from (-1 to zero to +1).
'''
if verbose:
print('###function correlation started')
begin = time()
if corr_type is None:
if verbose:
print('no parameter calculated, you need to inform type')
return False
elif corr_type == 'intersection':
#transform series into datafames
df1 = x.to_frame()
df2 = y.to_frame()
correlation = pd.concat([df1, df2], axis=1).corr().iloc[0,1]
elif corr_type == 'kendall_tau':
#rank both data vectors
x = x.rank()
y = y.rank()
correlation = fn_onsquare(x, y, verbose=verbose)
elif corr_type == 'pearson':
correlation = fn_ologn(x, y, verbose=verbose)
elif corr_type == 'spearman':
#rank both data vectors
x = x.rank()
y = y.rank()
correlation = fn_ologn(x, y, verbose=verbose)
else:
if verbose:
print('invalid parameter')
return False
end = time()
if verbose:
print('{} correlation: {:.4f}'.format(corr_type, correlation))
print('elapsed time: {:4f}s'.format(end-begin))
return correlation
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_create_ranked_df(movie,
review,
verbose=True):
'''This function creates a ranked movies dataframe, that are sorted by
highest avg rating, more reviews, then time, and must have more than 4
ratings. Laterly this function can be forked for other purposes.
Source: Udacity Data Science Course - Lesson 6 - Recomendation Engines -
Class 5 - First Notebook - Intro to Recommendation data - Part I - Finding
Most Popular Movies.
Inputs:
- movie (mandatory) - the movies dataframe
- review (mandatory) - the reviews dataframe
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- ranked_movie - a dataframe with movies
'''
if verbose:
print('###function create_ranked_df started')
begin = time()
#for review - take mean, count, last rating
avg_rating = review.groupby('movie_id')['rating'].mean()
num_rating = review.groupby('movie_id')['rating'].count()
last_rating = pd.DataFrame(review.groupby('movie_id').max()['date'])
last_rating.columns = ['last_rating']
#create a new dataset for dates
rating_count_df = pd.DataFrame({'avg_rating': avg_rating,
'num_rating': num_rating})
rating_count_df = rating_count_df.join(last_rating)
#turn them only one dataset
movie_rec = movie.set_index('movie_id').join(rating_count_df)
#rank movies by the average rating, and then by the rating counting
ranked_movie = movie_rec.sort_values(['avg_rating', 'num_rating', 'last_rating'],
ascending=False)
#for the border of our list, get at least movies with more than 4 reviews
ranked_movie = ranked_movie[ranked_movie['num_rating'] >= 5]
end = time()
if verbose:
print('elapsed time: {:.4f}s'.format(end-begin))
return ranked_movie
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_create_train_test(review,
order_by,
train_size,
test_size,
verbose=False):
'''This function creates a train test for our FunkSVD system.
Source: Udacity Data Science Course - Lesson 7 - Matrix Factorization for
Recommendations - Third Notebook - Class 18 - How are we doing w/ FunkSVD
Inputs:
- review (mandatory) - (pandas df) dataframe to split into train and test
- order_by (mandatory) - (string) column name to sort by
- train_size (mandatory) - (int) number of rows in training set
- test_size (mandatory) - (int) number of columns in the test set
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Outputs:
- train_df - (pandas df) dataframe of the training set
- validate_df - (pandas df) dataframe of the test set
'''
if verbose:
print('###function create_train_test started')
begin = time()
review_new = review.sort_values(order_by)
train_df = review_new.head(train_size)
validate_df = review_new.iloc[train_size:train_size+test_size]
output = train_df, validate_df
end = time()
if verbose:
print('elapsed time: {:.4f}s'.format(end-begin))
return output
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_create_user_movie_dict(df_user_movie,
lower_filter=None,
verbose=False):
'''This function creates a dictionnary structure based on an array of movies
watched by a user.
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering -Recommendations with
MovieTweetings - Collaborative Filtering
Input:
- df_user_movie (mandatory) - Pandas dataset with all movies vs users at
the type user by movie, to be processed
or a dictionnary to be filtered (if it is a dict, please informa the
lower_filter parameter)
- lower_filter (mandatory) - elliminate users with a number of watched
videos below the number (Integer, default=None)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- movies_seen - a dictionary where each key is a user_id and the value is
an array of movie_ids. Creates the movies_seen dictionary
'''
if verbose:
print('###function create user movie started')
begin = time()
movie_registered = dict()
if type(df_user_movie) == dict: #dictionnary already processed
if lower_filter == None or lower_filter < 1:
if verbose:
print('run as post processing without a lower value don´t make sense')
return False
else:
if verbose:
print('running as post processing filter, for lower:', lower_filter)
for user, movie in df_user_movie.items():
if len(movie) > lower_filter:
movie_registered[user] = movie
else:
if verbose:
print('running as original dictionnary builder, for lower:', lower_filter)
n_users = df_user_movie.shape[0]
#creating a list of movies for each user
for num_user in range(1, n_users+1): #added lower_filter param
content = fn_movie_watched(df_user_movie=df_user_movie,
user_id=num_user,
lower_filter=lower_filter,
verbose=verbose)
if content is not None:
movie_registered[num_user] = content #if there is some movie
end = time()
if verbose:
print('elapsed time: {:.1f}s'.format(end-begin))
return movie_registered
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_create_user_movie(df_user_item,
verbose=False):
'''This function creates user by movie matrix. As it is normally a big data,
please make a pre-filter on rewiew dataset, using:
user_item = review[['user_id', 'movie_id', 'rating']]
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering - Recommendations with
MovieTweetings - Collaborative Filtering
Inputs:
- df_user_item (mandatory) - a Pandas dataset containing all reviews for
movies made by users, in a condensed way (a thin dataset)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- user_by_movie - a thick dataset, ordered by best rated first, each row
representing an user and each column a movie
(a sparse dataset, as most of the movies were never rated by each user!)
'''
if verbose:
print('###function create user by movie matrix started')
begin = time()
#remember that...
#df_user_item = df_review[['user_id', 'movie_id', 'rating']]
user_by_movie = df_user_item.groupby(['user_id', 'movie_id'])['rating'].max()
user_by_movie = user_by_movie.unstack()
end = time()
if verbose:
print('elapsed time: {:.1f}s'.format(end-begin))
return user_by_movie
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_find_closest_neighbor(filt_user1,
limit=None,
verbose=True):
'''This function takes a distance dataset and returns the closest users.
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering -Recommendations with
MovieTweetings - Collaborative Filtering
Inputs:
- filt_user1 (mandatory) - (Pandas dataset) the user_id of the individual
you want to find the closest users.
e.g: filt_user1=df_dists[df_dists['user1'] == user]
- limit (optional) - maximum number of closest users you want to return -
(integer, default=None)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- closest_neighbor - a numpy vector containing all closest users, from
the cloest ones until the end
'''
try:
user1 = filt_user1['user1'].iloc[0]
except TypeError:
if verbose:
print('you must inform a filtered dataset, see documentation')
return False
except IndexError:
if verbose:
print('an empty dataset was informed, this user does not exist')
return False
if verbose:
print('###function find closest neighbors started for user', user1)
begin = time()
filt_user2 = filt_user1[filt_user1['user2'] != user1]
closest_user = filt_user2.sort_values(by='eucl_dist')['user2']
closest_neighbor = np.array(closest_user)
if limit is not None:
closest_neighbor = closest_neighbor[:limit]
#if verbose:
# print('*limit:', len(closest_neighbor))
end = time()
if verbose:
print('returned {} neighbors'.format(len(closest_neighbor)))
print('elapsed time: {:.4f}s'.format(end-begin))
return closest_neighbor
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_find_similar_movie(df_dot_product,
df_movie,
movie_id,
verbose=False):
'''This function takes one movie_id, find the physical position of it in
our already processed dot product movie matrix and find the best similarity
rate. Then search on the dot product matrix movies with the same rate, for
their idxs (they are the most collinear from your movie-vector!). Finally,
it retrieves the movie names, based on these idxs.
It is similar to fn_find_closest_neighbor(), for Collaborative Filter.
Source: Udacity Data Science Course - Lesson 6 - Ways to Reccomend
Fifth Notebook - Class 21 - Content Based Recommendations
Inputs:
- df_dot_produt (mandatory) - your dot product matrix, with movies
collinearity values. You need to preprocess this earlier
- df_movie (mandatory) - your movies dataset, including movie names
- movie_id (mandatory) - a movie id to be asked for
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- similar_movies - an array of the titles of the most similar movies
'''
if verbose:
print('###function find similar movies started')
begin = time()
if verbose:
our_movie = df_movie[df_movie['movie_id'] == movie_id]['movie']
print('our movie iloc: ', our_movie) #.values[0])
#retrieve the physical position (iloc) of your movie
movie_idx = np.where(df_movie['movie_id'] == movie_id)[0][0]
#get the maximum similarity rate
max_rate = np.max(df_dot_product[movie_idx])
if verbose:
print('*max collinearity:', max_rate)
#retrieve the movie indices for maximum similarity
similar_idx = np.where(df_dot_product[movie_idx] == max_rate)[0]
#make an array, locating by position on dataset, the similars + title
similar_movie = fn_get_movie_name(df_movie=df_movie,
movie_id=similar_idx,
by_id=False,
as_list=False,
verbose=verbose)
end = time()
if verbose:
print('similar movies:', len(similar_movie))
print('elapsed time: {:.4f}s'.format(end-begin))
return similar_movie
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_FunkSVD(rating_mat,
latent_feature=4,
learning_rate=0.0001,
num_iter=100,
verbose=False):
'''
This function performs matrix factorization using a basic form of FunkSVD
with no regularization. This version don´t have a Sigma matrix for matrix
factorization!
Source: Udacity Data Science Course - Lesson 7 - Matrix Factorization for
Recommendations - Second Notebook - Class 15 - Implementing FunkSVD
Inputs:
- rating_mat (mandatory) - (numpy array) a matrix with users as rows,
movies as columns, and ratings as values
- latent_feature (optional) - (integer) the number of latent features
used for calculations (use this wisely, as each latent feature means
one dimension added to your model)
- learning_rate (optional) - (float) the learning rate used for each step
of iteration process (it is a kind of fine-grain process)
- num_iter (optional) - (integer) the maximum number of iterations (is a
kind of break method when things goes not so well)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Outputs:
- user_mat - (numpy array) a user by latent feature matrix
- movie_mat - (numpy array) a latent feature by movie matrix
'''
if verbose:
print('###function FunkSDV started')
begin = time()
#these values will be used later, so keep them!
num_user = rating_mat.shape[0]
num_movie = rating_mat.shape[1]
num_rating = np.count_nonzero(~np.isnan(rating_mat))
if verbose:
print('number of users:', num_user)
print('number of movies:', num_movie)
print('number of valid ratings:', num_rating)
#start the users and movies with completelly alleatory numbers
user_mat = np.random.rand(num_user, latent_feature)
movie_mat = np.random.rand(latent_feature, num_movie)
#Sum of Standard Errors start with zero, for our first iteration
sse_accum = 0
if verbose:
print('Optimizaiton Statistics')
print('Iteration Mean Squared Error')
#main iteration loop
for iteration in range(num_iter):
old_sse = sse_accum #save old value
sse_accum = 0 #new value
#user-movie pairs treatment
for i in range(num_user): #i for users
for j in range(num_movie):#j for movies
if rating_mat[i, j] > 0: #if there is some rating
#error = actual - dot prof of user and movie latents
diff = rating_mat[i, j] - np.dot(user_mat[i, :], movie_mat[:, j])
#tracking sum of sqr errors on the matrix
sse_accum += diff**2
#updating vals for each matrix, in the gradient way
for k in range(latent_feature):
user_mat[i, k] += learning_rate * (2*diff*movie_mat[k, j])
movie_mat[k, j] += learning_rate * (2*diff*user_mat[i, k])
mse_val = sse_accum / num_rating
if verbose:
print('{:3d} {:.6f}'.format(iteration+1, mse_val))
output = user_mat, movie_mat
end = time()
if verbose:
#https://stackoverflow.com/questions/27779677/how-to-format-elapsed-time-from-seconds-to-hours-minutes-seconds-and-milliseco
hour, remaining = divmod(end-begin, 3600)
minute, second = divmod(remaining, 60)
print('elapsed time: {:.4f}s ({:0>2}:{:0>2}:{:05.4f}s)'.format(end-begin,
int(hour),
int(minute),
second))
return output
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_get_movie_name(df_movie,
movie_id,
by_id=True,
as_list=True,
verbose=False):
'''This function finds a movie (or a list of movies) by its index and return
their titles as a list.
There are only two ways implemented at this moment:
First, it takes a single movie id and returns a single name, inside a list
(function default)
Second, it takes a list of movies idx and returns a numpy Array, with
multiple names.
(for providing service for fn_find_similar_movie())
Source: Udacity Data Science Course - Lesson 6 - Ways to Reccomend
Fifth Notebook - Class 21 - Content Based Recommendations
Inputs:
- df_movie (mandatory) - a preformated dataset of movies
- movie_id (mandatory) - a list of movie_id or one single movie_id
(depends on the case)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- movie - a list of names of movies
'''
if verbose:
print('###function get movie names started')
begin = time()
if as_list:
if by_id:
if verbose:
print('taking movies id, returning a list')
print('*function default')
try:
movie_list = list(df_movie[df_movie['movie_id'].isin(movie_id)]['movie'])
except TypeError:
movie_id = [movie_id]
movie_list = list(df_movie[df_movie['movie_id'].isin(movie_id)]['movie'])
else:
if verbose:
print('taking a movies idx, returning a list') #id=idx
print('not yet implemented!')
return False
else:
if by_id:
if verbose:
print('taking a movies id, returning numpy vector')
print('not yet implemented!')
return False
else:
if verbose:
print('taking movies idx, returning a list')
print('*default for fn_find_similar_movie') #id=idx
movie_list = np.array(df_movie.iloc[movie_id]['movie'])
end = time()
if verbose:
print('elapsed time: {:.6f}s'.format(end-begin))
return movie_list
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_make_recommendation_collab(filt_dist,
df_user_movie,
df_movie,
num_rec=10,
limit=None,
min_rating=7,
sort=False,
verbose=False):
'''This function takes filtered distances from a focus user and find the
closest users. Then retrieves already watched movies by the user, just to
not recommend them. And in sequence, iterate over closest neighbors, retrieve
their liked movies and it they were not already seen, put in a recommend
list. For finish, transform movies ids into movies names and return a list.
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering - Recommendations with
MovieTweetings - Collaborative Filtering
Input:
- filt_dist (mandatory) - a user by movie type dataset, created with the
function fn_create_user_item(), from user distances dataset -
(Pandas dataset)
e.g.: filt_dist=df_dist[df_dist['user1'] == user]
- df_user_movie (mandatory) - dataset in the shape user by movie -
(Pandas dataset)
- df_movie (mandatory) - dataset in she shape movies -
(Pandas dataset)
- num_rec (optional) - (int) number of recommended movies to return
- limit (optional) - extra parameter for fn_find_closest_neighbor -
it limits the number of neighbors (normally 100 is more than enough)
- min_rating (optional) - extra parameter for fn_movie_liked2() - it is
the worst score for considering a movie as liked (normally rate 7 is
enough)
- sort (optional) - extra parameter for fn_movie_liked2() - if you want
to show the best rated movies first (in this algorithm it is useless)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- recommendations - a list of movies - if there are "num_recs" recommendations return this many
otherwise return the total number of recommendations available for the "user"
which may just be an empty list
'''
try:
user_id = filt_dist['user1'].iloc[0]
except TypeError:
if verbose:
print('you must inform a filtered dataset, see documentation')
return False
except IndexError:
if verbose:
print('an empty dataset was informed, this user does not exist')
return False
if verbose:
print('###function make recommendations started')
begin = time()
# movies_seen by user (we don't want to recommend these)
movie_user = df_user_movie.loc[user_id].dropna()
movie_seen = movie_user.index.tolist()
if verbose:
print('*seen {} movies by user {} - first is {}'.format(len(movie_seen), user_id, movie_seen[0]))
closest_neighbor = udacourse3.fn_find_closest_neighbor(filt_user1=filt_dist,
limit=limit,
verbose=verbose)
if verbose:
print('*{} closest neigbors'.format(len(closest_neighbor)))
#creating your recommended array
rec = np.array([])
#from closest neighbors, 1-take move & 2-that had not been watched
for i in range (0, len(closest_neighbor)):
neighbor_id = closest_neighbor[i]
filt_user = df_user_movie.loc[neighbor_id].dropna()
if verbose:
print('comparing with neighbor', neighbor_id)
neighbor_like = udacourse3.fn_movie_liked2(item=filt_user,
min_rating=7,
sort=False,
verbose=False)
if verbose:
print('...that liked {} movies'.format(len(neighbor_like)))
#take recommendations by difference
new_rec = np.setdiff1d(neighbor_like,
movie_seen,
assume_unique=True)
if verbose:
print('...and so, {} were new!'.format(len(new_rec)))
#store rec
rec = np.unique(np.concatenate([new_rec, rec], axis=0))
if verbose:
print('...now I have {} movies in my record'.format(len(rec)))
#print(rec)
#print()
#if store is OK, exit the engine
if len(rec) > num_rec-1:
break
#take the titles
recommendation = udacourse3.fn_movie_name(df_movie=df_movie,
movie_id=rec,
verbose=False)
end = time()
if verbose:
print('elapsed time: {:.4f}s'.format(end-begin))
return recommendation
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_make_recommendation_content(df_dot_product,
df_movie,
user,
verbose=False):
'''This function...
Source: Udacity Data Science Course - Lesson 6 - Ways to Reccomend
Fifth Notebook - Class 21 - Content Based Recommendations
Input:
- user (mandatory) -
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- recommendation - a Python dictionary containing user as keys and
values for recommendations
'''
if verbose:
print('###function make recommendations started')
begin = time()
# Create dictionary to return with users and ratings
recommendation = defaultdict(set)
# How many users for progress bar
try:
num_user = len(user)
except TypeError:
user = [user]
if verbose:
print('only one user was informed, putting it in a list')
num_user = len(user)
# Create the progressbar
counter = 0
bar = progressbar.ProgressBar(maxval=num_user+1,
widgets=[progressbar.Bar('=', '[', ']'),
' ',
progressbar.Percentage()])
bar.start()
#iterate user by user
for one_user in user:
#only updating the progress bar
counter += 1
bar.update(counter)
#taking only the reviews seen by this user
review_temp = ranked_review[ranked_review['user_id'] == one_user]
movie_temp = np.array(review_temp['movie_id'])
movie_name = np.array(udacourse3.fn_get_movie_name(
df_movie=movie,
movie_id=movie_temp,
verbose=verbose))
#iterate each of these movies (highest ranked first)
#taking only the movies that were not watched by this user
#and that are most similar - these are elected to be the
#recommendations - I need only 10 of them!
#you keep going until there are no more movies in the list
#of this user
for movie_id in movie_temp:
recommended_movie = udacourse3.fn_find_similar_movie(
df_dot_product=dot_prod_movie,
df_movie=df_movie,
movie_id=movie_id,
verbose=True)
temp_recommendation = np.setdiff1d(recommended_movie, movie_name)
recommendation[one_user].update(temp_recommendation)
#if you have the enough number of recommendations, you will stop
if len(recommendation[one_user]) >= 10:
break
bar.finish()
end = time()
if verbose:
print('elapsed time: {:.2f}s'.format(end-begin))
return recommendation
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_movie_liked2(item,
min_rating=7,
sort=True,
verbose=False):
'''This function takes all the items for one user and return the best rated
items.
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering -Recommendations with
MovieTweetings - Collaborative Filtering
Inputs:
- item (mandatory) - a dataset on the shape user by movie, filtered
for an individual user.
e.g. item=user_by_movie.loc[user_id].dropna()
- min_rating (optional) - the trigger point to consider an item to be
considered "nice" for an user (integer, default=7)
- sort (optional) - if you want to show the most rated items first
(Boolean, default=True)
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- movie_liked - an array of movies the user has watched and liked
'''
user = item.name
if verbose:
print('###function movies liked started for user', user)
begin = time()
movie_liked = item[item > 7]
if sort:
if verbose:
print('*sorting the list - best rated first')
movie_liked = movie_liked.sort_values(ascending=False)
movie_liked = np.array(movie_liked.index)
end = time()
if verbose:
print('elapsed time: {:.4f}s'.format(end-begin))
return movie_liked
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_movie_name(df_movie,
movie_id,
verbose=False):
'''This function takes a list of movies_id (liked from other user) and
returns ne movie titles
Source: Udacity Data Science Course - Lesson 6 - Identifying Reccomendations
Forth Notebook - Class 17 - Collaborative Filtering -Recommendations with
MovieTweetings - Collaborative Filtering
Inputs:
- df_movie (mandatory) - the movies dataset - Pandas Dataset
- movie_id (mandatory) - a numpy vector containing a list of movie_ids
- verbose (optional) - if you want some verbosity in your function -
(Boolean, default=False)
Output:
- movies - a list of movie names associated with the movie_ids (python
list)
'''
if verbose:
print('###function movie names started')
begin = time()
movie_get = df_movie[df_movie['movie_id'].isin(movie_id)]
movie_list = movie_get['movie'].to_list()
end = time()
if verbose:
print('elapsed time: {:.4f}s'.format(end-begin))
return movie_list
#########1#########2#########3#########4#########5#########6#########7#########8
def fn_movie_watched(df_user_movie,
user_id,
lower_filter=None,
verbose=False):
'''This function creates a array structure. Keys are users, content is
a list of movies seen. DF is a user by movie dataset, created with the
function fn_create_user_item.