r/learnmachinelearning • • 25d ago

i build Kmeans an unsupervised machine learning algorithm from scratch

It's Day 59 of building machine learning algorithms from Scratch and im currently into unsupervised learning in short i've completed all the algorithms in supervised learning.

Well the crazy part I'm only 2 algorithms and 2 concept for completing Machine learning and I'm diving into "Deep learning" I'm way too excited too explore new things,build new things, let see how far it takes me

Peoples dreams... have no end!!

72 Upvotes

13 comments sorted by

10

u/Ok-Library1020 24d ago

nice one. an edge case worth testing is a cluster that ends up with zero points after assignment, since the mean update divides by zero there. reinitializing that centroid or just keeping its old position avoids the NaNs

3

u/not-okarun 24d ago

I add a if-else to check whether the points len is zero or not, if true put old_centroid in centroid ,else calculate mean

thankyou for helping me

1

u/Ok-Library1020 24d ago

Nice, that handles the empty-cluster edge case cleanly. You could also test a deliberately empty cluster and confirm the next assignment step stays finite.

2

u/Intelligent-Tour8322 25d ago

What do the red crosses in the 1st picture represent?

2

u/not-okarun 24d ago edited 24d ago

the img i plot when I was testing my Kmeans I was very curious how the point shift, like i know it shift because of distances and recalculating means but i wanna see it so i plot 2 img first graph is when the centroid was initialise, second graph is after running the code, calculating everything only one time and as you can see changes happend the centroid move towards clusters it was run only one time so 2 centroid end up at one cluster, but the progress was happening and I was amazed to see it how the centroid were moving

2

u/Intelligent-Tour8322 24d ago

Ok thanks. A very cool thing you could try to do is plotting the position at every cycle and tracking the path of the three centroids. Maybe you could do that for different initial points and note the difference in the paths and number of iterations. Nice work btw :)

1

u/OliverThaCat 25d ago

The “points” to compare the cluster locations against

1

u/Intelligent-Tour8322 25d ago

Yeah, but in the legend it is written "centroids"

2

u/paultoc 24d ago

I believe that's the technical name for it in the algorithm

3

u/ds_account_ 24d ago

Nice, now can you do it in 40 min during a coding interview.

1

u/Open_Two_1119 23d ago

Self.iterations is unused :)

Great job!

1

u/cajmorgans 23d ago

Try solving it with broadcasting instead of loops! You can do this entirely with matrix multiplication and some broadcasting

-3

u/Fun-Site-6434 24d ago

Sure you did buddy!