'''
##################################################################################
# k-means clustering by s.maroofi (maroofi[At]gmail.com) #
# License : MIT #
# Permission is hereby granted, free of charge, to any person obtaining a copy #
# of this software and associated documentation files (the "Software"), to deal #
# in the Software without restriction, including without limitation the rights #
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #
# copies of the Software, and to permit persons to whom the Software is #
# furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in all #
# copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #
# SOFTWARE. #
##################################################################################
'''
'''
Note that this is an Unsupervised algorithm.
This algorithm uses Forgy method for initialization since it is the preferable
method for standard kmeans.
There is no guarantee tha kemans algorithm converge to global optimum and
it highly depends on initialization. So you have to run it several times and
choose the best result.
It chooses random k samples as centers and continue to find the optimal center.
Stop condition :
1. number of iteration >= max_number_of_iteration
2. no change in clusters
Input parameters:
samples : this is the dataset you want to cluster(numpy array)
k : number of cluster
centers : user provided centers(default is None) and it must be a list of list
for example: centers = [
[feat1,feat2,feat3],
[feat1,feat2,feat3],
[feat1,feat2,feat3],
[feat1,feat2,feat3]
]
max_number_of_iteration : maximum number of iteration to stop(default is 1000).
'''
import numpy as np
class kmeans():
def __init__(self,samples,k=2,centers=None,max_number_of_iteration=1000):
self.max_number_of_iteration = max_number_of_iteration;
self.number_of_samples = len(samples);
self.cluster_number = np.ones((self.number_of_samples,)) * -1
self.k = k;
self.samples = samples
if(centers == None):
self.centers = list();
#select k random centers
temp_list=list()
while(len(self.centers)!=k):
center_temp = np.random.randint(0,self.number_of_samples);
if (center_temp not in temp_list):
self.centers.append(self.samples[center_temp]);
temp_list.append(center_temp)
#end if
#end while
else:
if isinstance(centers,list):
if(len(centers) == k):
self.centers = centers
else:
print("ERROR : centers length must be equal to number of clusters(k)");
return;
else:
print("ERROR : centers must be list");
return;
#end if
def compute_distance(self,instance1,instance2):
#euclidean distance
#you can replace this method with any metrics you like.
result = 0;
if(len(instance1)!=len(instance2)):
print("ERROR: instance1 and instance2 must be the same size.")
return
#return (np.sqrt(sum((abs(instance1-instance2)))))
return (np.sqrt(sum((instance1-instance2)**2)))
def run(self):
changed = np.ones((self.number_of_samples,));
iteration = 0;
distance_array = np.zeros((self.number_of_samples,self.k))
print('Starting iteration....')
#YOU CAN CHANGE THE STOP CONDITION HERE BY REMOVING ONE OF THESE CLAUSES
while(iteration