K-meansは標準の教師なしクラスタリングアルゴリズムであり、一連の「ポイント」といくつかのクラスターKが与えられると、各「ポイント」をK個のクラスターのいずれかに割り当てます。
K平均の疑似コード
K-meansには多くのバリアントがあることに注意してください。以下で説明するアルゴリズムを実装する必要があります。同じ初期点が与えられた場合にこのアルゴリズムと同じ結果が得られる限り、アルゴリズムにいくつかのバリエーションを持たせたり、組み込みを使用したりできます。
この課題では、すべての入力が2D平面上の点になります(各点は、xとyの座標で表されます)。
Inputs: K, the number of clusters
P, the set of points
Choose K points of P uniformly at random
Each chosen point is the initial centroid of its cluster
Loop:
For each point in P:
Assign to the cluster whose centroid is the nearest (Euclidean distance)
In case of a tie, any of the tied cluster can be chosen
Recompute the centroid of each cluster:
Its x coordinate is the average of all x's of the points in the cluster
Its y coordinate is the average of all y's of the points in the cluster
Until the clusters don't change from one iteration to the next
Output: the set of clusters
入力と出力
- KとPを介して
STDIN
、または関数の引数などとして使用できます。 - PおよびPのポイントは、選択した言語のセット/リストに自然な構造を使用して表すことができます。
- Kは厳密に正の整数です。
- 入力が有効であると想定することができます。
- Pには常に少なくともKポイントがあります。
- クラスタを
STDOUT
に出力したり、関数から返したりすることができます。 - クラスターの順序とクラスター内の順序は重要ではありません。-クラスターを表すポイントのグループ、またはクラスターの識別子(整数など)でラベル付けされた各ポイントを返すことができます。
テストケース
結果のクラスターは最初に選択されたポイントに依存するため、すべてが同じ結果(またはコードを実行するたびに同じ結果)になるとは限りません。
したがって、出力はサンプル出力としてのみ使用してください。
Input:
K = 1
P = [[1,2.5]]
Output:
[[[1,2.5]]]
Input:
K = 3
P = [[4,8], [15,16], [23,42], [-13.37,-12.1], [666,-666]]
Output:
[[[666,-666]],[[-13.37,-12.1],[4,8]],[[15,16],[23,42]]]
Input:
K = 2
P = [[1,1], [1,1], [1,1]]
Output:
[[[1,1]],[[1,1],[1,1]]]
得点
これはcode-golfなので、バイト単位の最も短い答えが優先されます。
1
すべてのポイントにラベルが付けられ、2番目のクラスターのすべてのポイントにラベルが付けられる2
など)
K=2, P = [[1,1], [1,1], [1,1]]
。