いろいろ倉庫

KNIME、EXCEL、R、Pythonなどの備忘録

【KNIME】Spectral Clusteringでクラスタリングしたい。

・先日KNIMEでk-meansクラスタリングなどを実施してみた。k-meansクラスタリングの特徴は、プロットした空間中で中心から距離をベースに考えるところで、要は2次元グラフ上なら丸く分布していないと綺麗に分けることができない。

・歪んだ分布の場合、Spectral Clusteringなどの少々ヒネた手法を使う必要がある。

・KNIMEでこれをどう試せば良いのか分からなかったので、Pythonノードで実施した。

・まず、scikit-learnで三日月型のデータを作った(下図)。

f:id:choron81:20211218000006p:plain

Python Scriptノードの中身

import numpy as np
import pandas as pd
from sklearn import datasets as sd 

data = sd.make_moons(n_samples=100,noise=0.05,random_state=0)

output_table_1 = pd.DataFrame(data[0])

 

・次に、これらをk-meansクラスタリングとSpectral Clusteringでラベル付けし、元データと併せた(下図)。

f:id:choron81:20211218000304p:plain

・k-means clusteringの中身

import pandas as pd
from sklearn import cluster

#k-means
km = cluster.KMeans(n_clusters=2).fit(input_table_1)

output_table_1=pd.DataFrame(km.predict(input_table_1))

・Spectral Clusteringの中身

import pandas as pd
from sklearn.cluster import SpectralClustering

#spectral clustering
spc = SpectralClustering(n_clusters=2,affinity="nearest_neighbors").fit(input_table_1)
output_table_1=pd.DataFrame(spc.labels_)

・最後にクラスタで色を付けて図示した(下図)。

f:id:choron81:20211218000737p:plain

f:id:choron81:20211218002254p:plain

・なんだかそれっぽくできた気がする。

・importはこんなに何度もする必要があるのか分からない。

 

終わり。