> For the complete documentation index, see [llms.txt](https://gitbook.testingwaters.in/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.testingwaters.in/geometry-1/k-mean.md).

# K Mean

K-means stores **k** centroids that it uses to define clusters. A point is considered to be in a particular cluster if it is closer to that cluster's centroid than any other centroid.

![Grouping points into k (no.s) clusters](/files/-MjDw6lFpiVErPvKSEF4)

<https://stanford.edu/~cpiech/cs221/handouts/kmeans.html>

```d
// Group by Centroid
def k1(pnts:var[]..[],cnts:var[]..[])
{
	//Labels
	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),
	Math.Average(pnts.Y),Math.Average(pnts.Z));
};

// 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;
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.testingwaters.in/geometry-1/k-mean.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
