ex8_cofi.m 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. %% Machine Learning Online Class
  2. % Exercise 8 | Anomaly Detection and Collaborative Filtering
  3. %
  4. % Instructions
  5. % ------------
  6. %
  7. % This file contains code that helps you get started on the
  8. % exercise. You will need to complete the following functions:
  9. %
  10. % estimateGaussian.m
  11. % selectThreshold.m
  12. % cofiCostFunc.m
  13. %
  14. % For this exercise, you will not need to change any code in this file,
  15. % or any other files other than those mentioned above.
  16. %
  17. %% =============== Part 1: Loading movie ratings dataset ================
  18. % You will start by loading the movie ratings dataset to understand the
  19. % structure of the data.
  20. %
  21. fprintf('Loading movie ratings dataset.\n\n');
  22. % Load data
  23. load ('ex8_movies.mat');
  24. % Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies on
  25. % 943 users
  26. %
  27. % R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a
  28. % rating to movie i
  29. % From the matrix, we can compute statistics like average rating.
  30. fprintf('Average rating for movie 1 (Toy Story): %f / 5\n\n', ...
  31. mean(Y(1, R(1, :))));
  32. % We can "visualize" the ratings matrix by plotting it with imagesc
  33. imagesc(Y);
  34. ylabel('Movies');
  35. xlabel('Users');
  36. fprintf('\nProgram paused. Press enter to continue.\n');
  37. pause;
  38. %% ============ Part 2: Collaborative Filtering Cost Function ===========
  39. % You will now implement the cost function for collaborative filtering.
  40. % To help you debug your cost function, we have included set of weights
  41. % that we trained on that. Specifically, you should complete the code in
  42. % cofiCostFunc.m to return J.
  43. % Load pre-trained weights (X, Theta, num_users, num_movies, num_features)
  44. load ('ex8_movieParams.mat');
  45. % Reduce the data set size so that this runs faster
  46. num_users = 4; num_movies = 5; num_features = 3;
  47. X = X(1:num_movies, 1:num_features);
  48. Theta = Theta(1:num_users, 1:num_features);
  49. Y = Y(1:num_movies, 1:num_users);
  50. R = R(1:num_movies, 1:num_users);
  51. % Evaluate cost function
  52. J = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...
  53. num_features, 0);
  54. fprintf(['Cost at loaded parameters: %f '...
  55. '\n(this value should be about 22.22)\n'], J);
  56. fprintf('\nProgram paused. Press enter to continue.\n');
  57. pause;
  58. %% ============== Part 3: Collaborative Filtering Gradient ==============
  59. % Once your cost function matches up with ours, you should now implement
  60. % the collaborative filtering gradient function. Specifically, you should
  61. % complete the code in cofiCostFunc.m to return the grad argument.
  62. %
  63. fprintf('\nChecking Gradients (without regularization) ... \n');
  64. % Check gradients by running checkNNGradients
  65. checkCostFunction;
  66. fprintf('\nProgram paused. Press enter to continue.\n');
  67. pause;
  68. %% ========= Part 4: Collaborative Filtering Cost Regularization ========
  69. % Now, you should implement regularization for the cost function for
  70. % collaborative filtering. You can implement it by adding the cost of
  71. % regularization to the original cost computation.
  72. %
  73. % Evaluate cost function
  74. J = cofiCostFunc([X(:) ; Theta(:)], Y, R, num_users, num_movies, ...
  75. num_features, 1.5);
  76. fprintf(['Cost at loaded parameters (lambda = 1.5): %f '...
  77. '\n(this value should be about 31.34)\n'], J);
  78. fprintf('\nProgram paused. Press enter to continue.\n');
  79. pause;
  80. %% ======= Part 5: Collaborative Filtering Gradient Regularization ======
  81. % Once your cost matches up with ours, you should proceed to implement
  82. % regularization for the gradient.
  83. %
  84. %
  85. fprintf('\nChecking Gradients (with regularization) ... \n');
  86. % Check gradients by running checkNNGradients
  87. checkCostFunction(1.5);
  88. fprintf('\nProgram paused. Press enter to continue.\n');
  89. pause;
  90. %% ============== Part 6: Entering ratings for a new user ===============
  91. % Before we will train the collaborative filtering model, we will first
  92. % add ratings that correspond to a new user that we just observed. This
  93. % part of the code will also allow you to put in your own ratings for the
  94. % movies in our dataset!
  95. %
  96. movieList = loadMovieList();
  97. % Initialize my ratings
  98. my_ratings = zeros(1682, 1);
  99. % Check the file movie_idx.txt for id of each movie in our dataset
  100. % For example, Toy Story (1995) has ID 1, so to rate it "4", you can set
  101. my_ratings(1) = 4;
  102. % Or suppose did not enjoy Silence of the Lambs (1991), you can set
  103. my_ratings(98) = 2;
  104. % We have selected a few movies we liked / did not like and the ratings we
  105. % gave are as follows:
  106. my_ratings(7) = 3;
  107. my_ratings(12)= 5;
  108. my_ratings(54) = 4;
  109. my_ratings(64)= 5;
  110. my_ratings(66)= 3;
  111. my_ratings(69) = 5;
  112. my_ratings(183) = 4;
  113. my_ratings(226) = 5;
  114. my_ratings(355)= 5;
  115. fprintf('\n\nNew user ratings:\n');
  116. for i = 1:length(my_ratings)
  117. if my_ratings(i) > 0
  118. fprintf('Rated %d for %s\n', my_ratings(i), ...
  119. movieList{i});
  120. end
  121. end
  122. fprintf('\nProgram paused. Press enter to continue.\n');
  123. pause;
  124. %% ================== Part 7: Learning Movie Ratings ====================
  125. % Now, you will train the collaborative filtering model on a movie rating
  126. % dataset of 1682 movies and 943 users
  127. %
  128. fprintf('\nTraining collaborative filtering...\n');
  129. % Load data
  130. load('ex8_movies.mat');
  131. % Y is a 1682x943 matrix, containing ratings (1-5) of 1682 movies by
  132. % 943 users
  133. %
  134. % R is a 1682x943 matrix, where R(i,j) = 1 if and only if user j gave a
  135. % rating to movie i
  136. % Add our own ratings to the data matrix
  137. Y = [my_ratings Y];
  138. R = [(my_ratings ~= 0) R];
  139. % Normalize Ratings
  140. [Ynorm, Ymean] = normalizeRatings(Y, R);
  141. % Useful Values
  142. num_users = size(Y, 2);
  143. num_movies = size(Y, 1);
  144. num_features = 10;
  145. % Set Initial Parameters (Theta, X)
  146. X = randn(num_movies, num_features);
  147. Theta = randn(num_users, num_features);
  148. initial_parameters = [X(:); Theta(:)];
  149. % Set options for fmincg
  150. options = optimset('GradObj', 'on', 'MaxIter', 100);
  151. % Set Regularization
  152. lambda = 10;
  153. theta = fmincg (@(t)(cofiCostFunc(t, Ynorm, R, num_users, num_movies, ...
  154. num_features, lambda)), ...
  155. initial_parameters, options);
  156. % Unfold the returned theta back into U and W
  157. X = reshape(theta(1:num_movies*num_features), num_movies, num_features);
  158. Theta = reshape(theta(num_movies*num_features+1:end), ...
  159. num_users, num_features);
  160. fprintf('Recommender system learning completed.\n');
  161. fprintf('\nProgram paused. Press enter to continue.\n');
  162. pause;
  163. %% ================== Part 8: Recommendation for you ====================
  164. % After training the model, you can now make recommendations by computing
  165. % the predictions matrix.
  166. %
  167. p = X * Theta';
  168. my_predictions = p(:,1) + Ymean;
  169. movieList = loadMovieList();
  170. [r, ix] = sort(my_predictions, 'descend');
  171. fprintf('\nTop recommendations for you:\n');
  172. for i=1:10
  173. j = ix(i);
  174. fprintf('Predicting rating %.1f for movie %s\n', my_predictions(j), ...
  175. movieList{j});
  176. end
  177. fprintf('\n\nOriginal ratings provided:\n');
  178. for i = 1:length(my_ratings)
  179. if my_ratings(i) > 0
  180. fprintf('Rated %d for %s\n', my_ratings(i), ...
  181. movieList{i});
  182. end
  183. end