Name

ST_ClusterKMeans — 使用 K 均值算法返回每个输入几何图形的簇 id 的窗口函数。

Synopsis

`integer ST_ClusterKMeans(`geometry winset geom, integer number_of_clusters, float max_radius`)`;

描述

`max_radius` 如果设置，将导致 ST_ClusterKMeans 生成比 `k` 更多的簇，确保输出中没有簇的半径大于 `max_radius`。 这在可达性分析中很有用。

示例

```CREATE TABLE parcels AS
SELECT lpad((row_number() over())::text,3,'0') As parcel_id, geom,
('{residential, commercial}'::text[])[1 + mod(row_number()OVER(),2)] As type
FROM
ST_Subdivide(ST_Buffer('SRID=3857;LINESTRING(40 100, 98 100, 100 150, 60 90)'::geometry,
40, 'endcap=square'),12) As geom;
```

```SELECT ST_ClusterKMeans(geom, 3) OVER() AS cid, parcel_id, geom
FROM parcels;```

```cid | parcel_id |   geom
-----+-----------+---------------
0 | 001       | 0103000000...
0 | 002       | 0103000000...
1 | 003       | 0103000000...
0 | 004       | 0103000000...
1 | 005       | 0103000000...
2 | 006       | 0103000000...
2 | 007       | 0103000000...
```

```SELECT ST_ClusterKMeans(geom, 3) over (PARTITION BY type) AS cid, parcel_id, type
FROM parcels;```
```cid | parcel_id |    type
-----+-----------+-------------
1 | 005       | commercial
1 | 003       | commercial
2 | 007       | commercial
0 | 001       | commercial
1 | 004       | residential
0 | 002       | residential
2 | 006       | residential
```

```create table kontur_population_3000km_clusters as
select
geom,
ST_ClusterKMeans(
ST_Force4D(
ST_Transform(ST_Force3D(geom), 4978), -- cluster in 3D XYZ CRS
mvalue => population -- set clustering to be weighed by population
),
20,                      -- aim to generate at least 20 clusters
max_radius => 3000000    -- but generate more to make each under 3000 km radius
) over () as cid
from
kontur_population;
```