名前

ST_ClusterKMeans — 入力ジオメトリごとにk平均法アルゴリズムを使ってクラスタ番号を返すウィンドウ関数です。

概要

integer ST_ClusterKMeans(geometry winset geom, integer number_of_clusters);

説明

入力ジオメトリ毎に、2次元距離に基づくK-meansクラスタ番号を返します。クラスタリングに使われる距離は、2次元ジオメトリについては重心間の距離と、3次元ジオメトリについてはバウンディングボックスの重心間の距離です。POINT入力については、M値が入力の重みとして扱われ、0より大きい値にしなければなりません。

Enhanced: 3.1.0 3次元ジオメトリと重みに対応するようになりました

Availability: 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, 5) 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...
(7 rows)

-- 種別による区画クラスタの分割
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
(7 rows)
-- 日付変更線周辺のポイントのクラスタリングは3次元XYZのEPSG:4978で実行できます

SELECT ST_ClusterKMeans(ST_Transform(ST_Force3D(geom), 4978), 3) over () AS cid, parcel_id, type
FROM parcels;
-- 結果 --
┌─────┬───────────┬─────────────┐
│ cid │ parcel_id │    type     │
├─────┼───────────┼─────────────┤
│   1 │ 001       │ commercial  │
│   2 │ 002       │ residential │
│   0 │ 003       │ commercial  │
│   1 │ 004       │ residential │
│   0 │ 005       │ commercial  │
│   2 │ 006       │ residential │
│   0 │ 007       │ commercial  │
└─────┴───────────┴─────────────┘
(7 rows)

関連情報

ST_ClusterDBSCAN, ST_ClusterIntersecting, ST_ClusterWithin, ST_Subdivide