LoginSignup
1
3

More than 5 years have passed since last update.

【ざっくり】KMeansによるクラスタリング

Posted at

概要

  • 目的:購買履歴などから顧客をクラスタリングして、それぞれの特徴を把握
  • 方法:KMeansによるクラスタリング
  • アウトプット:各クラスタの人数、顧客クラスタ毎の特徴
  • 利用分野:マーケティング

アプローチ

  1. データをdataframeに格納
  2. クラスタ数の決定
  3. KMeansでクラスタリング
  4. クラスタリング結果を出力

コード

import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from collections import Counter

##dataframeを準備 df ###

num_clus = 4 #クラスタ数を設定
kmeans = KMeans(n_clusters=num_clus, random_state=0).fit(df)

print(Counter(kmeans.labels_)) #各クラスタの人数を出力

df['cluster_id']=kmeans.labels_ #元のdataframeにクラスタ番号を追加

for i in range(0,num_clus): #各クラスタの平均値を出力
    print(df[df['cluster_id']==i].mean())

1
3
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
3