python
1コード
前提・実現したいこと
excelのデータを利用してクラスタリングをしているプログラミング初心者です。
複数の項目があったのでPCAで次元削減をした後クラスタリングを行い、その結果をグラフの描画を行おうと試みているのですがいろいろ試してみましたが描画されません。
基礎的なところで躓いているかもしれませんがご指摘いただけたら嬉しいです。
発生している問題・エラーメッセージ
TypeError Traceback (most recent call last) <ipython-input-22-81f51b7dc085> in <module> 2 color = ['r', 'b', 'g'] 3 for i in range(3): ----> 4 p = data1[labels == i, :] 5 plt.scatter(p[:, 0], p[:, 1], marker = markers[i], color = color[i]) 6 ~\anaconda3\envs\OpenCV_Face\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 2900 if self.columns.nlevels > 1: 2901 return self._getitem_multilevel(key) -> 2902 indexer = self.columns.get_loc(key) 2903 if is_integer(indexer): 2904 indexer = [indexer] ~\anaconda3\envs\OpenCV_Face\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2893 casted_key = self._maybe_cast_indexer(key) 2894 try: -> 2895 return self._engine.get_loc(casted_key) 2896 except KeyError as err: 2897 raise KeyError(key) from err pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() TypeError: '(array([ True, False, False, False, False, False, True, False, False, True, True, False, False, False, True, False, True, True, True, False, False, True, False, False, False, False, True, True, False, False, False, False, True, True, True, True, True, True, False, False, True, False, False, False, True, True, False, False, False, False, False, True, True, False, False, True, True, True, False, False, True, True, False, False, False, False, False, False, False, True, False, False, False, True]), slice(None, None, None))' is an invalid key
該当のソースコード
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
PCA(copy=True, n_components=None, whiten=False)
pca.fit(data1)
data1_2d = pca.transform(data1)
data1_2d = pd.DataFrame(data1_2d)
data1_2d.index = data1.index
data1_2d.columns = ['PC1','PC2']
data1_2d
ax = data1_2d.plot(kind='scatter', x='PC2', y='PC1', figsize=(16,8))
from sklearn.cluster import KMeans
kmeans_model = KMeans(n_clusters=3, random_state=10).fit(data1.iloc[:, 1:])
labels = kmeans_model.labels_
labels
array([0, 2, 2, 1, 1, 1, 0, 2, 2, 0, 0, 1, 1, 1, 0, 2, 0, 0, 0, 1, 1, 0,
2, 1, 1, 1, 0, 0, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1,
0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1,
1, 1, 1, 0, 1, 1, 1, 0])
#ちゃんとクラスターに割り振られてはいます
markers = ["+", "*", "o"]
color = ['r', 'b', 'g']
for i in range(3):
p = data1[labels == i, :]
plt.scatter(p[:, 0], p[:, 1], marker = markers[i], color = color[i])
plt.show()
#ここでエラー発生
### 試したこと 様々なサイトを参考にさせていただき、思いつく内容を複数試したのですが、描画されることはありませんでした。 ### 補足情報(FW/ツールのバージョンなど) 基礎的なところで詰まっている可能性もあると思いますのどうぞお手柔らかにご教示いただければと思います。