0

Pandas と Sci-kit Learn を使用した平均シフト クラスタリングの実例があります。私はPythonが初めてなので、ここで基本的なものが欠けていると思います。ここに私の作業コードがあります:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import MeanShift
from matplotlib import style
style.use("ggplot")


filepath = "./Probes1.xlsx"
X = pd.read_excel(filepath, usecols="B:I", header=1)
df=pd.DataFrame(data=X)
np_array = df.values
print(np_array)

ms=MeanShift()
ms.fit(np_array)

labels= ms.labels_
cluster_centers = ms.cluster_centers_
print("cluster centers:")
print(cluster_centers)

labels_unique = np.unique(labels)
n_clusters_=len(labels_unique)

print("number of estimated clusters : %d" % n_clusters_)
#colors = 10*['r.','g.','b.','c.','k.','y.','m.']

for i in range(len(np_array)):
    plt.scatter(np_array[i][0], np_array[i][1], edgecolors='face' )
plt.scatter(cluster_centers[:,0],cluster_centers[:,1],c='b',
   marker = "x", s = 20, linewidths = 5, zorder = 10)
plt.show()

このコードから取得したプロットは次のとおりです。

プロット

ただし、クラスターの中心の色はそのデータ ポイントと一致しません。どんな助けでも大歓迎です。現在、中心の色を青 ('b') に設定しています。ありがとうございました!

編集:これを作成できました! 完璧な色の 2D プロット

EDIT2:

from itertools import cycle
import numpy as np
import pandas as pd
from sklearn.cluster import MeanShift
from sklearn.datasets.samples_generator import make_blobs
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


filepath = "./Probes1.xlsx"
X = pd.read_excel(filepath, usecols="B:I", header=1) #import excel data
df=pd.DataFrame(data=X) #excel to dataframe to use in ML
np_array = df.values #dataframe
print(np_array) #printing dataframe

ms = MeanShift()
ms.fit(X) #Clustering
labels=ms.labels_
cluster_centers = ms.cluster_centers_ #coordinates of cluster centers
print("cluster centers:")
print(cluster_centers)

labels_unique = np.unique(labels)
n_clusters_=len(labels_unique) #no. of clusters
print("number of estimated clusters : %d" % n_clusters_)

# ################################# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

colors=cycle('bgrkmycbgrkmycbgrkmycbgrkyc')
for k, col in zip(range(n_clusters_), colors):
    my_members= labels == k
    cluster_center = cluster_centers[k]
    ax.scatter(np_array[my_members, 0], np_array[my_members, 1], np_array[my_members, 2], col + '.')
    ax.scatter(cluster_centers[:,0], cluster_centers[:,1], cluster_centers[:,2], marker='o', s=300, linewidth=1, zorder=0)
    print(col) #prints b g r k in the respective iterations
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.grid()
plt.show()

これをプロットします: 3D プロット

再び色が一致しません。散布図の plt.plot の「markerfacecolor」に代わるものはありますか?クラスターの色をデータポイントと一致させることができますか?

編集 3: 必要な結果が得られました: Final3d-プロット

4

1 に答える 1