ST_ClusterKMeans — 使用 K-means 演算法為每個輸入幾何圖形返回群集 ID 的視窗函數。
integer ST_ClusterKMeans(
geometry winset geom, integer number_of_clusters, float max_radius)
;
為每個輸入幾何圖形返回 K-means 群集編號。用於群集的距離是 2D 幾何圖形質心之間的距離,以及 3D 幾何圖形邊界框中心之間的距離。對於 POINT 輸入,M 坐標將被視為輸入的權重,並且必須大於 0。
如果設定了 max_radius
,ST_ClusterKMeans 將產生比 k
更多的群集,以確保輸出中沒有群集的半徑大於 max_radius
。這在可達性分析中很有用。
增強功能:3.2.0 支援 max_radius
增強功能:3.1.0 支援 3D 幾何圖形和權重
可用性:2.3.0
產生範例用的虛擬地塊集合
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;
依群集編號 (cid) 著色的地塊
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
範例:使用 3D 群集和權重對預先彙總的行星規模資料人口資料集進行群集。根據 Kontur 人口資料,識別至少 20 個中心距離不超過 3000 公里的區域
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;
按上述規格群集的世界人口產生 46 個群集。群集集中在人口稠密的地區(紐約、莫斯科)。格陵蘭是一個群集。有些島嶼群集跨越反子午線。群集邊緣遵循地球的曲率。