私はwekaに道があると仮定していますが、私はwekaライブラリを一度も使用しませんでした。 sklearn k-meansを使用する場合は、非常に使いやすいです。
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
# create a dataset
ds = np.random.random((50, 2))
ds_anomaly = np.asarray([[-1,1], [1,-1]])
ds = np.concatenate((ds,ds_anomaly))
関数kmeansが呼び出されたフィットたら、クラスタ中心(この場合は2)がkmeans.cluster_centers_から取得することができます。また、データセットに割り当てられたラベルはkmeans.labels_から取得できます。
kmeans = KMeans(n_clusters=2)
kmeans.fit(ds)
# appropriate cluster labels of points in ds
data_labels = kmeans.labels_
# coordinates of cluster centers
cluster_centers = kmeans.cluster_centers_
colors = ['b', 'g']
plt.scatter(ds[:, 0], ds[:, 1],
c=[colors[i] for i in data_labels], s=1)
plt.scatter(cluster_centers[:, 0], cluster_centers[:, 1], color = "k")
plt.show()
結果をプロットして、自分で異常を見つけることができます。 ![enter image description here](https://i.stack.imgur.com/rehYg.png)
また、何らかのデータ分析を行い、異常を取得することもできます。次に、np.percentileを使用してさまざまな値を見つける非常に基本的な例を示します。異常な機能(良い結果が必要な場合)をより複雑な機能に変更することができます。
def anomalies(data):
perc = np.percentile(data, 99)
return data[np.where(data>perc)[0]]
for idx, c in enumerate(kmeans.cluster_centers_):
c_anomaly = anomalies(ds[np.where(kmeans.labels_==idx)])
print(c_anomaly)
plt.scatter(c_anomaly[:, 0], c_anomaly[:, 1], c="r", marker="o")
plt.show()
期待通りの結果が([[-1, 1], [1, -1]])
値です。 ![enter image description here](https://i.stack.imgur.com/ZsmBk.png)
免責事項:初期設定によっては、お使いのクラスタ中心は、あなたの異常近くendupことがあります。私は別のアルゴリズムで異常検出を実行するか、またはk値とクラスタ初期化パターンを選択するときに注意することをお勧めします。
こんにちは、ようこそ!あなたの質問を改善し、話題外として解雇されるのを避けるために[質問する](https://stackoverflow.com/help/how-to-ask)をご覧ください。 – rll