-
Notifications
You must be signed in to change notification settings - Fork 7
/
Cluster.py
60 lines (49 loc) · 1.85 KB
/
Cluster.py
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
# -*- coding: utf-8 -*-
__author__ = 'RicardoMoya'
import numpy as np
class Cluster:
"""
Class to represent a Cluster: set of points and their centroid
"""
def __init__(self, points):
if len(points) == 0:
raise Exception("Cluster cannot have 0 Points")
else:
self.points = points
self.dimension = points[0].dimension
# Check that all elements of the cluster have the same dimension
for p in points:
if p.dimension != self.dimension:
raise Exception(
"Point %s has dimension %d different with %d from the rest "
"of points") % (p, len(p), self.dimension)
# Calculate Centroid
self.centroid = self.calculate_centroid()
self.converge = False
def calculate_centroid(self):
"""
Method that calculates the centroid of the Cluster, calculating
the average of each of the coordinates of the points
:return: Centroid of cluster
"""
sum_coordinates = np.zeros(self.dimension)
for p in self.points:
for i, x in enumerate(p.coordinates):
sum_coordinates[i] += x
return (sum_coordinates / len(self.points)).tolist()
def update_cluster(self, points):
"""
Calculate the new centroid and check if converge
:param points: list of new points
:return: updated cluster
"""
old_centroid = self.centroid
self.points = points
self.centroid = self.calculate_centroid()
self.converge = np.array_equal(old_centroid, self.centroid)
def __repr__(self):
cluster = 'Centroid: ' + str(self.centroid) + '\nDimension: ' + str(
self.dimension)
for p in self.points:
cluster += '\n' + str(p)
return cluster + '\n\n'