実践データ分析100本ノック(第4章-顧客の行動を予測する-31~34)

2020年11月25日

参考:
  ・fit, transform, fit_transformについて
    fit、transform、fit_transformの意味を、正規化の例で解説
  ・標準化について
    統計で頻出する標準化とは?【意味や使用場面について詳しく解説!】
  ・scikit-learnの使い方について
    scikit-learnの4つの関数で機械学習などのデータを前処理する
  ・scikit-learn引数について
    データ分析がしたい
  ・sckikt-learn主成分分析について
    Pythonで主成分分析(PCA)を行う方法を現役エンジニアが解説【初心者向け】

cscikit-learnインストール

機械学習用のライブラリscikit-learnをインストールします。


pip3 install scikit-learn

コード


# %%
import pandas as pd

#--ノック31------------------------------
# %%
# CSV読み込み
uselog = pd.read_csv('./samples/3/use_log.csv')
# 欠損値確認
uselog.isnull().sum()
# log_id         0
# customer_id    0
# usedate        0
# dtype: int64
# %%
# CSV読み込み
customer = pd.read_csv('./samples/3/customer_join.csv')
# 欠損値確認
customer.isnull().sum()
# customer_id             0
# name                    0
# class                   0
# gender                  0
# start_date              0
# end_date             2842
# campaign_id             0
# is_deleted              0
# class_name              0
# price                   0
# campaign_name           0
# mean                    0
# median                  0
# max                     0
# min                     0
# routine_flg             0
# calc_date               0
# membership_period       0
# dtype: int64

#--ノック32------------------------------
# %%
customer_clustering = customer[["mean", "median", "max", "min", "membership_period"]]
print(customer_clustering.head())
#        mean  median  max  min  membership_period
# 0  4.833333     5.0    8    2                 47
# 1  5.083333     5.0    7    3                 47
# 2  4.583333     5.0    6    3                 47
# 3  4.833333     4.5    7    2                 47
# 4  3.916667     4.0    6    1                 47

# %%
# インポート
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# 標準化
sc = StandardScaler()
customer_clustering_sc = sc.fit_transform(customer_clustering)
# モデル構築
# 4つのクラスに分ける, 乱数指定
kmeans = KMeans(n_clusters=4, random_state=0)
# 実行
clusters = kmeans.fit(customer_clustering_sc)
# 代入
customer_clustering["cluster"] = clusters.labels_
print(customer_clustering["cluster"].unique())
customer_clustering.head()

#--ノック33------------------------------
# %%
# カラム名を変更
customer_clustering.columns = ["月内平均値", "月内中央値", "月内最大値", "月内最小値", "会員期間", "cluster"]
# グループごとの件数を確認
customer_clustering.groupby("cluster").count()
#       	月内平均値	月内中央値	月内最大値	月内最小値	会員期間
# cluster					
# 0      	761     	761      	 761    	 761	     761
# 1	        846      	846      	 846    	 846     	 846
# 2	        1249    	1249     	 1249	     1249	     1249
# 3	        1336    	1336	     1336	     1336	     1336

# グループごとの平均を確認
customer_clustering.groupby("cluster").mean()
# 	            月内平均値  月内中央値 月内最大値   月内最小値    会員期間
# cluster					
# 0	       3.051243	 2.885677	 4.750329	 1.653088	 9.269382
# 1	       8.054608	 8.039598	 10.009456	 6.160757	 7.072104
# 2	       4.677494	 4.671337	 7.232986	 2.153723	 36.915933
# 3	       5.522518	 5.373129	 8.743263	 2.686377	 14.831587

#--ノック34------------------------------
# 次元削除を行う(5つの変数で表現していたものを2次元で行う)
# %%
# 主成分分析ライブラリをインポート
from sklearn.decomposition import PCA
# データを定義
X = customer_clustering_sc
# 次元数を指定
pca = PCA(n_components=2)
# 主成分分析の実施
pca.fit(X)
# 主成分分析の結果を説明変数に適用
x_pca = pca.transform(X)
# データフレーム化
pca_df = pd.DataFrame(x_pca)
pca_df["cluster"] = customer_clustering["cluster"]

# 描画
import matplotlib.pyplot as plt
%matplotlib inline
for i in customer_clustering["cluster"].unique():
    tmp = pca_df.loc[pca_df["cluster"]==i]
    plt.scatter(tmp[0], tmp[1])

参考動画

【主成分分析】

【k-means】

関連のある書籍

YouTube

2020年11月25日