【第7回】pythonデータ分析100本ノックをやってみた (ノック31-35)
Python実戦データ分析100本ノックを、データサイエンス初心者の私と一緒にやっていきませんか?
今回は第7回、ノック31〜ノック35までをやっていきたいと思います。
Python実戦データ分析100本ノックは、pandas の使い方やデータサイエンスを実戦的に学べる書籍なのでぜひ手に取ってみてください
↓Python実践データ分析100本ノック
レビューでも実用的と高評価ですね。
リンク
この章の目的は、顧客をクラス分けして、顧客毎の利用回数を予測する事です。
いよいよ本格的な機械学習の章に入っていくようです。
import pandas as pd
uselog = pd.read_csv(‘use_log.csv’)
uselog.isnull().sum()
まず、今まで通りの方法で、use_log のcsvファイルを読み込みましょう。
次にcustomer_join も同様に読み込んだあと、欠損値の確認をしましょう
customer = pd.read_csv(‘customer_join.csv’)customer.isnull().sum()
クラスター化とは、ある特徴量に基づいていくつかの集団にクラス分けする事です。
customer_clustering = customer[[“mean”, “median”,”max”, “min”, “membership_period”]]
customer_clustering.head()
まず、機械学習ライブラリである sikit-learn をインポートした後、K-means法を用いてグルーピングしていきます。k-means法は変数間の距離を基準にグループ化する為、各変数のスケールを合わせる標準化が必要になります。
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
customer_clustering_sc = sc.fit_transform(customer_clustering)
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()
print(customer_clustering[“cluster”].unique()) を見ると、
1,2,3,0 と出ます。これはクラスター0~3 の4つにグループ化出来ているという事です。
まず、分析結果を見やすくする為、1行目で列の名前を変えていきます。
2行目で、クラスター毎にデータ件数の集計を行います。
customer_clustering.columns = [“月内平均値”,”月内中央値”, “月内最大値”, “月内最小値”,”会員期間”, “cluster”]
customer_clustering.groupby(“cluster”).count()
データ件数はcluster3が一番多いようです。
次は会員期間の平均を表に表示しましょう。
customer_clustering.groupby(“cluster”).mean()
次はPCA(主成分分析)を使って次元を減らし、2次元平面に可視化しましょう。
n_components=2 とは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”]
次に matplotlib で可視化しましょう。
for 文で、クラスター毎に繰り返して、描写します。
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])
かなり難しいですが、写経でも良いので続けましょう。
まず、データの結合(concat) を行います。その後、クラスター毎に is_deleted
つまり、在籍or退会会員数を並べてみます。
customer_clustering = pd.concat([customer_clustering, customer], axis=1)
customer_clustering.groupby([“cluster”,”is_deleted”],as_index=False).count()[[“cluster”,”is_deleted”,”customer_id”]] customer_clustering.groupby([“cluster”,”routine_flg”],as_index=False).count()[[“cluster”,”routine_flg”,”customer_id”]]
最後に、クラスター毎にroutine-flag つまり、週4回以上来ている人の数を並べて表示しましょう。グループ1,2 は flagあり、つまり継続会員が多い事がわかります。
ここまでで、3章の前半は終わりです。次回は【第8回】3章の後半ノック36-40 へいってみましょう。
このシリーズも中盤から終盤にさしかかってきています。最後まで付いてきてください!
リンク
この記事を書いた人
元薬局薬剤師。今は一般会社で働き、副業ライター(月5-6桁)しつつ自由に暮らす30代男性。英語学習(TOEIC920点)やライティング、マーケティング、メンタル術など、社会で必要とされつつ、個人で稼げるために必要なスキルを磨いて、その様子を発信しています。
詳しい自己紹介は(https://iroirotantan.com/ryoutaro/)で
コメント