Пример #1
0
        public void Predict(string SaleID, string CustomerID)
        {
            Dictionary <string, int> mapActors = new Dictionary <string, int>();

            SortedSet <int>[]            dataset    = SalesTransactionConverter(mapActors);
            Apriori                      apriori    = new Apriori(threshold: 3, confidence: 0);
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);
            var sale = _context.Sale.Include(s => s.Movies).Include("Movies.Movie").FirstOrDefault(s => s.SaleID == SaleID);

            HashSet <string> actorsSet = new HashSet <string>();
            List <int>       sample    = new List <int>();

            foreach (var movie in sale.Movies)
            {
                string[] actors = movie.Movie.Actors.Split(",");
                foreach (var actor in actors)
                {
                    if (!actorsSet.Contains(actor))
                    {
                        actorsSet.Add(actor);
                        sample.Add(mapActors.GetValueOrDefault(actor));
                    }
                }
            }
            int[][] matches = classifier.Decide(sample.ToArray());
        }
Пример #2
0
        // getting the identity id of the user!
        public List <ParkingSpot> GetRecommendedSpots(int[] uid)
        {
            if (classifier == null)
            {
                RecommendedSpots();
            }

            int[][] matches = classifier.Decide(uid);

            List <int> similarItems = new List <int>();

            // that nested forEach loop is to convert the matrix into list of the recomended spotsID's
            foreach (int[] match in matches)
            {
                foreach (int item in match)
                {
                    similarItems.Add(item);
                }
            }

            // 1 most recommended items - using the hash-set
            var similarIds = similarItems.ToHashSet().Take(1);
            // getting the spot from the DB
            var getSpot = _KeeParkContext.ParkingSpot.Where(x => similarIds.Contains(x.ParkingSpotID));

            return(getSpot.ToList());
        }
Пример #3
0
        public string getRecommendedBook(string CustomerId)
        {
            if (CustomerId == null)
            {
                return("error - must have CustomerId");
            }

            var allLoans  = db.Loans.Include(l => l.Book).Include(l => l.Customer).ToList();
            var customers = db.Customers.ToList();

            List <int[]> tempDataset = new List <int[]>();

            foreach (var c in customers)
            {
                var booksPerC = allLoans.Where(x => x.CustomerId == c.Id).Select(b => b.BookId).ToList();
                tempDataset.Add(booksPerC.ToArray());
            }

            int[][] dataset = tempDataset.ToArray();
            Apriori apriori = new Apriori(threshold: 1, confidence: 0);
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            var booksPerSpecC = allLoans.Where(x => x.Customer.PersonalID == (string)CustomerId).Select(b => b.BookId).ToArray();

            int[][] matches = classifier.Decide(booksPerSpecC);

            if (matches.Length > 0)
            {
                int    BestBookID   = matches[0][0];
                string BestBookName = db.Books.Single(x => x.Id == BestBookID).Name;
                return(BestBookName);
            }

            return("There is no recommended book for this customer.");
        }
Пример #4
0
        public List <Video> GetRelatedVideos([FromRoute] int[] videoIDS, [FromRoute] int limit = 5)
        {
            AssociationRuleMatcher <int> classifier = CreateAprioriClassifier();

            // Get the videos that appear most with the video who's ID is the given argument videoID
            int[][]       matches = classifier.Decide(videoIDS);
            List <Video>  videos  = new List <Video>();
            HashSet <int> ids     = new HashSet <int>();

            // Merge all the video IDs into a single HashSet, this will remove duplicates.
            foreach (int[] e in matches)
            {
                foreach (int f in e)
                {
                    ids.Add(f);
                }
            }

            // Take only the given amount of videos from the argument 'limit'.
            ids = ids.Take(limit).ToHashSet();

            // Get the full video model for each of the IDs.
            foreach (int id in ids)
            {
                videos.Add(_context.Video.FirstOrDefault(video => video.ID == id));
            }

            return(videos);
        }
Пример #5
0
        public async Task <string> getRecommendedMovie(string customerId)
        {
            if (customerId == null)
            {
                throw new ArgumentException("customer id is required!");
            }

            var loans = await _context.Loan
                        .Include(l => l.Movie)
                        .Include(l => l.Customer)
                        .ToListAsync();

            var customers = await _context.Customer.ToListAsync();

            List <int[]> tempDatasset = new List <int[]>();

            // Creating a unsymmetric matrix that each row contains the movies that a certain
            // customer has lent
            foreach (var customer in customers)
            {
                var moviesIdsPerCustomer = loans.Where(l => l.CustomerId == customer.CustomerId)
                                           .Select(m => m.MovieId).ToList();

                tempDatasset.Add(moviesIdsPerCustomer.ToArray());
            }

            int[][] dataset = tempDatasset.ToArray();

            // threshold represents that only 1 movie that the specified customer has lent
            // needs to be found in the other loans of other customers in order to recommend it
            // for him
            Apriori apriori = new Apriori(threshold: 1, confidence: 0);

            // machine learning section
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            // movies ids of the specified customer according to his loans
            var moviesPerSpecifiedCustomer = loans
                                             .Where(l => l.Customer.PersonalId == (string)customerId)
                                             .Select(b => b.MovieId).ToArray();

            // make an intersection between his movies and try to find from the dataset
            // all rows that contains atleast 1 of his movies that he had lent
            int[][] matches = classifier.Decide(moviesPerSpecifiedCustomer);

            if (matches.Length > 0)
            {
                int    bestMovieId   = matches[0][0];
                string bestMovieName = _context.Movie.Single(m => m.MovieId == bestMovieId).Name;
                return(bestMovieName);
            }

            return("There is no recommended movie for this customer.");
        }
Пример #6
0
        public IList <ProductResult> RecommendProducts(int userId)
        {
            var salesByUser = this.GetAllSalesByUser();

            List <int[]> tempDataset = new List <int[]>();

            int[] currUserSales = null;

            foreach (var userSales in salesByUser)
            {
                if (userSales.UserID == userId)
                {
                    currUserSales = userSales.Products.ToArray();
                }

                tempDataset.Add(userSales.Products.ToArray());
            }

            if (currUserSales == null || currUserSales.Length == 0)
            {
                return(new List <ProductResult>());
            }

            int[][] dataset = tempDataset.ToArray();

            // We will use Apriori to determine the frequent item sets of this database.
            // To do this, we will say that an item set is frequent if it appears in at
            // least 3 transactions of the database: the value 3 is the support threshold.

            // Create a new a-priori learning algorithm with support 3
            Apriori apriori = new Apriori(threshold: 1, confidence: 0.5);

            //// Use the algorithm to learn a set matcher
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            // Use the classifier to find orders that are similar to
            // orders where clients have bought items 1 and 2 together:
            int[][] matches = classifier.Decide(currUserSales);

            List <ProductResult> recommededProducts = new List <ProductResult>();

            if (matches.Length > 0)
            {
                int[] tmpRecommendedProducts = matches[0];
                foreach (var product in tmpRecommendedProducts)
                {
                    recommededProducts.Add(this.GetProduct(product));
                }
            }

            return(recommededProducts);
        }
Пример #7
0
        public void GetSkillsSuggestion()
        {
            SortedSet <int>[] dataset =
            {
                // Each row represents a set of items that have been bought
                // together. Each number is a SKU identifier for a product.
                new SortedSet <int> {
                    1, 2, 3, 4
                },                                 // bought 4 items
                new SortedSet <int> {
                    1, 2, 4
                },                                 // bought 3 items
                new SortedSet <int> {
                    1, 2
                },                                 // bought 2 items
                new SortedSet <int> {
                    2, 3, 4
                },                                 // ...
                new SortedSet <int> {
                    2, 3
                },
                new SortedSet <int> {
                    3, 4
                },
                new SortedSet <int> {
                    2, 4
                },
            };

            // We will use Apriori to determine the frequent item sets of this database.
            // To do this, we will say that an item set is frequent if it appears in at
            // least 3 transactions of the database: the value 3 is the support threshold.

            // Create a new a-priori learning algorithm with support 3
            Apriori apriori = new Apriori(threshold: 3, confidence: 0);

            // Use the algorithm to learn a set matcher
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            // Use the classifier to find orders that are similar to
            // orders where clients have bought items 1 and 2 together:
            int[][] matches = classifier.Decide(new[] { 1, 2 });

            // The result should be:
            //
            //   new int[][]
            //   {
            //       new int[] { 4 },
            //       new int[] { 3 }
            //   };
        }
Пример #8
0
        public List <Product> GetRecommendedProducts(int id)
        {
            if (classifier == null)
            {
                UpdateRecommendedProducts();
            }
            int[][] matches = classifier.Decide(new[] { _context.Product.FirstOrDefault(x => x.ProductID == id).ProductID });

            List <int> similarItems = new List <int>();

            foreach (int[] match in matches)
            {
                foreach (int item in match)
                {
                    similarItems.Add(item);
                }
            }
            var similarIds = similarItems.ToHashSet().Take(3); // 3 most recommended items
            var test       = _context.Product.Where(x => similarIds.Contains(x.ProductID));

            return(test.ToList());
        }
Пример #9
0
        public void CreateAprioriRules()
        {
            var associationBookList = bookSessionInfoManager.List().GroupBy(x => x.SessionId).ToArray();

            SortedSet <int>[] dataset = new SortedSet <int> [associationBookList.Count()];

            for (int i = 0; i < associationBookList.Count(); i++)
            {
                SortedSet <int> sortedSet = new SortedSet <int>()
                {
                };

                foreach (var item1 in associationBookList[i])
                {
                    sortedSet.Add(item1.BookId);
                }

                dataset[i] = sortedSet;
            }

            Apriori apriori = new Apriori(threshold: 3, confidence: 0.5);
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            int[][] matches = classifier.Decide(new[] { 1 });

            AssociationRule <int>[] rules = classifier.Rules;

            InsertSimilarBook(rules);

            //foreach (var item in rules)
            //{
            //    item.X.ToString();
            //    item.ToString();
            //}
            //return rules;
        }
        public string[][] AprioriAI(string[] BreakFastDietplan, string[] LunchDietplan, string[] DinnerDietplan)
        {
            string path  = Path.Combine(Environment.CurrentDirectory, "Data", "TeachPreferences.txt");
            string _Path = Path.Combine(Environment.CurrentDirectory, "Data", "PreferencesDB.txt");

            // Let the database of dietplan consist of following itemsets:

            //SortedSet<string>[] dataset =
            //{
            //// Each row represents a set of foods that have been consumed
            //// together. Each number is a SKU identifier for a food.
            //new SortedSet<string> { "grilled chicken breast", "lettuce", "carrot", "3 oz of greek yogurt" }, //consumed 4 food as a meal
            //new SortedSet<string> { "grilled chicken breast", "lettuce", "3 oz of greek yogurt" },    // consumed 3 food as a meal
            //new SortedSet<string> { "grilled chicken breast", "lettuce" },       // ....
            //new SortedSet<string> { "lettuce", "carrot", "3 oz of greek yogurt" },
            //new SortedSet<string> { "lettuce", "carrot" },
            //new SortedSet<string> { "carrot", "3 oz of greek yogurt" },
            //new SortedSet<string> { "lettuce", "3 oz of greek yogurt" },
            //};


            //TextWriter tw = new StreamWriter(_Path,true);

            //tw.Write(string.Join(",", BreakFastDietplan));
            //tw.WriteLine("");
            //tw.Write(string.Join(",", LunchDietplan));
            //tw.WriteLine("");
            //tw.Write(string.Join(",", DinnerDietplan));

            //tw.Close();

            //if (File.Exists(_Path))
            //{
            //    string lines;

            //    System.IO.StreamReader f = new System.IO.StreamReader(_Path);
            //    while ((lines = f.ReadLine()) != null)
            //    {
            //        if (lines==string.Join(",",BreakFastDietplan))
            //        {

            //        }

            //    }
            //}

            SortedSet <string>[] resultingArray = new SortedSet <string> [3];

            string line; int counter = 0;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(_Path);
            while ((line = file.ReadLine()) != null)
            {
                line = line.Replace(" ", string.Empty); //remove unnecessary spaces
                SortedSet <string> lineSet = new SortedSet <string>(line.Split(','));
                resultingArray.SetValue(lineSet, counter);

                counter++;
            }


            // We will use Apriori to determine the frequent item sets of this database.
            // To do this, we will say that an item set is frequent if it appears in at
            // least 3 transactions of the database: the value 3 is the support threshold.

            // Create a new a-priori learning algorithm with support 3
            var apriori = new Apriori <string>(threshold: 2, confidence: 0);

            // Use the algorithm to learn a set matcher
            AssociationRuleMatcher <string> classifier = apriori.Learn(resultingArray);

            // Use the classifier to find orders that are similar to
            // orders where clients have bought items 1 and 2 together:
            //string[][] matches = classifier.Decide(new[] { "2 oz. grilled chicken breast", "lettuce" });//this is a jagged array
            string[]   foodtest = { "4", "9" };
            string[][] matches  = classifier.Decide(foodtest);


            // We can also obtain the association rules from frequent itemsets:
            AssociationRule <string>[] rules = classifier.Rules;
            var food = new List <Meal> {
            };

            //foreach (string[] i in matches)
            //{
            //    foreach (string item in i)
            //    {
            //        System.Diagnostics.Debug.WriteLine("Results: " + item);
            //    }

            //}
            return(matches);
        }
Пример #11
0
        public void AprioriExampleTest1()
        {
            #region doc_learn_1
            // Example from https://en.wikipedia.org/wiki/Apriori_algorithm

            // Assume that a large supermarket tracks sales data by stock-keeping unit
            // (SKU) for each item: each item, such as "butter" or "bread", is identified
            // by a numerical SKU. The supermarket has a database of transactions where each
            // transaction is a set of SKUs that were bought together.

            // Let the database of transactions consist of following itemsets:

            SortedSet <int>[] dataset =
            {
                // Each row represents a set of items that have been bought
                // together. Each number is a SKU identifier for a product.
                new SortedSet <int> {
                    1, 2, 3, 4
                },                                 // bought 4 items
                new SortedSet <int> {
                    1, 2, 4
                },                                 // bought 3 items
                new SortedSet <int> {
                    1, 2
                },                                 // bought 2 items
                new SortedSet <int> {
                    2, 3, 4
                },                                 // ...
                new SortedSet <int> {
                    2, 3
                },
                new SortedSet <int> {
                    3, 4
                },
                new SortedSet <int> {
                    2, 4
                },
            };

            // We will use Apriori to determine the frequent item sets of this database.
            // To do this, we will say that an item set is frequent if it appears in at
            // least 3 transactions of the database: the value 3 is the support threshold.

            // Create a new a-priori learning algorithm with support 3
            Apriori apriori = new Apriori(threshold: 3, confidence: 0);

            // Use the algorithm to learn a set matcher
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            // Use the classifier to find orders that are similar to
            // orders where clients have bought items 1 and 2 together:
            int[][] matches = classifier.Decide(new[] { 1, 2 });

            // The result should be:
            //
            //   new int[][]
            //   {
            //       new int[] { 4 },
            //       new int[] { 3 }
            //   };

            // Meaning the most likely product to go alongside the products
            // being bought is item 4, and the second most likely is item 3.

            // We can also obtain the association rules from frequent itemsets:
            AssociationRule <int>[] rules = classifier.Rules;

            // The result will be:
            // {
            //     [1] -> [2]; support: 3, confidence: 1,
            //     [2] -> [1]; support: 3, confidence: 0.5,
            //     [2] -> [3]; support: 3, confidence: 0.5,
            //     [3] -> [2]; support: 3, confidence: 0.75,
            //     [2] -> [4]; support: 4, confidence: 0.66,
            //     [4] -> [2]; support: 4, confidence: 0.8,
            //     [3] -> [4]; support: 3, confidence: 0.75,
            //     [4] -> [3]; support: 3, confidence: 0.6
            // };
            #endregion

            Assert.AreEqual(8, rules.Length);
            Assert.AreEqual(rules[0].ToString(), "[1] -> [2]; support: 3, confidence: 1");
            Assert.AreEqual(rules[1].ToString(), "[2] -> [1]; support: 3, confidence: 0.5");
            Assert.AreEqual(rules[2].ToString(), "[2] -> [3]; support: 3, confidence: 0.5");
            Assert.AreEqual(rules[3].ToString(), "[3] -> [2]; support: 3, confidence: 0.75");
            Assert.AreEqual(rules[4].ToString(), "[2] -> [4]; support: 4, confidence: 0.666666666666667");
            Assert.AreEqual(rules[5].ToString(), "[4] -> [2]; support: 4, confidence: 0.8");
            Assert.AreEqual(rules[6].ToString(), "[3] -> [4]; support: 3, confidence: 0.75");
            Assert.AreEqual(rules[7].ToString(), "[4] -> [3]; support: 3, confidence: 0.6");

            var str = matches.ToCSharp();

            int[][] expectedMatches = new int[][]
            {
                new int[] { 4 },
                new int[] { 3 }
            };

            var expected = new Tuple <int[], int>[]
            {
                Tuple.Create(new[] { 1 }, 3),
                Tuple.Create(new[] { 2 }, 6),
                Tuple.Create(new[] { 3 }, 4),
                Tuple.Create(new[] { 4 }, 5),
                Tuple.Create(new[] { 1, 2 }, 3),
                Tuple.Create(new[] { 2, 3 }, 3),
                Tuple.Create(new[] { 2, 4 }, 4),
                Tuple.Create(new[] { 3, 4 }, 3),
            };

            var frequent = apriori.Frequent;

            foreach (var tuple in expected)
            {
                var a = frequent.Where(x => x.Key.SetEquals(tuple.Item1)).First();
                Assert.AreEqual(tuple.Item2, a.Value);
            }
        }
Пример #12
0
        public void ClassifierTest1()
        {
            #region doc_learn_2
            // Example from http://www3.cs.stonybrook.edu/~cse634/lecture_notes/07apriori.pdf

            // For this example, we will consider a database consisting of 9 transactions:
            // - Minimum support count required will be 2 (i.e. min_sup = 2 / 9 = 22%);
            // - Minimum confidence required should be 70%;

            // The dataset of transactions can be as follows:
            string[][] dataset =
            {
                new string[] { "1", "2", "5" },
                new string[] { "2", "4" },
                new string[] { "2", "3" },
                new string[] { "1", "2", "4" },
                new string[] { "1", "3" },
                new string[] { "2", "3" },
                new string[] { "1", "3" },
                new string[] { "1", "2", "3", "5"},
                new string[] { "1", "2", "3" },
            };

            // Create a new A-priori learning algorithm with the requirements
            var apriori = new Apriori <string>(threshold: 2, confidence: 0.7);

            // Use apriori to generate a n-itemset generation frequent pattern
            AssociationRuleMatcher <string> classifier = apriori.Learn(dataset);

            // Generate association rules from the itemsets:
            AssociationRule <string>[] rules = classifier.Rules;

            // The result should be:
            // {
            //   [5]   -> [1];   support: 2, confidence: 1,
            //   [5]   -> [2];   support: 2, confidence: 1,
            //   [4]   -> [2];   support: 2, confidence: 1,
            //   [5]   -> [1 2]; support: 2, confidence: 1,
            //   [1 5] -> [2];   support: 2, confidence: 1,
            //   [2 5] -> [1];   support: 2, confidence: 1,
            // }
            #endregion

            Assert.AreEqual(6, rules.Length);
            Assert.AreEqual(rules[0].ToString(), "[5] -> [1]; support: 2, confidence: 1");
            Assert.AreEqual(rules[1].ToString(), "[5] -> [2]; support: 2, confidence: 1");
            Assert.AreEqual(rules[2].ToString(), "[4] -> [2]; support: 2, confidence: 1");
            Assert.AreEqual(rules[3].ToString(), "[5] -> [1 2]; support: 2, confidence: 1");
            Assert.AreEqual(rules[4].ToString(), "[1 5] -> [2]; support: 2, confidence: 1");
            Assert.AreEqual(rules[5].ToString(), "[2 5] -> [1]; support: 2, confidence: 1");


            string[][] actual;

            actual = classifier.Decide(new string[] { "1", "5" });
            Assert.AreEqual("2", actual[0][0]);
            Assert.AreEqual("1", actual[1][0]);
            Assert.AreEqual("2", actual[1][1]);
            actual = classifier.Decide(new string[] { "2", "5" });
            Assert.AreEqual("1", actual[0][0]);
            Assert.AreEqual("1", actual[1][0]);
            Assert.AreEqual("2", actual[1][1]);
            actual = classifier.Decide(new string[] { "0", "5" });
            Assert.AreEqual("1", actual[0][0]);
            Assert.AreEqual("2", actual[0][1]);
            Assert.AreEqual("2", actual[1][0]);
            Assert.AreEqual("1", actual[2][0]);
        }
Пример #13
0
        public string RecommendOnProduct(Dictionary <int, string> dictCurrentCart)
        {
            if (dictCurrentCart.Count == 0)
            {
                return(string.Empty);
            }

            // We will use Apriori to determine the frequent item sets of this database.
            // To do this, we will say that an item set is frequent if it appears in at
            // least 3 transactions of the database: the value 3 is the support threshold.

            // Create a new a-priori learning algorithm with support 3
            Apriori apriori = new Apriori(threshold: 2, confidence: 0);

            // Use the algorithm to learn a set matcher
            AssociationRuleMatcher <int> classifier = apriori.Learn(dataset);

            // Use the classifier to find orders that are similar to
            // orders where clients have bought items 1 and 2 together:
            var products = new int[dictCurrentCart.Count];
            int index    = 0;

            foreach (var product in dictCurrentCart)
            {
                products[index] = product.Key;
                index++;
            }
            int[][] matches = classifier.Decide(products);

            if (matches.Length == 0)
            {
                return(string.Empty);
            }
            else if (!allProducts.Keys.Contains(matches[0][0])) // the first product recommended
            {
                return(string.Empty);
            }

            AssociationRule <int>[] rules = classifier.Rules;
            string recProduct;
            bool   res = allProducts.TryGetValue(matches[0][0], out recProduct);

            if (res)
            {
                return(recProduct);
            }
            return(string.Empty);
            // The result should be:
            //
            //   new int[][]
            //   {
            //       new int[] { 4 },
            //       new int[] { 3 }
            //   };

            // Meaning the most likely product to go alongside the products
            // being bought is item 4, and the second most likely is item 3.

            // We can also obtain the association rules from frequent itemsets:

            // The result will be:
            // {
            //     [1] -> [2]; support: 3, confidence: 1,
            //     [2] -> [1]; support: 3, confidence: 0.5,
            //     [2] -> [3]; support: 3, confidence: 0.5,
            //     [3] -> [2]; support: 3, confidence: 0.75,
            //     [2] -> [4]; support: 4, confidence: 0.66,
            //     [4] -> [2]; support: 4, confidence: 0.8,
            //     [3] -> [4]; support: 3, confidence: 0.75,
            //     [4] -> [3]; support: 3, confidence: 0.6
            // };
        }