text stringlengths 0 897 |
|---|
initialize k clusters at random positions |
repeat until done: |
assign each data point to the nearest cluster |
move each cluster to the centroid of data assigned to it |
``` |
Using Mini Micro, we can implement this algorithm in a very visual way, using sprites for the data points and cluster centroids. It comes out a bit longer, but it's totally worth it. |
{caption:"k-means clustering program."} |
```miniscript |
import "mathUtil" |
import "listUtil" |
clear |
Datum = new Sprite |
Datum.image = file.loadImage("/sys/pics/shapes/Circle.png") |
Datum.scale = 0.2 |
Cluster = new Sprite |
Cluster.image = file.loadImage("/sys/pics/XO/X-white.png") |
Cluster.scale = 0.2 |
// Define the number of data points (n) and centroids (k). |
n = 40 |
k = 4 |
// Create some random data points. |
data = [] |
for i in range(1, n) |
d = new Datum |
d.x = round(960 * rnd) // (960 is the screen width) |
d.y = round(640 * rnd) // (640 is screen height) |
display(4).sprites.push d // (display 4 is the sprite display) |
data.push d |
end for |
// Create the centroids, also in random starting positions. |
centroids = [] |
colors = [color.orange, color.aqua, color.fuchsia, color.lime] |
for i in range(1, k) |
c = new Cluster |
c.tint = colors[i-1] |
c.x = round(960) * rnd |
c.y = round(640 * rnd) |
display(4).sprites.push c |
centroids.push c |
end for |
// update all data points by assigning them to the nearest centroid |
// also update dataX and dataY lists within each centroid |
updateData = function() |
for c in centroids |
c.dataX = [] |
c.dataY = [] |
end for |
for d in data |
bestCluster = null |
for c in centroids |
dist = mathUtil.distance(d, c) |
if bestCluster == null or dist < bestDist then |
bestCluster = c |
bestDist = dist |
end if |
end for |
d.tint = bestCluster.tint |
bestCluster.dataX.push d.x |
bestCluster.dataY.push d.y |
end for |
end function |
// update the centroids by moving them to the average position |
// of the data points assigned to them |
updateClusters = function() |
for c in centroids |
if not c.dataX then continue |
c.x = c.dataX.mean |
c.y = c.dataY.mean |
end for |
end function |
// Repeat those steps until done! |
for i in range(10) |
updateData |
updateClusters |
wait // slow things down enough that you can see! |
end for |
``` |
Notice that even though the pseudocode didn't show any functions, I chose to put each of the major update steps into its own function in the MiniScript implementation. That just helps keep things neat and organized. Also note that we're defining "done" as simply completing 10 updates. You might need more in some cas... |
{width:"75%"} |
 |
Run this a few times; since the data and initial cluster positions are random, you'll get a different result every time. |
## Next Steps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.