Exemple #1
1
        public void AprioriExampleTest1()
        {
            // Example from https://en.wikipedia.org/wiki/Apriori_algorithm

            SortedSet<int>[] dataset = 
            {
                new SortedSet<int> { 1, 2, 3, 4 },
                new SortedSet<int> { 1, 2, 4 },
                new SortedSet<int> { 1, 2 },
                new SortedSet<int> { 2, 3, 4 },
                new SortedSet<int> { 2, 3 },
                new SortedSet<int> { 3, 4 },
                new SortedSet<int> { 2, 4 },
            };

            var apriori = new Apriori(threshold: 3, confidence: 0);

            var classifier = apriori.Learn(dataset);

            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[] {1,3}, 1),
                //Tuple.Create(new[] {1,4}, 2),
                Tuple.Create(new[] {2,3}, 3),
                Tuple.Create(new[] {2,4}, 4),
                Tuple.Create(new[] {3,4}, 3),
                //Tuple.Create(new[] {2,3,4}, 2),
            };

            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);
            }
        }
Exemple #2
0
        public void ProcessTransactionTest()
        {
            //Arrange
            IApriori target = new Apriori();

            //Act
            Output actual = target.ProcessTransaction(_minSupport, _minConfidence, _items, _transactions);

            //Assert
            Assert.AreEqual(9, actual.FrequentItems.Count);
            Assert.AreEqual(2, actual.FrequentItems["a"].Support);
            Assert.AreEqual(3, actual.FrequentItems["b"].Support);
            Assert.AreEqual(3, actual.FrequentItems["c"].Support);
            Assert.AreEqual(3, actual.FrequentItems["e"].Support);
            Assert.AreEqual(2, actual.FrequentItems["ac"].Support);
            Assert.AreEqual(2, actual.FrequentItems["bc"].Support);
            Assert.AreEqual(3, actual.FrequentItems["be"].Support);
            Assert.AreEqual(2, actual.FrequentItems["ce"].Support);
            Assert.AreEqual(2, actual.FrequentItems["bce"].Support);

            Assert.AreEqual(2, actual.MaximalItemSets.Count);
            Assert.AreEqual("ac", actual.MaximalItemSets[0]);
            Assert.AreEqual("bce", actual.MaximalItemSets[1]);

            Assert.AreEqual(5, actual.StrongRules.Count);
        }
Exemple #3
0
        private void Statistic()
        {
            var    apriori = new Apriori(Tree);
            string path    = Path.Combine(DirectoryPath, "statistic.txt");

            File.WriteAllText(path, $"Liczba transakcji: {Tree.NumberTransactions} Liczba towarów: {apriori.NumberOfUniqProducts()}");
        }
Exemple #4
0
        public static void Main()
        {
            BL.DataHandle  db = new BL.DataHandle();
            Item[][]       a  = db.GetOrders().Select(order => order.Items.ToArray()).ToArray();
            Apriori <Item> ab = new Apriori <Item>(15, 0);

            //var clsfr = ab.Learn(a);
            //var itemsDistinctByBarcode = db.GetAllItems().GroupBy(i => i.BarcodeNumber).Select(grp => grp.FirstOrDefault());
            //AssociationRuleMatcher<Item> cl = new AssociationRuleMatcher<Item>(itemsDistinctByBarcode.Count(),
            //    clsfr.Rules.Where(r => r.Confidence > 0.6).ToArray());

            //int abcde;
            //System.Collections.Generic.Dictionary<Item, int> counter = new System.Collections.Generic.Dictionary<Item, int>();
            //foreach (Order o in db.GetOrders()){
            //    foreach (Item item in o.Items)
            //    {
            //        if (counter.TryGetValue(item,out abcde))
            //        {

            //        }
            //    }
            //}
            //var abcd = cl.Decide(itemsDistinctByBarcode.ToList().GetRange(0,10).ToArray());
            AssociationRule <Item>[] rules = ab.Learn(a).Rules;
            foreach (var rule in rules)
            {
                Console.WriteLine(rule);
            }
            Console.ReadLine();
            //BL.DataHandle.GenerateQRcodes();
            //FlushData.FlushAll();
            //Console.WriteLine("press key to exit");
            //Console.ReadLine();
        }
Exemple #5
0
        public void TestMethodAlgorithms()
        {
            List <double> supports     = new List <double>(new double[] { 0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.02, 0.03, 0.04, 0.05, 0.1, 0.2 });
            string        stringResult = "";

            foreach (double support in supports)
            {
                var start        = DateTime.Now;
                var transactions = new TransactionDatabase(@"\\small.txt");
                var apriori      = new Apriori(transactions, 0.2);
                apriori.Run();
                var end    = DateTime.Now;
                var result = end - start;
                stringResult += $"APRIORI Support:{support} Total Time (ms): {result.TotalMilliseconds}" + Environment.NewLine;
            }
            foreach (double support in supports)
            {
                var start        = DateTime.Now;
                var transactions = new TransactionDatabase(@"\\small.txt");
                var eclat        = new Eclat(transactions, 0.2);
                eclat.Run();
                var end    = DateTime.Now;
                var result = end - start;
                stringResult += $"ECLAT Support:{support} Total Time (ms): {result.TotalMilliseconds}" + Environment.NewLine;
                System.IO.File.WriteAllText(@"PerformanceResultsAuto.csv", stringResult);
            }
        }
        private void performanceTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List <double> supports     = new List <double>(new double[] { 0.01, 0.02, 0.03, 0.04, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5 });
            string        stringResult = "";
            string        readfile     = File.ReadAllText(comboBoxTestDataSet.Text);

            foreach (double support in supports)
            {
                var start        = DateTime.Now;
                var transactions = new TransactionDatabase(comboBoxTestDataSet.Text);
                var apriori      = new Apriori(transactions, support);
                apriori.Run();
                var end       = DateTime.Now;
                var result    = end - start;
                var resultMem = GC.GetTotalMemory(true);
                stringResult += $"APRIORI Support:{support} Total Time (ms): {result.TotalMilliseconds} Memory Usage (bytes): {resultMem}" + Environment.NewLine;
            }
            foreach (double support in supports)
            {
                var start        = DateTime.Now;
                var transactions = new TransactionDatabase(comboBoxTestDataSet.Text);
                var eclat        = new Eclat(transactions, support);
                eclat.Run();
                var end       = DateTime.Now;
                var result    = end - start;
                var resultMem = GC.GetTotalMemory(true);
                stringResult += $"ECLAT Support:{support} Total Time (ms): {result.TotalMilliseconds} Memory Usage (bytes): {resultMem}" + Environment.NewLine;
                System.IO.File.WriteAllText(@"PerformanceResults.txt", stringResult);
            }
        }
Exemple #7
0
        public MainViewModel()
        {
            var     tr      = new TextReader();
            Apriori apriori = new Apriori(tr.GetItems(), 0.2, 0.2);

            Console.WriteLine();
        }
Exemple #8
0
        static void Main(string[] args)
        {
            var events = File.ReadAllLines(@"C:\Users\leosm\Documents\Projects\TCC\DataSetByCNPJ\cartelFull.csv");

            var list = events.Select(x =>
            {
                var split = x.Split(';');
                return(new Participante
                {
                    CodItemCompra = split[0],
                    CnpjParticipante = split[1]
                });
            });

            var groups = list.GroupBy(x => x.CodItemCompra).ToDictionary(x => x.Key, x => x.Select(e => e.CnpjParticipante).ToArray()).ToArray();

            var dataset = groups.Select(x => x.Value.ToArray()).ToArray();

            // Create a new A-priori learning algorithm with the requirements
            var apriori = new Apriori <string>(threshold: 3, 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;
        }
Exemple #9
0
        static void Main(string[] args)
        {
            var apriori = new Apriori();

            var support    = 2;
            var confidence = 0.8;

            var transactions = new[] { "milk~egg~flower", "honey~egg~siroup", "milk~honey~egg~siroup", "honey~siroup", "milk~egg~siroup" };
            var items        = new List <string> {
                "milk", "honey", "egg", "flower", "siroup"
            };

            //var transactions = new[] { "1~3~4", "2~3~5", "1~2~3~5", "2~5", "1~3~5" };
            //var items = new List<string> { "1", "2", "3", "4", "5" };

            var transactionsTest = ReadTransactionsFile();
            var itemsTest        = ReadItemsFile();

            var result = apriori.ProcessTransaction(support, confidence, itemsTest, transactionsTest);

            WriteRules(result.StrongRules);
            WriteFrequent(result.FrequentItems);
            WriteClosest(result.ClosedItemSets);
            WriteMaximal(result.MaximalItemSets);

            Console.WriteLine("Done...");
            Console.Read();
        }
Exemple #10
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.");
        }
Exemple #11
0
        public List <int[]> FrequentItemsets_Apriori(double threshold)
        {
            List <int[]>       itemsets     = context.Items.Select(s => new int[] { s.Value.Code }).ToList();
            List <List <int> > transactions = context.Transactions.Select(t => t.Value.Items).ToList();

            return(Apriori.GenerateAllFrecuentItemsets(itemsets, transactions, threshold).ToList());
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Hi, Thank you for choosing AgentNet. \n\n\nGetting latest transaction data from DB...");
            InititalizeData();
            Console.WriteLine("Following items found :");
            Console.WriteLine(string.Join(",", ItemSets));
            Console.WriteLine("Number of transactions found : " + TransactionSets.Count);
            //Console.WriteLine(string.Join(",", TransactionSets));
            Console.Write("Please enter a minimum support (%) :");
            string minSupportStr = Console.ReadLine();//"50";//Console.ReadLine();

            Console.Write("Please enter a minimum confidence (%) :");
            string minConfidenceStr = Console.ReadLine(); //"80";//Console.ReadLine();

            double minSupport    = double.Parse(minSupportStr) / 100;
            double minConfidence = double.Parse(minConfidenceStr) / 100;

            string[] transactionArray = TransactionSets.ToArray();

            IApriori _apriori = new Apriori();
            Output   output   = _apriori.ProcessTransaction(minSupport, minConfidence, ItemSets, transactionArray);

            Console.WriteLine(string.Join("", output.StrongRules.Select(i => i.X + "-->" + i.Y + "\t" + i.Confidence * 100 + "%\n").ToList()));
            Console.ReadKey();
        }
Exemple #13
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());
        }
        public void GenerateFrequentItemSets()
        {
            var sut  = new Apriori(null);
            var test = new string[] { "banana", "apple", "potato", "grape" };

            var result = sut.GenerateFrequentItemSets(test, 1);
        }
Exemple #15
0
        public void UpdateRecommendedProducts()
        {
            var orders1 = _context.OrderClient.Include(order => order.ProductOrders).ThenInclude(po => po.Product);
            var orders  = _context.ApplicationUser.Include(user => user.Orders).ThenInclude(order => order.ProductOrders)
                          .ThenInclude(po => po.Product).Select(delegate(ApplicationUser user)
            {
                List <int> orderList = new List <int>();
                foreach (ClientOrder co in user.Orders)
                {
                    foreach (ProductOrder po in co.ProductOrders)
                    {
                        orderList.Add(po.Product.ProductID);
                    }
                }
                return(orderList);
            }).ToArray();


            SortedSet <int>[] dataset = ToSortedSet(orders);


            // 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 20% transactions of the database: the value _minSupport * dataset.Length is the support threshold.

            // Create a new a-priori learning algorithm with support 3
            Apriori <int> apriori =
                new Apriori <int>(Convert.ToInt32(_minSupport * dataset.Length), _minConfidence);

            // Use the algorithm to learn a set matcher
            classifier = apriori.Learn(dataset);
        }
Exemple #16
0
        public void Example()
        {
            List <Transaction <char> > database = new List <Transaction <char> >();

            database.Add(new Transaction <char>('a', 'c', 'd', 'e')
            {
                ID = 10
            });
            database.Add(new Transaction <char>('a', 'b', 'e')
            {
                ID = 20
            });
            database.Add(new Transaction <char>('b', 'c', 'e')
            {
                ID = 30
            });
            database.Add(new Transaction <char>('b', 'c', 'e')
            {
                ID = 40
            });

            Apriori <char>  method   = new Apriori <char>();
            ItemSets <char> itemsets = method.MinePatterns(database, 2, new List <char>()
            {
                'a', 'b', 'c', 'd', 'e'
            });

            for (int i = 0; i < itemsets.Count; ++i)
            {
                ItemSet <char> itemset = itemsets[i];

                Console.WriteLine(itemset);
            }
        }
Exemple #17
0
        private void FrequentSets(double minSup, int maxSize)
        {
            var apriori = new Apriori(Tree);

            Leaf[] leafs = apriori.GetFrequentSets(minSup, maxSize);

            FrequentSets(leafs, $"FrequentSets {minSup} {maxSize} Find elements: {leafs.Length}", $"{TreeName}-frequentsets-{DoubleToString(minSup)}-{maxSize}.txt");
        }
Exemple #18
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     KetNoi();
     Program.apriori = new Apriori();
     Application.Run(new FormMain());
 }
        public PlaylistController(ApplicationDbContext context, UserManager <ApplicationUser> userManager)
        {
            _context     = context;
            _userManager = userManager;

            //Initializing aprior alg.
            AprioriAlg = new Apriori(threshold: 1, confidence: 0);
        }
Exemple #20
0
        public List <String> FrequentItemSetsByClient(String clientCode, double Support)
        {
            List <int[]>       itemsets     = context.Clients[clientCode].Transactions.SelectMany(t => t.Items).Distinct().Select(s => new int[] { s }).ToList();
            List <List <int> > transactions = context.Clients[clientCode].Transactions.Select(t => t.Items).ToList();
            var frequent = Apriori.GenerateAllFrecuentItemsets(itemsets, transactions, Support).ToList();

            return(formatItemSets(frequent));
        }
Exemple #21
0
        public List <String> FrequentItemSetsByDepartment(String department, double support)
        {
            List <int[]>       itemsets     = TransactionsByDepartment(department).SelectMany(t => t.Items).Distinct().Select(s => new int[] { s }).ToList();
            List <List <int> > transactions = TransactionsByDepartment(department).Select(t => t.Items).ToList();
            var frequent = Apriori.GenerateAllFrecuentItemsets(itemsets, transactions, support).ToList();

            return(formatItemSets(frequent));
        }
        static void Main(string[] args)
        {
            /*

            This sample demonstrate how-to use the Apriori algorithm.

            As a test data I use a data from an imagine book store:
            1) We have a list of authors, which the store sells.
            2) We have an information about shopping cart of some users.

            As a result we get the following information:
            1. Order by popularity of the authors/set of authors.
            2. What we can advise the user, basing on his shopping cart. It is ordered by probability (frequent).

            */

            TypeRegister.Register<BookAuthor>((a, b) => a.Name.CompareTo(b.Name));

            var itemsets = new List<Itemset<BookAuthor>>();
            var transactions = new SampleHelper().Transactions.ToList();

            var apriori = new Apriori<BookAuthor>
            {
                MinSupport = (double) 1/9,
                SaveItemset = itemset => itemsets.Add(itemset),
                GetTransactions = ()=> transactions
            };

            apriori.ProcessTransactions();

            var rules = new List<Rule<BookAuthor>>();

            var agrawal = new AgrawalFaster<BookAuthor>
            {
                MinLift = 0.01,
                MinConfidence = 0.01,
                TransactionsCount = transactions.Count(),
                GetItemsets = ()=>itemsets,
                SaveRule = rule=>rules.Add(rule)
            };

            agrawal.Run();

            foreach (var item in itemsets.OrderByDescending(v => v.Support))
            {
                Console.WriteLine(string.Join("; ", item.Value.OrderBy(i => i.Name)) + " #SUP: " + item.Support);
            }

            Console.WriteLine("====");

            foreach (var item in rules.OrderByDescending(r => r.Confidence))
            {
                Console.WriteLine(string.Join("; ", item.Combination) + " => " + string.Join("; ", item.Remaining) + " ===> Confidence: " + item.Confidence + " Lift: " + item.Lift);
            }

            Console.ReadLine();
        }
        private void aprioriAlgorithmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var transactions = new TransactionDatabase(comboBoxTestDataSet.Text);
            var apriori      = new Apriori(transactions, double.Parse(textBoxMinimumSupport.Text));

            apriori.Run();
            textBoxOutput.AppendText(apriori.ToString());
            csvString = apriori.ToCSV();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Stream         myStream        = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex      = 1;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            StreamReader          sr = new StreamReader(myStream);
                            LoadTransactions      lt = new LoadTransactions(sr);
                            List <List <string> > transactions;
                            transactions = lt.Load();
                            apriori      = new Apriori(transactions);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            listBox1.Items.Clear();
            listBox2.Items.Clear();
            listBox3.Items.Clear();
            listBox4.Items.Clear();

            foreach (var transacion in apriori.transactions)
            {
                StringBuilder tempString = new StringBuilder();

                foreach (var item in transacion)
                {
                    tempString.Append(item + ", ");
                }
                listBox4.Items.Add(tempString.ToString());
            }

            trackBar1.Maximum        = apriori.FirstFrequent.Values.ToList().Max();
            labelSupportMax.Text     = trackBar1.Maximum.ToString();
            textBoxSupportValue.Text = trackBar1.Value.ToString();

            button1.Enabled   = true;
            trackBar1.Enabled = true;
            trackBar2.Enabled = true;
            button3.Enabled   = false;
        }
Exemple #25
0
        public void AprioriExampleTest1()
        {
            // Example from https://en.wikipedia.org/wiki/Apriori_algorithm

            SortedSet <int>[] dataset =
            {
                new SortedSet <int> {
                    1, 2, 3, 4
                },
                new SortedSet <int> {
                    1, 2, 4
                },
                new SortedSet <int> {
                    1, 2
                },
                new SortedSet <int> {
                    2, 3, 4
                },
                new SortedSet <int> {
                    2, 3
                },
                new SortedSet <int> {
                    3, 4
                },
                new SortedSet <int> {
                    2, 4
                },
            };

            var apriori = new Apriori(threshold: 3, confidence: 0);

            var classifier = apriori.Learn(dataset);

            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[] {1,3}, 1),
                //Tuple.Create(new[] {1,4}, 2),
                Tuple.Create(new[] { 2, 3 }, 3),
                Tuple.Create(new[] { 2, 4 }, 4),
                Tuple.Create(new[] { 3, 4 }, 3),
                //Tuple.Create(new[] {2,3,4}, 2),
            };

            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);
            }
        }
Exemple #26
0
        private void CallApriori(double support)
        {
            int result = 0;

            Apriori algorithm = new Apriori(support);

            algorithm.MileStoneEvent += algorithm_MileStoneEvent;
            algorithm.InputDataFile   = textDataFile.Text;
            algorithm.Process();
        }
Exemple #27
0
 static void Main(string[] args)
 {
     ProductRepository         productRepository         = new ProductRepository();
     PurchaseRepository        purchaseRepository        = new PurchaseRepository();
     AssociationRuleRepository associationRuleRepository = new AssociationRuleRepository();
     List <Product>            products  = productRepository.GetAllProducts();
     List <Purchase>           purchases = purchaseRepository.GetAllPurchases();
     Apriori apriori = new Apriori();
     List <AssociationRule> associatiationRules = apriori.ProccessApriori(0.14, 0.1, products, purchases);
 }
Exemple #28
0
 public void TestCandidateNull()
 {
     SetUp1();
     candidates = Apriori.GenerateCandidate(input.ElementAt(0), input.ElementAt(1));
     Assert.IsTrue(candidates == null);
     candidates = Apriori.GenerateCandidate(input.ElementAt(0), input.ElementAt(2));
     Assert.IsTrue(candidates == null);
     candidates = Apriori.GenerateCandidate(input.ElementAt(0), input.ElementAt(3));
     Assert.IsTrue(candidates == null);
 }
        public void UnionSetsTest_3Items()
        {
            var set = new List <string> {
                "banana", "apple", "potato", "grape"
            };
            var sut = new Apriori(null);

            var results = sut.UnionSets(set, 3);

            Assert.AreEqual(results.Count, 4);
        }
        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.");
        }
Exemple #31
0
        public void TestNextCandidates_Size3()
        {
            SetUp5();
            var a   = Apriori.GenerateNextCandidates(input);
            int aux = 0;

            foreach (String[] n in a)
            {
                n.SequenceEqual(solution.ToList().ElementAt(aux));
                aux++;
            }
        }
Exemple #32
0
        public AssociationRuleMatcher <int> CreateAprioriClassifier()
        {
            // Create a new a-priori learning algorithm with support 3
            Apriori apriori = new Apriori(threshold: 2, confidence: 0);

            int[][] histories = GetAllViewingHistories();

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

            return(classifier);
        }
Exemple #33
0
        public void ClassifierTest1()
        {
            // example from http://www3.cs.stonybrook.edu/~cse634/lecture_notes/07apriori.pdf

            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" },
            };

            var apriori = new Apriori<string>(threshold: 2, confidence: 0.7);

            var classifier = apriori.Learn(dataset);

            var rules = classifier.Rules;

            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("1", actual[0][0]);
            Assert.AreEqual("2", actual[1][0]);
            Assert.AreEqual("1", actual[2][0]);
            Assert.AreEqual("2", actual[2][1]);
            Assert.AreEqual("2", actual[3][0]);
            actual = classifier.Decide(new string[] { "2", "5" });
            Assert.AreEqual("1", actual[0][0]);
            Assert.AreEqual("2", actual[1][0]);
            Assert.AreEqual("1", actual[2][0]);
            Assert.AreEqual("2", actual[2][1]);
            Assert.AreEqual("1", actual[3][0]);
            actual = classifier.Decide(new string[] { "0", "5" });
            Assert.AreEqual("1", actual[0][0]);
            Assert.AreEqual("2", actual[1][0]);
            Assert.AreEqual("1", actual[2][0]);
            Assert.AreEqual("2", actual[2][1]);
        }