public double EuclideanDistance(DataItem data, DataItem mean) { double difference = 0; difference = Math.Pow(data.X - mean.X, 2); difference += Math.Pow(data.Y - mean.Y, 2); return Math.Sqrt(difference); }
static bool ExpandCluster(List<DataItem> points, DataItem p, int clusterId, double eps, int minPts) { List<DataItem> seeds = GetRegion(points, p, eps); if (seeds.Count < minPts) // no core point { p.Cluster = Point.NOISE; return false; } else // all points in seeds are density reachable from point 'p' { for (int i = 0; i < seeds.Count; i++) seeds[i].Cluster = clusterId; seeds.Remove(p); while (seeds.Count > 0) { DataItem currentP = seeds[0]; List<DataItem> result = GetRegion(points, currentP, eps); if (result.Count >= minPts) { for (int i = 0; i < result.Count; i++) { DataItem resultP = result[i]; if (resultP.Cluster == DataItem.UNCLASSIFIED || resultP.Cluster == DataItem.NOISE) { if (resultP.Cluster == Point.UNCLASSIFIED) seeds.Add(resultP); resultP.Cluster = clusterId; } } } seeds.Remove(currentP); } return true; } }
public void Cluster() { while (points.Count > 0) { Random rnd = new Random(); var index = rnd.Next(0, points.Count); DataItem center = points[index]; DataItem newCenter = center; //inside points List<DataItem> lst = new List<DataItem>(); while (center == newCenter) { foreach (var p in points) { if (Math.Sqrt(Math.Pow((p.X - center.X), 2) + Math.Pow((p.Y - center.Y), 2)) < R) { lst.Add(p); } } //power center double powerX = 0; double powerY = 0; foreach (var p in lst) { powerX += p.X; powerY += p.Y; } double powerCenterX = powerX / lst.Count; double powerCenterY = powerY / lst.Count; newCenter = new DataItem(powerCenterX, powerCenterY); } result.Add(lst); centers.Add(newCenter); foreach (var p in lst) { points.Remove(p); } } }
static List<DataItem> GetRegion(List<DataItem> points, DataItem p, double eps) { List<DataItem> region = new List<DataItem>(); for (int i = 0; i < points.Count; i++) { int distSquared = DataItem.DistanceSquared(p, points[i]); if (distSquared <= eps) region.Add(points[i]); } return region; }
public static int DistanceSquared(DataItem p1, DataItem p2) { double diffX = p2.X - p1.X; double diffY = p2.Y - p1.Y; return (int) (diffX * diffX + diffY * diffY); }