public void updatecentroid() { Dictionary <int, float> averages = new Dictionary <int, float>(); int usercount = 0; foreach (UserForKMeansWine user in clustermembers) { usercount++; foreach (KeyValuePair <int, Boolean> rating in user.transactions) { if (!averages.ContainsKey(rating.Key)) { averages.Add(rating.Key, Convert.ToInt16(rating.Value)); } else { averages[rating.Key] = (averages[rating.Key] + Convert.ToInt16(rating.Value)); } } } Dictionary <int, Boolean> newcentroidcoords = new Dictionary <int, bool>(); foreach (KeyValuePair <int, float> pair in averages) { Boolean result = (Math.Round(pair.Value / usercount) == 1); newcentroidcoords.Add(pair.Key, result); } currentcentroid = new UserForKMeansWine(int.MaxValue); currentcentroid.transactions = newcentroidcoords; }
public float distancebetweenthisanduser(UserForKMeansWine user2) { float[] set1 = new float[32]; float[] set2 = new float[32]; foreach (KeyValuePair <int, Boolean> transaction in transactions) { set1[transaction.Key] = Convert.ToInt16(transactions[transaction.Key]); set2[transaction.Key] = Convert.ToInt16(user2.transactions[transaction.Key]); } return(Clustering.calculateEuclidianDistance(set1, set2)); }
public static Cluster getClusterWithClosestCentroidForUser(List <Cluster> clusters, UserForKMeansWine user) { float lowestdistance = float.PositiveInfinity; Cluster currentcluster = null; foreach (Cluster cluster in clusters) { float currentdistance = user.distancebetweenthisanduser(cluster.currentcentroid); if (currentdistance < lowestdistance) { lowestdistance = currentdistance; currentcluster = cluster; } } if (currentcluster == null) { throw new ArgumentException("No clusters found to compute"); } return(currentcluster); }