1 // Core Part about Movie Recommendations   | 
     1 // Core Part about Movie Recommendations   | 
     2 // at Danube.co.uk  | 
     2 // at Danube.co.uk  | 
     3 //===========================================  | 
     3 //===========================================  | 
     4   | 
     4   | 
     5 object CW7b { | 
         | 
     6   | 
         | 
     7 import io.Source  | 
     5 import io.Source  | 
     8 import scala.util._  | 
     6 import scala.util._  | 
         | 
     7   | 
         | 
     8 object CW7b { // for purposes of generating a jar | 
     9   | 
     9   | 
    10 // (1) Implement the function get_csv_url which takes an url-string  | 
    10 // (1) Implement the function get_csv_url which takes an url-string  | 
    11 //     as argument and requests the corresponding file. The two urls  | 
    11 //     as argument and requests the corresponding file. The two urls  | 
    12 //     of interest are ratings_url and movies_url, which correspond   | 
    12 //     of interest are ratings_url and movies_url, which correspond   | 
    13 //     to CSV-files.  | 
    13 //     to CSV-files.  | 
    14 //  | 
    14 //     The function should ReTurn the CSV file appropriately broken  | 
    15 //     The function should ReTurn the CSV-file appropriately broken  | 
         | 
    16 //     up into lines, and the first line should be dropped (that is without  | 
    15 //     up into lines, and the first line should be dropped (that is without  | 
    17 //     the header of the CSV-file). The result is a list of strings (lines  | 
    16 //     the header of the CSV file). The result is a list of strings (lines  | 
    18 //     in the file).  | 
    17 //     in the file).  | 
    19   | 
    18   | 
    20 def get_csv_url(url: String) : List[String] = { | 
    19 def get_csv_url(url: String) : List[String] = { | 
    21     Try(Source.fromURL(url)("UTF-8").mkString.split("\n").toList.tail).getOrElse(List()) | 
    20   val csv = Source.fromURL(url)("ISO-8859-1") | 
         | 
    21   csv.mkString.split("\n").toList.drop(1) | 
    22 }  | 
    22 }  | 
    23   | 
         | 
    24   | 
    23   | 
    25 val ratings_url = """https://nms.kcl.ac.uk/christian.urban/ratings.csv"""  | 
    24 val ratings_url = """https://nms.kcl.ac.uk/christian.urban/ratings.csv"""  | 
    26 val movies_url = """https://nms.kcl.ac.uk/christian.urban/movies.csv"""  | 
    25 val movies_url = """https://nms.kcl.ac.uk/christian.urban/movies.csv"""  | 
    27   | 
    26   | 
    28 // testcases  | 
    27 // test cases  | 
    29 //-----------  | 
    28   | 
    30 // val ratings = get_csv_url(ratings_url)  | 
    29 //val ratings = get_csv_url(ratings_url)  | 
    31 // val movies = get_csv_url(movies_url)  | 
    30 //val movies = get_csv_url(movies_url)  | 
    32   | 
    31   | 
    33 //ratings.length  // 87313  | 
    32 //ratings.length  // 87313  | 
    34 //movies.length   // 9742  | 
    33 //movies.length   // 9742  | 
    35   | 
    34   | 
    36   | 
    35 // (2) Implement two functions that process the CSV files. The ratings  | 
    37   | 
         | 
    38 // (2) Implement two functions that process the CSV-files from (1). The ratings  | 
         | 
    39 //     function filters out all ratings below 4 and ReTurns a list of   | 
    36 //     function filters out all ratings below 4 and ReTurns a list of   | 
    40 //     (userID, movieID) pairs. The movies function just ReTurns a list   | 
    37 //     (userID, movieID) pairs. The movies function just ReTurns a list   | 
    41 //     of (movieID, title) pairs.  | 
    38 //     of (movieId, title) pairs.  | 
    42   | 
    39   | 
    43   | 
    40   | 
    44 def process_ratings(lines: List[String]) : List[(String, String)] = { | 
    41 def process_ratings(lines: List[String]) : List[(String, String)] = { | 
    45     val filteredLines = lines.filter(line => line.split(",")(2).toInt >= 4) | 
    42   for (cols <- lines.map(_.split(",").toList);  | 
    46     filteredLines.map(line => (line.split(",")(0), line.split(",")(1))) | 
    43        if (cols(2).toFloat >= 4)) yield (cols(0), cols(1))    | 
    47 }  | 
    44 }  | 
    48   | 
    45   | 
    49 def process_movies(lines: List[String]) : List[(String, String)] = { | 
    46 def process_movies(lines: List[String]) : List[(String, String)] = { | 
    50     lines.map(line => (line.split(",")(0), line.split(",")(1))) | 
    47   for (cols <- lines.map(_.split(",").toList)) yield (cols(0), cols(1))   | 
    51 }  | 
    48 }  | 
    52   | 
    49   | 
         | 
    50 // test cases  | 
    53   | 
    51   | 
    54 // testcases  | 
    52 //val good_ratings = process_ratings(ratings)  | 
    55 //-----------  | 
    53 //val movie_names = process_movies(movies)  | 
    56 // val good_ratings = process_ratings(ratings)  | 
         | 
    57 // val movie_names = process_movies(movies)  | 
         | 
    58   | 
    54   | 
    59 //good_ratings.length   //48580  | 
    55 //good_ratings.length   //48580  | 
    60 //movie_names.length    // 9742  | 
    56 //movie_names.length    // 9742  | 
    61   | 
    57   | 
         | 
    58 //==============================================  | 
         | 
    59 // Do not change anything below, unless you want   | 
         | 
    60 // to submit the file for the advanced part 3!  | 
         | 
    61 //==============================================  | 
         | 
    62   | 
         | 
    63   | 
         | 
    64 // (3) Implement a grouping function that calulates a map  | 
         | 
    65 //     containing the userIds and all the corresponding recommendations   | 
         | 
    66 //     (list of movieIds). This  should be implemented in a tail  | 
         | 
    67 //     recursive fashion, using a map m as accumulator. This map  | 
         | 
    68 //     is set to Map() at the beginning of the claculation.  | 
         | 
    69   | 
         | 
    70 def groupById(ratings: List[(String, String)],   | 
         | 
    71               m: Map[String, List[String]]) : Map[String, List[String]] = ratings match { | 
         | 
    72   case Nil => m  | 
         | 
    73   case (id, mov) :: rest => { | 
         | 
    74     val old_ratings = m.getOrElse (id, Nil)  | 
         | 
    75     val new_ratings = m + (id -> (mov :: old_ratings))  | 
         | 
    76     groupById(rest, new_ratings)  | 
         | 
    77   }  | 
         | 
    78 }  | 
         | 
    79   | 
         | 
    80 //  | 
         | 
    81 //val ls = List(("1", "a"), ("2", "a"), ("1", "c"), ("2", "a"), ("1", "c")) | 
         | 
    82 //  | 
         | 
    83 //val m = groupById(ls, Map())  | 
         | 
    84 //  | 
         | 
    85 //m.getOrElse("1", Nil).count(_ == "c") // => 2 | 
         | 
    86 //m.getOrElse("1", Nil).count(_ == "a") // => 1 | 
         | 
    87   | 
         | 
    88 // test cases  | 
         | 
    89 //val ratings_map = groupById(good_ratings, Map())  | 
         | 
    90 //groupById(good_ratings, Map()).get("214") | 
         | 
    91 //groupById(good_ratings, Map()).toList.minBy(_._2.length)  | 
         | 
    92 //val movies_map = movie_names.toMap  | 
         | 
    93   | 
         | 
    94 //ratings_map.get("414").get.map(movies_map.get(_)) // most prolific recommender with 1227 positive ratings | 
         | 
    95 //ratings_map.get("474").get.map(movies_map.get(_)) // second-most prolific recommender with 787 positive ratings | 
         | 
    96 //ratings_map.get("214").get.map(movies_map.get(_)) // least prolific recommender with only 1 positive rating | 
    62   | 
    97   | 
    63   | 
    98   | 
    64   | 
    99   | 
    65 // (3) Implement a grouping function that calculates a Map  | 
   100 //(4) Implement a function that takes a ratings map and a movie_name as argument.  | 
    66 //     containing the userIDs and all the corresponding recommendations   | 
   101 // The function calculates all suggestions containing  | 
    67 //     (list of movieIDs). This  should be implemented in a tail  | 
   102 // the movie mov in its recommendations. It ReTurns a list of all these  | 
    68 //     recursive fashion, using a Map m as accumulator. This Map m  | 
   103 // recommendations (each of them is a list and needs to have mov deleted,   | 
    69 //     is set to Map() at the beginning of the calculation.  | 
   104 // otherwise it might happen we recommend the same movie).  | 
    70   | 
   105   | 
    71 def groupById(ratings: List[(String, String)],   | 
   106 def favourites(m: Map[String, List[String]], mov: String) : List[List[String]] =   | 
    72               m: Map[String, List[String]]) : Map[String, List[String]] = { | 
   107   (for (id <- m.keys.toList;  | 
    73     if (ratings.length == 0) m  | 
   108         if m(id).contains(mov)) yield m(id).filter(_ != mov))  | 
    74     else { | 
         | 
    75         val firstUser = ratings(0)._1  | 
         | 
    76         val userRatings = ratings.filter(r => r._1 == firstUser)  | 
         | 
    77         val movieIds = userRatings.map(r => r._2)  | 
         | 
    78         val newMap = m + (firstUser -> movieIds)  | 
         | 
    79         groupById(ratings.filter(r => r._1 != firstUser), newMap)  | 
         | 
    80     }  | 
         | 
    81 }  | 
         | 
    82   | 
         | 
    83   | 
         | 
    84 // testcases  | 
         | 
    85 //-----------  | 
         | 
    86 //val ratings_map = groupById(good_ratings, Map())  | 
         | 
    87 //val movies_map = movie_names.toMap  | 
         | 
    88   | 
         | 
    89 //ratings_map.get("414").get.map(movies_map.get(_))  | 
         | 
    90 //    => most prolific recommender with 1227 positive ratings  | 
         | 
    91   | 
         | 
    92 //ratings_map.get("474").get.map(movies_map.get(_))  | 
         | 
    93 //    => second-most prolific recommender with 787 positive ratings  | 
         | 
    94   | 
         | 
    95 //ratings_map.get("214").get.map(movies_map.get(_))  | 
         | 
    96 //    => least prolific recommender with only 1 positive rating  | 
         | 
    97   | 
   109   | 
    98   | 
   110   | 
    99   | 
   111   | 
   100 // (4) Implement a function that takes a ratings map and a movie_name as argument.  | 
   112 // test cases  | 
   101 //     The function calculates all suggestions containing  | 
         | 
   102 //     the movie in its recommendations. It ReTurns a list of all these  | 
         | 
   103 //     recommendations (each of them is a list and needs to have the movie deleted,   | 
         | 
   104 //     otherwise it might happen we recommend the same movie).  | 
         | 
   105   | 
         | 
   106   | 
         | 
   107 def favourites(m: Map[String, List[String]], mov: String) : List[List[String]] = { | 
         | 
   108     val movieLists = m.map(r => r._2).toList.filter(_.contains(mov))  | 
         | 
   109     for (movieList <- movieLists) yield { | 
         | 
   110         movieList.filter(_!=mov)  | 
         | 
   111     }  | 
         | 
   112 }  | 
         | 
   113   | 
         | 
   114   | 
         | 
   115 // testcases  | 
         | 
   116 //-----------  | 
         | 
   117 // movie ID "912" -> Casablanca (1942)  | 
   113 // movie ID "912" -> Casablanca (1942)  | 
   118 //          "858" -> Godfather  | 
   114 //          "858" -> Godfather  | 
   119 //          "260" -> Star Wars: Episode IV - A New Hope (1977)  | 
   115 //          "260" -> Star Wars: Episode IV - A New Hope (1977)  | 
   120   | 
   116   | 
   121 //favourites(ratings_map, "912").length  // => 80  | 
   117 //favourites(ratings_map, "912").length  // => 80  | 
   123 // That means there are 80 users that recommend the movie with ID 912.  | 
   119 // That means there are 80 users that recommend the movie with ID 912.  | 
   124 // Of these 80  users, 55 gave a good rating to movie 858 and  | 
   120 // Of these 80  users, 55 gave a good rating to movie 858 and  | 
   125 // 52 a good rating to movies 260, 318, 593.  | 
   121 // 52 a good rating to movies 260, 318, 593.  | 
   126   | 
   122   | 
   127   | 
   123   | 
         | 
   124 // (5) Implement a suggestions function which takes a rating  | 
         | 
   125 // map and a movie_name as arguments. It calculates all the recommended  | 
         | 
   126 // movies sorted according to the most frequently suggested movie(s) first.  | 
   128   | 
   127   | 
   129 // (5) Implement a suggestions function which takes a rating  | 
   128 // needed in Scala 2.13.  | 
   130 //     map and a movie_name as arguments. It calculates all the recommended  | 
   129    | 
   131 //     movies sorted according to the most frequently suggested movie(s) first.  | 
   130 def mapValues[S, T, R](m: Map[S, T], f: T => R) =  | 
   132   | 
   131   m.map { case (x, y) => (x, f(y)) } | 
   133   | 
   132   | 
   134 def suggestions(recs: Map[String, List[String]],   | 
   133 def suggestions(recs: Map[String, List[String]],   | 
   135                 mov_name: String) : List[String] = { | 
   134                     mov_name: String) : List[String] = { | 
   136     val favs = favourites(recs, mov_name).flatten  | 
   135   val favs = favourites(recs, mov_name).flatten  | 
   137     favs.map(x => (x, favs.count(_==x)))  | 
   136   val favs_counted = mapValues(favs.groupBy(identity), (v:List[String]) => v.size).toList  | 
   138         .sortBy(_._1)  | 
   137   val favs_sorted = favs_counted.sortBy(_._2).reverse  | 
   139         .reverse  | 
   138   favs_sorted.map(_._1)  | 
   140         .sortBy(_._2)  | 
         | 
   141         .reverse  | 
         | 
   142         .distinct  | 
         | 
   143         .map(_._1)  | 
         | 
   144 }  | 
   139 }  | 
   145   | 
   140   | 
         | 
   141 // check  | 
         | 
   142 // groupMap is equivalent to groupBy(key).mapValues(_.map(f))  | 
   146   | 
   143   | 
   147 // testcases  | 
   144 // test cases  | 
   148 //-----------  | 
         | 
   149   | 
   145   | 
   150 //suggestions(ratings_map, "912")  | 
   146 //suggestions(ratings_map, "912")  | 
   151 //suggestions(ratings_map, "912").length    | 
   147 //suggestions(ratings_map, "912").length    | 
   152 // => 4110 suggestions with List(858, 260, 318, 593, ...)  | 
   148 // => 4110 suggestions with List(858, 260, 318, 593, ...)  | 
   153 //    being the most frequently suggested movies  | 
   149 //    being the most frequently suggested movies  | 
   154   | 
   150   | 
   155   | 
   151 // (6) Implement recommendations functions which generates at most  | 
   156   | 
   152 // *two* of the most frequently suggested movies. It Returns the   | 
   157 // (6) Implement a recommendations function which generates at most  | 
   153 // actual movie names, not the movieIDs.  | 
   158 //     *two* of the most frequently suggested movies. It ReTurns the   | 
         | 
   159 //     actual movie names, not the movieIDs.  | 
         | 
   160   | 
         | 
   161   | 
   154   | 
   162 def recommendations(recs: Map[String, List[String]],  | 
   155 def recommendations(recs: Map[String, List[String]],  | 
   163                     movs: Map[String, String],  | 
   156                    movs: Map[String, String],  | 
   164                     mov_name: String) : List[String] = { | 
   157                    mov_name: String) : List[String] =  | 
   165     val sug = suggestions(recs, mov_name)  | 
   158   suggestions(recs, mov_name).take(2).map(movs.get(_).get)                   | 
   166     val toptwo = sug.take(2)  | 
         | 
   167     if (toptwo.length == 0) Nil  | 
         | 
   168     else toptwo.map(movs(_))  | 
         | 
   169 }  | 
         | 
   170   | 
         | 
   171   | 
   159   | 
   172   | 
   160   | 
   173 // testcases  | 
   161 // testcases  | 
   174 //-----------  | 
   162   | 
   175 // recommendations(ratings_map, movies_map, "912")  | 
   163 // recommendations(ratings_map, movies_map, "912")  | 
   176 //   => List(Godfather, Star Wars: Episode IV - A NewHope (1977))  | 
   164 //   => List(Godfather, Star Wars: Episode IV - A NewHope (1977))  | 
   177   | 
   165   | 
   178 //recommendations(ratings_map, movies_map, "260")  | 
   166 //recommendations(ratings_map, movies_map, "260")  | 
   179 //   => List(Star Wars: Episode V - The Empire Strikes Back (1980),   | 
   167 //   => List(Star Wars: Episode V - The Empire Strikes Back (1980),   |