【Python】 x-meansを使ってクラスタリングする例
k-meansのクラスタ数を自動で決めてくれるx-meansという手法があることを以下で知ったので試してみようとしました。 qiita.com ただリンク先のコードは自分のデータセットに対しては「行列式が0で計算できない」といったようなエラーが出ました。それで代わりにx-meansを実装しているpyclusteringというライブラリで試したので、pyclusteringのx-meansの使い方をメモとして残します(pyclusteringはpip install pyclusteringでインストールできます)。
# -*- coding: utf-8 -*- import numpy as np from pyclustering.cluster.xmeans import xmeans, kmeans_plusplus_initializer from pyclustering.utils import draw_clusters if __name__ == "__main__": # データの準備 x = np.array([np.random.normal(loc, 0.1, 20) for loc in np.repeat([1,2], 2)]).flatten() #ランダムな80個の数を生成 y = np.array([np.random.normal(loc, 0.1, 20) for loc in np.tile([1,2], 2)]).flatten() #ランダムな80個の数を生成 points = np.concatenate((x[np.newaxis,:], y[np.newaxis,:]), axis=0).T.tolist() # クラスタ数2から探索させてみる initial_centers = kmeans_plusplus_initializer(points, 2).initialize() # クラスタリングの実行 instances = xmeans(points, initial_centers, ccore=True) instances.process() # クラスタはget_clustersで取得できる clusters = instances.get_clusters() # クラスタの平均は以下で計算できる centers = [] points = np.array(points) for cluster in clusters: c = points[cluster, :] centers.append(np.mean(c, axis=0)) # クラスタリング結果を表示する draw_clusters(points, clusters)