Ejemplo n.º 1
0
    // Called by LandMap.GetZones (), returns number of subregions
    public int ClusterLocationsAccordKMedoidsPAM(MapPoint[,] points, TerrainVerticesDatabase vertDatabase)
    {
        // K-means cluster algorithm to separate locations in the regions

        int regionId = 0;

        for (int isleId = 0; isleId < regions.Count; isleId++)
        {
            MapRegion region = regions[isleId];

            double[][] tileLocations = new double[region.turf.Count][];

            for (int i = 0; i < tileLocations.Length; i++)
            {
                tileLocations[i] = new double[3];

                TerrainVertData vertData = vertDatabase.GetVertDataFromRegionTile(region.turf[i], isleId);
                if (vertData != null)
                {
                    tileLocations[i][0] = region.turf[i].x;
                    tileLocations[i][1] = vertData.inlandPosition;
                    tileLocations[i][2] = region.turf[i].y;
                }
                else
                {
                    LoggerTool.Post("Null from VertDB for " + region.turf[i].ToString());
                }
            }

            int k = InitializeNumOfK(tileLocations.Length);
            k = Mathf.Max(1, k);
            Debug.Log(k + " centroid(s)");

            KMedoids kmedoidsPam = new KMedoids(k);
            kmedoidsPam.MaxIterations = 100;

            KMedoidsClusterCollection <double> clusters = kmedoidsPam.Learn(tileLocations);

            int[] labels = clusters.Decide(tileLocations);

            Debug.Log("Number of labels = " + labels.Length);
            for (int i = 0; i < labels.Length; i++)
            {
                points[(int)tileLocations[i][0], (int)tileLocations[i][2]].areaValue = regionId + labels[i];
            }

            regionId += k;
        }

        return(regionId);
    }
Ejemplo n.º 2
0
        public void doc_learn()
        {
            #region doc_learn
            Accord.Math.Random.Generator.Seed = 0;

            // Declare some observations
            int[][] observations = new int[][]
            {
                new[] { 2, 6 }, // a
                new[] { 3, 4 }, // b
                new[] { 3, 8 }, // a
                new[] { 4, 7 }, // a
                new[] { 6, 2 }, // b
                new[] { 6, 4 }, // b
                new[] { 7, 3 }, // b
                new[] { 7, 4 }, // b
                new[] { 8, 5 }, // b
                new[] { 7, 6 }  // b
            };

            // Create a new 2-Medoids algorithm.
            var kmedoidsPam = new KMedoids <int>(2, new Manhattan());
            kmedoidsPam.MaxIterations = 100;

            // Compute and retrieve the data centroids
            var clusters = kmedoidsPam.Learn(observations);

            // Use the centroids to parition all the data
            int[] labels = clusters.Decide(observations);
            #endregion

            Assert.AreEqual(labels[0], labels[2]);
            Assert.AreEqual(labels[0], labels[3]);

            Assert.AreEqual(labels[4], labels[1]);
            Assert.AreEqual(labels[4], labels[5]);
            Assert.AreEqual(labels[4], labels[6]);
            Assert.AreEqual(labels[4], labels[7]);
            Assert.AreEqual(labels[4], labels[8]);
            Assert.AreEqual(labels[4], labels[9]);
        }
Ejemplo n.º 3
0
    // Called by LandMap.GetZones (), returns number of subregions
    public int ClusterLocationsAccordKMedoidsPAM(MapPoint[,] points)
    {
        // K-medoids cluster algorithm to separate locations in the regions

        int regionId = 0;

        for (int isleId = 0; isleId < regions.Count; isleId++)
        {
            MapRegion region = regions[isleId];

            double[][] tileLocations = new double[region.turf.Count][];

            for (int i = 0; i < tileLocations.Length; i++)
            {
                tileLocations[i]    = new double[2];
                tileLocations[i][0] = region.turf[i].x;
                tileLocations[i][1] = region.turf[i].y;
            }

            int k = InitializeNumOfK(region.turf.Count);
            Debug.Log(k + " centroid(s)");

            KMedoids kmedoidsPam = new KMedoids(k);
            kmedoidsPam.MaxIterations = 100;

            KMedoidsClusterCollection <double> clusters = kmedoidsPam.Learn(tileLocations);

            int[] labels = clusters.Decide(tileLocations);

            Debug.Log("Number of labels = " + labels.Length);
            for (int i = 0; i < labels.Length; i++)
            {
                points[(int)tileLocations[i][0], (int)tileLocations[i][1]].areaValue = regionId + labels[i];
            }

            regionId += k;
        }

        return(regionId);
    }
Ejemplo n.º 4
0
        public JsonResult PredictPossibleProducts()
        {
            var userId       = 0;
            int knnNum       = 5;
            int clusterNum   = 4;
            var userIdString = "";

            if (HttpContext.Session["userid"] == null)
            {
                return(Json(new { errorCode = 1, errorMessage = "יוזר לא חוקי" }));
            }

            userIdString = HttpContext.Session["userid"].ToString();
            var didParsed = Int32.TryParse(userIdString, out userId);

            if (!didParsed)
            {
                return(Json(new { errorCode = 1, errorMessage = "יוזר לא חוקי" }));
            }

            var userGender = _context.Users
                             .Where(x => x.Id == userId)
                             .Select(x => x.Gender)
                             .SingleOrDefault();

            var trainData = _context.Purchases
                            .OrderBy(x => x.UserId)
                            .Where(x => x.Product != null)
                            .Select(x => new
            {
                userId     = x.UserId.Value,
                size       = x.Product.Size,
                type       = x.Product.ProductTypeId,
                gender     = x.Product.ProductType.Gender,
                genderUser = x.User.Gender
            })
                            .ToList();

            if (trainData.Count < knnNum || trainData.Count < clusterNum)
            {
                return(Json(new { errorCode = 2, errorMessage = "אין מספיק מידע" }));
            }
            var inputs = trainData.Select(x =>
            {
                double[] res = new double[]
                {
                    Convert.ToInt32(x.gender),
                    Convert.ToInt32(x.genderUser),
                    x.type.Value,
                    x.size
                };

                return(res);
            })
                         .ToArray();

            var codification = new Codification <double>()
            {
                CodificationVariable.Categorical,
                CodificationVariable.Categorical,
                CodificationVariable.Categorical,
                CodificationVariable.Discrete
            };

            // Learn the codification from observations
            var model = codification.Learn(inputs);

            // Transform the mixed observations into only continuous:
            double[][] newInputs = model.ToDouble().Transform(inputs);

            KMedoids kmeans   = new KMedoids(k: clusterNum);
            var      clusters = kmeans.Learn(newInputs);

            int[] labels = clusters.Decide(newInputs);

            var knn5 = new KNearestNeighbors(k: knnNum);

            knn5.Learn(newInputs, labels);

            var purchasesById = _context.Purchases
                                .Where(x => x.Product != null)
                                .Select(x => new
            {
                userId     = x.UserId.Value,
                size       = x.Product.Size,
                type       = x.Product.ProductTypeId,
                gender     = x.Product.ProductType.Gender,
                genderUser = x.User.Gender
            })
                                .GroupBy(x => x.userId)
                                .ToList();

            IList <Tuple <int, int[]> > labelsForUsers = new List <Tuple <int, int[]> >();

            for (int i = 0; i < purchasesById.Count; i++)
            {
                var userInputs = purchasesById[i].
                                 Select(x =>
                {
                    double[] res = new double[]
                    {
                        Convert.ToInt32(x.gender),
                        Convert.ToInt32(x.genderUser),
                        x.type.Value,
                        x.size
                    };

                    return(res);
                })
                                 .ToArray();

                double[][] newUserInputs = model.ToDouble().Transform(userInputs);
                labelsForUsers.Add(new Tuple <int, int[]>(purchasesById[i].Key, clusters.Decide(newUserInputs).Distinct().ToArray()));
            }

            var productIdsUserBought = _context.Purchases
                                       .Where(x => x.UserId == userId)
                                       .Select(x => x.ProductId)
                                       .Distinct()
                                       .ToList();

            var validProductTypeIds = _context.Purchases
                                      .Where(x => x.UserId == userId)
                                      .Select(x => x.Product.ProductTypeId)
                                      .Distinct()
                                      .ToList();

            var productsToPredict = _context.Products
                                    .Where(x => !productIdsUserBought.Contains(x.Id))
                                    .Where(x => validProductTypeIds.Contains(x.ProductTypeId))
                                    .Select(x => new
            {
                id         = x.Id,
                size       = x.Size,
                type       = x.ProductTypeId,
                gender     = x.ProductType.Gender,
                genderUser = userGender
            })
                                    .ToList();

            var predInputs = productsToPredict.Select(x =>
            {
                double[] res = new double[]
                {
                    Convert.ToInt32(x.gender),
                    Convert.ToInt32(x.genderUser),
                    x.type.Value,
                    x.size
                };

                return(res);
            })
                             .ToArray();

            double[][] newPredInputs = model.ToDouble().Transform(predInputs);

            int[] newLabels = knn5.Decide(newPredInputs);

            IList <int> productIdsPrediction = new List <int>();
            var         userLabels           = labelsForUsers.Where(x => x.Item1 == userId).FirstOrDefault() != null?
                                               labelsForUsers.Where(x => x.Item1 == userId).FirstOrDefault().Item2 : new int[0];

            for (int i = 0; i < newLabels.Length; i++)
            {
                if (userLabels.Contains(newLabels[i]))
                {
                    productIdsPrediction.Add(productsToPredict[i].id);
                }
            }

            var predictedProduct = _context.Products
                                   .Where(x => productIdsPrediction.Contains(x.Id))
                                   .Select(x => new
            {
                Id          = x.Id,
                Name        = x.Name,
                Price       = x.Price,
                Size        = x.Size,
                PictureName = x.PictureName
            })
                                   .ToList();

            return(Json(new { products = predictedProduct }, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 5
0
        public ActionResult SuggestedItems()
        {
            var userId = HttpContext.Session["UserID"];


            if (userId != null)
            {
                int id     = (int)userId;
                var orders = db.Orders.Where(x => x.UserID == id).Select(x => x.ID).ToList();

                if (orders.Count != 0)
                {
                    var joinDB = db.Orders.Join(db.Items,
                                                o => o.ItemID,
                                                i => i.ItemID,
                                                (o, i) => new
                    {
                        isdeleted  = i.IsDeleted,
                        UserID     = o.UserID,
                        Gender     = i.Gender,
                        Brand      = i.Brand,
                        ItemTypeId = i.ItemTypeId
                    }).Where(x => x.isdeleted == false).ToList();

                    var trainData = joinDB.Select(X =>
                                                  new
                    {
                        UserID     = X.UserID,
                        Gender     = X.Gender,
                        Brand      = X.Brand,
                        ItemTypeId = X.ItemTypeId
                    }).OrderBy(x => x.UserID).ToList();

                    DataTable table = new DataTable("");
                    table.Columns.Add("ItemTypeId", typeof(int));
                    table.Columns.Add("Brand", typeof(string));
                    table.Columns.Add("Gender", typeof(string));
                    foreach (var row in trainData)
                    {
                        table.Rows.Add(row.ItemTypeId, row.Brand, row.Gender);
                    }

                    var codebook = new Codification(table);

                    DataTable result = codebook.Apply(table);

                    // The resulting table can be transformed to jagged array:
                    double[][] matrix = Matrix.ToJagged(result);

                    KMedoids kmeans = new KMedoids(k: 6)
                    {
                    };


                    var   clusters = kmeans.Learn(matrix);
                    int[] labels   = clusters.Decide(matrix);



                    var purchasesById = joinDB.Select(X =>
                                                      new
                    {
                        UserID     = X.UserID,
                        Gender     = X.Gender,
                        Brand      = X.Brand,
                        ItemTypeId = X.ItemTypeId
                    }).GroupBy(x => x.UserID).ToList();

                    IList <Tuple <int, int[]> > labelsForUsers = new List <Tuple <int, int[]> >();

                    // מתאים כל רכישה למבנה למידה
                    for (int i = 0; i < purchasesById.Count; i++)
                    {
                        table.Clear();

                        foreach (var row in purchasesById[i])
                        {
                            table.Rows.Add(row.ItemTypeId, row.Brand, row.Gender);
                        }

                        codebook = new Codification(table);

                        result = codebook.Apply(table);

                        // The resulting table can be transformed to jagged array:
                        double[][] newUserInputs = Matrix.ToJagged(result);
                        //var Currentlusters = kmeans.Learn(newUserInputs);
                        int[] currentLabels = clusters.Decide(newUserInputs).Distinct();

                        // יקח את כל הרכישות של יוזר שנמצאות בלאסטר
                        labelsForUsers.Add(new Tuple <int, int[]>(purchasesById[i].Key, currentLabels));
                    }
                    var itemIdsUserBought = db.Orders
                                            .Where(x => x.UserID == id)
                                            .Select(x => x.ItemID)
                                            .Distinct()
                                            .ToList();

                    var productsToPredict = db.Items
                                            .Where(x => !itemIdsUserBought.Contains(x.ItemID))
                                            .Where(x => x.IsDeleted == false)
                                            .Select(x => new
                    {
                        id         = x.ItemID,
                        Brand      = x.Brand,
                        Gender     = x.Gender,
                        ItemTypeId = x.ItemTypeId
                    }).ToList();


                    table.Clear();

                    foreach (var row in productsToPredict)
                    {
                        table.Rows.Add(row.ItemTypeId, row.Brand, row.Gender);
                    }

                    codebook = new Codification(table);

                    DataTable ItemInputs = codebook.Apply(table);

                    // The resulting table can be transformed to jagged array:
                    double[][] NewItemInputs = Matrix.ToJagged(ItemInputs);


                    int[] lol = clusters.Decide(NewItemInputs);

                    IList <int> productIdsPrediction = new List <int>();
                    var         userLabels           = labelsForUsers.Where(x => x.Item1 == id).FirstOrDefault().Item2;
                    for (int i = 0; i < lol.Length; i++)
                    {
                        if (userLabels.Contains(lol[i]))
                        {
                            productIdsPrediction.Add(productsToPredict[i].id);
                        }
                    }

                    var predictedProduct = db.Items
                                           .Where(x => productIdsPrediction.Contains(x.ItemID))
                                           .ToList();

                    return(View("SuggestedItems", predictedProduct));
                }
            }
            return(View("SuggestedItems", new List <Item>()));
        }