Design Script - Imperative kmeans

After the Dynamo teams persentation today on design script I got energized and dove back into Dynamo’s Imperative functions. I have had the goal for a few years to get Kmean to work in Design script with no luck. I got a bit closer today but still confused and not even sure if it is even possible.

Attached is the .dyn with the required function. How to inbed them into a while loop is the question?!?

Kmean (Python) explanation : CS221

Kmeans.dyn (54.0 KB)


Good persentation today, thanks for the inspration!


Great with your descriptions in dynamo .

Replication guides don’t work within Imperative blocks.
You could however create an associative function that does the needful and call it within the imperative block


See if this is adequate. Not complete though.

Kmeans-20210910-1.dyn (24.7 KB)

// Group by Centroid
def k1(pnts:var[]..[],cnts:var[]..[])
	lbl1 = "A"..#(List.Count(cnts))..1;

	//Distance to Centroids
	dst1 = pnts<1>.DistanceTo(cnts<2>);
	dst2 = List.SortByKey(lbl1,dst1<1>);
	dst3 = List.FirstItem(dst2["sortedList"]<1>);

	//Group by Closest to Centroid
	pnt1 = List.GroupByKey(pnts,dst3)["groups"];
	return pnt1;

// Centroid
def ctr (pnts:var[]..[])
	return Point.ByCoordinates(Math.Average(pnts.X),

// K Mean
def kMean (pnts:var[]..[],k:int)
	pnt1 = k1(pnts,pnts[1..k]);
	cnt1 = 1;
	pnt2 = [];
	pts1 = [Imperative]
		while (cnt1 <= k)
			ctr1 = ctr(pnt1);
			pnt2 = k1(List.Flatten(pnt1,-1),ctr1);
			cnt1 = cnt1 + 1;
			pnt1 = pnt2;
		return pnt2;
	return pts1;

Thanks @Vikram_Subbaiah!! What version of Dynamo did you use?
I open your script using Dynamo 2.6.1 and got one large cluster. I’ll be taking a closer look this weekend.

Dose this function make the Centroids?

1 Like

Try this new look daily build
I’ve used a csv file (change attached txt extension to csv) instead of Remember
Kmeans-20210910-2.dyn (16.0 KB)
pnts.txt (218.9 KB)




Looks fancy the new look…:wink: does it comes with next update for revit as well??

Ooh this is interesting. I was just looking at K Means for image segmentation…
Did you ever use it to group by color?
(Im researching ways to find all the ‘empty’ space in a view).