Standard k-mean Algorithm implemented in python

link to know — what is standard k-mean algorithm

Here is 1st a Point class –

from math import sqrt
class Point(object):
def __init__(self, x, y):
def distance(self, other):
return sqrt(( self.x - other.x)**2 +( self.y - other.y)**2)
def __add__(self,p):
localx = self.x + p.x
localy = self.y + p.y
return Point(localx, localy)
def __truediv__(self, p):
self.x = self.x / p
self.y = self.y / p
return self
def __repr__(self):
return str(self.x) +' '+ str(self.y)

Here is Cluster class for clustering based on points near to center point.

class Cluster(object):
def __init__(self, x, y): = Point(x, y)
self.points = []

def update(self):
temp=Point(0, 0)
for point in self.points:
temp += point
print(len(self.points)) = temp/count
self.points = []
def add_point(self, point):

Here is Compute Class in which we did all stuff of calculating dist

def compute_result(points):
points = [Point(*point) for point in points]
a = Cluster(1,0)
b = Cluster(-1,0)
a_old = []
for _ in range(10000): # max iterations
for point in points:
if point.distance( < point.distance(
# add the right point
# add the right point
if a_old == a.points:
a_old = a.points
return [(,, (,]

Check More on :




Research Machine Learning Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SQA Engineer to Dev?

SQL Database with Python

The Hidden Factor of Company Size: Why Your Project Team Should Be a Part of Something Bigger

Installation and usage of UniConvertor(Sk1 project): A file conversion tool

Ballerina REST API service with Cosmos DB connector — Part2

Lightning Node Performance: Testing TPS

Control layout and styling in Build Annotations

Automatic Flamegraphs for Benchmarks in Rust

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Research Machine Learning Engineer

More from Medium

Applying Graph Theory concepts in basic data manipulation problems

Real-time classification with Deephaven and SciKit-Learn

Ultimate python DateParser with holidays, paydays and all the good stuff.

Explore how to apply continual learning to your machine learning models