Exemplo n.º 1
0
        public ActionResult GetRecommendedFilms(string filmIdsJson)
        {
            var filmIds = JsonConvert.DeserializeObject <long[]>(filmIdsJson);

            var dataModel = GetDataModel();

            // recommendation is performed for the user that is missed in the preferences data
            var plusAnonymModel = new PlusAnonymousUserDataModel(dataModel);
            var prefArr         = new GenericUserPreferenceArray(filmIds.Length);

            prefArr.SetUserID(0, PlusAnonymousUserDataModel.TEMP_USER_ID);
            for (int i = 0; i < filmIds.Length; i++)
            {
                prefArr.SetItemID(i, filmIds[i]);

                // in this example we have no ratings of movies preferred by the user
                prefArr.SetValue(i, 5); // lets assume max rating
            }
            plusAnonymModel.SetTempPrefs(prefArr);

            var similarity       = new LogLikelihoodSimilarity(plusAnonymModel);
            var neighborhood     = new NearestNUserNeighborhood(15, similarity, plusAnonymModel);
            var recommender      = new GenericUserBasedRecommender(plusAnonymModel, neighborhood, similarity);
            var recommendedItems = recommender.Recommend(PlusAnonymousUserDataModel.TEMP_USER_ID, 5, null);

            return(Json(recommendedItems.Select(ri => new Dictionary <string, object>()
            {
                { "film_id", ri.GetItemID() },
                { "rating", ri.GetValue() },
            }).ToArray()));
        }
Exemplo n.º 2
0
        public List <MovieRecommendationDto> GetRecommendedMovies(int[] preferredMovieIds)
        {
            var dataModel = GetDataModel();

            // recommendation is performed for the user that is missed in the preferences data
            var plusAnonymModel = new PlusAnonymousUserDataModel(dataModel);
            var prefArr         = new GenericUserPreferenceArray(preferredMovieIds.Length);

            prefArr.SetUserID(0, PlusAnonymousUserDataModel.TEMP_USER_ID);
            for (int i = 0; i < preferredMovieIds.Length; i++)
            {
                prefArr.SetItemID(i, preferredMovieIds[i]);

                // in this example we have no ratings of movies preferred by the user
                prefArr.SetValue(i, 5); // lets assume max rating
            }
            plusAnonymModel.SetTempPrefs(prefArr);

            var similarity       = new LogLikelihoodSimilarity(plusAnonymModel);
            var neighborhood     = new NearestNUserNeighborhood(15, similarity, plusAnonymModel);
            var recommender      = new GenericUserBasedRecommender(plusAnonymModel, neighborhood, similarity);
            var recommendedItems = recommender.Recommend(PlusAnonymousUserDataModel.TEMP_USER_ID, 5, null);

            var movieIds = recommendedItems.Select(ri => (int)ri.GetItemID()).ToArray();
            var movieIdToTitleDictionary = _unitOfWork.MovieRepository.GetMovieIdToTileDictionary(movieIds);

            var recommendedMovies = new List <MovieRecommendationDto>();

            foreach (var item in recommendedItems)
            {
                var movieId    = (int)item.GetItemID();
                var movieTitle = movieIdToTitleDictionary[movieId];

                recommendedMovies.Add(
                    new MovieRecommendationDto
                {
                    MovieId    = movieId,
                    MovieTitle = movieTitle,
                    Rating     = item.GetValue()
                });
            }

            return(recommendedMovies);
        }
        public ActionResult Recommend(string filmIdsJson)
        {
            var filmIds        = (new JavaScriptSerializer()).Deserialize <long[]>(filmIdsJson);
            var pathToDataFile =
                Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, "data/albums.dat");

            if (dataModel == null)
            {
                try
                {
                    dataModel = new FileDataModel(pathToDataFile, false, FileDataModel.DEFAULT_MIN_RELOAD_INTERVAL_MS, false);
                }
                catch (Exception e)
                {
                    var exe = e.ToString();
                }
            }

            var plusAnonymModel = new PlusAnonymousUserDataModel(dataModel);
            var prefArr         = new GenericUserPreferenceArray(filmIds.Length);

            prefArr.SetUserID(0, PlusAnonymousUserDataModel.TEMP_USER_ID);
            for (int i = 0; i < filmIds.Length; i++)
            {
                prefArr.SetItemID(i, filmIds[i]);
                prefArr.SetValue(i, 5);                 // lets assume max rating
            }
            plusAnonymModel.SetTempPrefs(prefArr);

            var similarity       = new LogLikelihoodSimilarity(plusAnonymModel);
            var neighborhood     = new NearestNUserNeighborhood(15, similarity, plusAnonymModel);
            var recommender      = new GenericBooleanPrefUserBasedRecommender(plusAnonymModel, neighborhood, similarity);
            var recommendedItems = recommender.Recommend(PlusAnonymousUserDataModel.TEMP_USER_ID, 5, null);

            return(Json(recommendedItems.Select(ri => new Dictionary <string, object>()
            {
                { "id", ri.GetItemID() },
                { "rating", ri.GetValue() },
            }).ToArray()));
        }
Exemplo n.º 4
0
        /// <summary>
        /// 推荐
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="showCount">显示数量</param>
        /// <returns></returns>
        public List <Books> RecommendBooks(int pageIndex, int pageSize, int showCount)
        {
            #region 推荐
            List <Books> books = null;
            if (Session["user"] != null)
            {
                Users user = Session["user"] as Users;

                #region 构建用户行为数组
                var           loglist = logbll.LoadEntities(c => c.userID == user.Id).ToList();
                StringBuilder sb      = new StringBuilder();
                if (loglist.Count > 0)
                {
                    sb.Append("[");
                    int j = 0;
                    foreach (var item in loglist)
                    {
                        j++;
                        sb.Append(item.itemID.ToString());
                        if (j != loglist.Count)
                        {
                            sb.Append(",");
                        }
                    }
                    sb.Append("]");
                }
                #endregion

                if (string.IsNullOrEmpty(sb.ToString()))
                {
                    //冷启动
                    books = booksbll.LoadEntities(c => true).OrderByDescending(c => c.rating).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    var filmIds = (new JavaScriptSerializer()).Deserialize <long[]>(sb.ToString());

                    var    logmodel = settingbll.LoadEntities(c => c.id == 16).FirstOrDefault();
                    string path     = "";
                    if (logmodel != null && logmodel.value == "true")
                    {
                        path = "data/ratings1.dat";
                    }
                    else
                    {
                        path = "data/ratings.dat";
                    }

                    var pathToDataFile =
                        Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, path);

                    if (dataModel == null)
                    {
                        dataModel = new FileDataModel(pathToDataFile, false, FileDataModel.DEFAULT_MIN_RELOAD_INTERVAL_MS, false);
                    }

                    var plusAnonymModel = new PlusAnonymousUserDataModel(dataModel);
                    var prefArr         = new GenericUserPreferenceArray(filmIds.Length);
                    prefArr.SetUserID(0, PlusAnonymousUserDataModel.TEMP_USER_ID);
                    for (int i = 0; i < filmIds.Length; i++)
                    {
                        prefArr.SetItemID(i, filmIds[i]);
                        prefArr.SetValue(i, 5); // lets assume max rating
                    }
                    plusAnonymModel.SetTempPrefs(prefArr);

                    var          similarity       = new LogLikelihoodSimilarity(plusAnonymModel);
                    var          neighborhood     = new NearestNUserNeighborhood(15, similarity, plusAnonymModel);
                    var          recommender      = new GenericUserBasedRecommender(plusAnonymModel, neighborhood, similarity);
                    var          recommendedItems = recommender.Recommend(PlusAnonymousUserDataModel.TEMP_USER_ID, showCount, null);
                    List <Books> newbooks         = new List <Books>();
                    foreach (var item in recommendedItems)
                    {
                        int bid = Convert.ToInt32(item.GetItemID());
                        newbooks.Add(booksbll.LoadEntities(c => c.Id == bid).FirstOrDefault());
                    }

                    books = newbooks.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
            else //不推荐
            {
                books = booksbll.LoadEntities(c => true).OrderByDescending(c => c.rating).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            #endregion

            return(books.Count() <= 0 ? booksbll.LoadEntities(c => true).OrderByDescending(c => c.rating).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList() : books);
        }
        public ActionResult GetRecommendedbooks()
        {
            var csv            = new CsvReader(new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/books.csv")));
            var records        = csv.GetRecords <BookRecord>().ToList();
            int favouriteGenre = db.Users.Where(u => u.UserName == User.Identity.Name).Select(u => u.genreID).SingleOrDefault();
            var userRentals    = db.Rentals.Where(m => m.rentalUser == User.Identity.Name).Join(db.Books,
                                                                                                r => r.rentalBook,
                                                                                                m => m.bookName,
                                                                                                (r, m) => new
            {
                genreId   = m.genreID,
                bookName  = m.bookName,
                rentalUer = r.rentalUser
            });

            if (userRentals.Count() == 0)
            {
                return(Json(new Dictionary <string, object>()
                {
                    { "book_id", 0 },
                    { "rating", 0 },
                }));
            }
            else if (userRentals.Where(m => m.genreId == favouriteGenre).Count() != 0)
            {
                userRentals = userRentals.Where(m => m.genreId == favouriteGenre);
            }

            long[] bookIdsTemp = new long[userRentals.Count()];
            int    bookCounter = 0;

            foreach (var item in userRentals)
            {
                foreach (var record in records)
                {
                    if (item.bookName == record.title)
                    {
                        if (!bookIdsTemp.Contains(record.bookId))
                        {
                            bookIdsTemp[bookCounter] = record.bookId;
                            bookCounter++;
                        }
                    }
                }
            }
            long[] bookIds = new long[bookCounter];
            for (int i = 0; i < bookCounter; i++)
            {
                bookIds[i] = bookIdsTemp[i];
            }

            var dataModel = GetDataModel();

            // recommendation is performed for the user that is missed in the preferences data
            var plusAnonymModel = new PlusAnonymousUserDataModel(dataModel);
            var prefArr         = new GenericUserPreferenceArray(userRentals.Count());

            prefArr.SetUserID(0, PlusAnonymousUserDataModel.TEMP_USER_ID);
            for (int i = 0; i < bookIds.Length; i++)
            {
                prefArr.SetItemID(i, bookIds[i]);

                // in this example we have no ratings of books preferred by the user
                prefArr.SetValue(i, 5); // lets assume max rating
            }
            plusAnonymModel.SetTempPrefs(prefArr);

            var similarity       = new LogLikelihoodSimilarity(plusAnonymModel);
            var neighborhood     = new NearestNUserNeighborhood(15, similarity, plusAnonymModel);
            var recommender      = new GenericUserBasedRecommender(plusAnonymModel, neighborhood, similarity);
            var recommendedItems = recommender.Recommend(PlusAnonymousUserDataModel.TEMP_USER_ID, 1, null);

            if (recommendedItems.Count() == 0)
            {
                return(Json(new Dictionary <string, object>()
                {
                    { "book_id", 0 },
                    { "rating", 0 },
                }));
            }

            return(Json(recommendedItems.Select(ri => new Dictionary <string, object>()
            {
                { "book_id", ri.GetItemID() },
                { "rating", ri.GetValue() },
            }).ToArray()[0]));
        }