-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathK_means.cs
122 lines (94 loc) · 3.37 KB
/
K_means.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace Clusterization_algorithms
{
class K_means
{
/* Dictionary contain all pairs (point, number_of_cluster),
* if (cluster = 0) => point not belong to cluster*/
private Dictionary<Point, int> points = new Dictionary<Point, int>();
private List<Point> seeds;
private Graphic graphic;
public List<Point> Seeds { get => seeds; set => seeds = value; }
public void setPoints(Dictionary<Point, int> pointDictionary) {
points.Clear();
foreach (KeyValuePair<Point, int> point in pointDictionary)
{
points.Add(point.Key, point.Value);
}
}
public K_means()
{
}
public K_means(Graphic graphic)
{
this.graphic = graphic;
}
public Dictionary<Point, int> getPoints()
{
return points;
}
public void DrawSeeds() {
foreach (Point seed in seeds)
graphic.DrawPoint(seed, Brushes.Red, 6);
}
//write select point to cluster
private void AddToCluster(KeyValuePair<Point, int> point, int clusterNum) {
points.Remove(point.Key);
points.Add(point.Key, clusterNum);
//Calculator.printPointsDictionary(points);
}
private void FindAllClusters() {
for (int i = 0; i < points.Count; i++) {
double distance = 99999;
int closerSeedNum = 0;
KeyValuePair<Point, int> point = points.ElementAt(i);
for (int j = 0; j < seeds.Count; j++) {
double dist = Calculator.calcDistance(point.Key, seeds.ElementAt(j));
if (dist < distance) {
distance = dist;
closerSeedNum = j + 1;
}
}
AddToCluster(point, closerSeedNum);
graphic.DrawLine(seeds.ElementAt(closerSeedNum - 1), point.Key, Color.LightGreen);
}
}
private Boolean FindCentroids() {
List<Point> centroids = new List<Point> { };
for (int i = 0; i < seeds.Count; i++) {
List<Point> pointList = new List<Point> { };
foreach (KeyValuePair<Point, int> pair in points) {
if (i + 1 == pair.Value)
pointList.Add(pair.Key);
}
Point centroid = Calculator.findCentroid(pointList);
centroids.Add(centroid);
}
if (!isEqualSeed(centroids))
seeds = centroids;
else return false;
return true;
}
public void startK_means() { //
graphic.DrawPointDictionary(points);
DrawSeeds();
FindAllClusters();
if (FindCentroids()) {
graphic.PAUSE(100);
graphic.ClearImage();
startK_means();
}
DrawSeeds();
}
private Boolean isEqualSeed(List<Point> list) {
for (int i = 0; i < seeds.Count; i++) {
if (seeds.ElementAt(i) != list.ElementAt(i))
return false;
}
return true;
}
}
}