Pythonでグラフを表示
上記記事で整えたMac & Python3環境でグラフ表示を可能とするために matplotlib をインストール。
(data_analysis) $ pip install matplotlib
乱数配列をヒストグラム化するプログラムを作成。
import pandas as pd import numpy as np import matplotlib.pyplot as plt # ヒストグラムのY軸を正規化(確率)して表示させる関数 def show_normed_hist(data, title, xlabel, ylabel, bins): plt.hist(data, normed=True, bins=bins) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.show() r = np.random.randn(1000,5) df = pd.DataFrame(r, columns=list('ABCDE')) print(df.describe()) show_normed_hist(r, 'Histgram', 'n', 'prob', 50)
下記のコマンドでプログラムを実行。
(data_analysis) $ python test.py & [1] 40776
グラフ表示を終了させるまでシェルの制御が戻ってこなくなるため、"&“ を付けてバックグラウンド実行とする。
ヒストグラムの表示結果。2次元配列を渡しても matplotlib 側で制御してくれる。
scikit-learn のインストール
続いて機械学習ライブラリの scikit-learn をインストールする。普通にPIPインストールすると失敗するので調べたら、SciPy が必須とのこと。
Python (>= 2.6 or >= 3.3),
NumPy (>= 1.6.1),
SciPy (>= 0.9).
Installing scikit-learn — scikit-learn 0.18.1 documentation
先に SciPy をインストールしてから scikit-learnをインストール。scikit-learnは途中でコンパイルが必要となるため、sudoで実行する。
(data_analysis) $ pip install scipy (data_analysis) $ sudo pip install scikit-learn
scikit-learn でクラスタリング
乱数配列を Kmeans法でクラスタリングするプログラムを作成。
import pandas as pd import numpy as np from sklearn.cluster import KMeans # Kmeans 表示 def show_kmeans(data): # Kmeas kmeans_model = KMeans(n_clusters=3, random_state=10).fit(data) # クラスタラベルを結合 df = pd.concat([pd.DataFrame(kmeans_model.labels_, columns=['Label']), data], axis=1) print(df) r = np.random.randn(10,5) df = pd.DataFrame(r, columns=list('ABCDE')) show_kmeans(df)
前回インストールした pandas で配列同士を結合すると便利。
(data_analysis) $ python test.py Label A B C D E 0 0 0.462018 1.573145 1.356272 2.077497 -0.442880 1 0 0.105133 0.314921 1.316209 1.887002 1.163974 2 1 -1.092522 1.290340 1.187348 -1.262344 0.037429 3 0 0.733690 -0.245179 0.304962 0.459715 1.306258 4 0 0.570241 -0.238423 0.353163 0.241814 0.874983 5 1 -0.420605 -0.783803 0.036591 -1.197135 -0.534035 6 1 -0.691496 0.767393 -0.682319 -1.080912 0.580725 7 2 2.951777 0.570069 -0.311573 -0.072250 -1.133658 8 0 0.932389 0.179889 0.166576 0.873454 -0.396965 9 0 0.156743 -0.671090 1.227245 -0.024907 0.041011
結果を表示。なんとなく特徴のある行ごとにクラスタリングできたっぽい。

- 作者: 株式会社システム計画研究所
- 出版社/メーカー: オーム社
- 発売日: 2016/12/01
- メディア: 単行本(ソフトカバー)
- この商品を含むブログ (1件) を見る