1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

K-Meansクラスタリング

1
Last updated at Posted at 2024-08-07

まえがき

クラスタリングは、データを自動的にグループ化し、パターンを見つけるための強力な手法です。この記事では、K-Meansクラスタリングの基本概念と実装方法を具体的な例を用いて説明します。

クラスタリングの基礎

クラスタリングの目的
クラスタリングは、データを自然にグループ化し、各グループ内のデータポイントが互いに類似しているようにする手法です。

K-Meansの詳細
K-Meansクラスタリングは、データを指定した数のクラスターに分け、各クラスターの中心(セントロイド)を計算します。

実装と解説

コード例

import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

# サンプルデータの作成
data = pd.DataFrame({
    'CustomerID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'Age': [25, 45, 35, 50, 23, 40, 30, 55, 37, 42],
    'AnnualPurchases': [5000, 12000, 7000, 15000, 4500, 10000, 6000, 20000, 8000, 11000]
})

# 特徴量の選択
features = data[['Age', 'AnnualPurchases']]

# 標準化
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)

# K-meansクラスタリングの実行
kmeans = KMeans(n_clusters=3, random_state=42)
data['Cluster'] = kmeans.fit_predict(features_standardized)

print("DataFrame with Cluster Labels:")
print(data)

アウトプット

   CustomerID  Age  AnnualPurchases  Cluster
0           1   25             5000        2
1           2   45            12000        0
2           3   35             7000        2
3           4   50            15000        0
4           5   23             4500        2
5           6   40            10000        0
6           7   30             6000        2
7           8   55            20000        0
8           9   37             8000        1
9          10   42            11000        0

クラスターの解釈

各クラスターの特徴を理解するために、各クラスターの平均値を計算します。

コード例

print(data.groupby('Cluster').mean())

アウトプット

         CustomerID        Age  AnnualPurchases
Cluster                                       
0           6.333333  47.166667     14000.000000
1           9.000000  37.000000      8000.000000
2           3.250000  28.250000      5625.000000

クラスターの特徴

  • クラスター0:高年齢で年間購買額が高い顧客。
  • クラスター1:年齢が平均的で年間購買額が中程度の顧客。
  • クラスター2:若年層で年間購買額が低い顧客。

あとがき

K-Meansクラスタリングは、データを効果的にグループ化し、パターンを見つけるための強力な手法です。
クラスター分析を行った結果、特定の要因を見つけられなかった場合は、追加の特徴量を導入して再クラスター化を行うと良いでしょう。
これにより、データの洞察を深め、より正確な要因特定が可能になります。このプロセスを繰り返すことで、パフォーマンスの高い要因を特定する可能性が高まります。再クラスター化の際は、新たな特徴量を追加して、元の特徴量と組み合わせて分析を行うことをお勧めします。これにより、より詳細なパターンを発見しやすくなります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?