Exemple #1
0
    def test(self, testset):
        """
        Test the recommendation system by recommending scores to all users in testset.
        :param testset: test dataset
        :return:
        """
        if not self.n_rec_movie or not self.trainset or not self.movie_popular \
                or not self.movie_count or not self.movie_popular_sort:
            raise ValueError(
                'UserCF has not init or fit method has not called yet.')
        self.testset = testset
        print('Test recommendation system start...')
        N = self.n_rec_movie
        #  varables for precision and recall
        hit = 0
        rec_count = 0
        test_count = 0
        # varables for coverage
        all_rec_movies = set()
        # varables for popularity
        popular_sum = 0

        # record the calculate time has spent.
        test_time = utils.LogTime(print_step=1000)
        for i, user in enumerate(self.trainset):
            test_movies = self.testset.get(user, {})
            rec_movies = self.recommend(user)  # type:list
            for movie in rec_movies:
                if movie in test_movies:
                    hit += 1
                all_rec_movies.add(movie)
                popular_sum += math.log(1 + self.movie_popular[movie])
                # log steps and times.
            rec_count += N
            test_count += len(test_movies)
            # print time per 500 times.
            test_time.count_time()
        precision = hit / (1.0 * rec_count)
        recall = hit / (1.0 * test_count)
        coverage = len(all_rec_movies) / (1.0 * self.movie_count)
        popularity = popular_sum / (1.0 * rec_count)

        print('Test recommendation system success.')
        test_time.finish()

        print('precision=%.4f\trecall=%.4f\tcoverage=%.4f\tpopularity=%.4f\n' %
              (precision, recall, coverage, popularity))

        summary = []
        summary.append(precision)
        summary.append(recall)
        summary.append(coverage)
        summary.append(popularity)
Exemple #2
0
 def predict(self, testset):
     """
     Recommend movies to all users in testset.
     :param testset: test dataset
     :return: `dict` : recommend list for each user.
     """
     movies_recommend = defaultdict(list)
     print('Predict scores start...')
     # record the calculate time has spent.
     predict_time = utils.LogTime(print_step=500)
     for i, user in enumerate(testset):
         rec_movies = self.recommend(user)  # type:list
         movies_recommend[user].append(rec_movies)
         # log steps and times.
         predict_time.count_time()
     print('Predict scores success.')
     predict_time.finish()
     return movies_recommend