private Hashtable k_means ObjectParameters medians k_means_plus_plus n

 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
private Hashtable k_means()
{
ObjectParameters[] medians = k_means_plus_plus(); /*new ObjectParameters[clustCount];*/
Hashtable table = new Hashtable(clustCount);
//Random random = new Random();
for (int i = 0; i < clustCount; i++)
{
table[i] = new List<int>();
}
Hashtable prevTable = null;
while (true)
{
for(int i = 0; i < table.Count; i++)
{
((List<int>)table[i]).Clear();
}
// Для каждого объекта считаем расстояние до центров
for (int i = 1; i < objects.Length; i++)
{
if (isBadValue(objects[i]))
continue;
double[] distances = new double[clustCount];
for (int j = 0; j < clustCount; j++)
distances[j] = calculateDistance(objects[i], medians[j]);
int indexOfMin = Array.IndexOf(distances, distances.Min());
((List<int>)table[indexOfMin]).Add(i);
}
if (prevTable != null)
{
bool isSame = true;
for (int i = 0; i < table.Count; i++)
{
isSame = ((List<int>)table[i]).SequenceEqual((List<int>)prevTable[i]);
if (isSame == false)
break;
}
if (isSame == true)
break;
}
prevTable = (Hashtable)table.Clone();
// Пересчитываем средние (центры масс) по всем кластерам
for (int i = 0; i < clustCount; i++)
{
int squareSum = 0, perimSum = 0;
double compactSum = 0, elongationSum = 0, orientSum = 0;
foreach (int numberOfObject in (List<int>)table[i])
{
squareSum += objects[numberOfObject].Square;
perimSum += objects[numberOfObject].Perimeter;
compactSum += objects[numberOfObject].Compactness;
elongationSum += objects[numberOfObject].elongation;
// orientSum += objects[numberOfObject].OrientationOfMainAxis;
}
int count = ((List<int>)table[i]).Count();
if (count != 0)
{
medians[i].Square = squareSum / count;
medians[i].Perimeter = perimSum / count;
medians[i].Compactness = compactSum / count;
medians[i].elongation = elongationSum / count;
// medians[i].OrientationOfMainAxis = orientSum / count;
}
}
}
return table;
}