科学の箱

科学・IT・登山の話題

機械学習

irisを教師なし学習で分類ーGMM

投稿日:

これまでは正解ラベルがある前提、つまり教師あり学習でモデルを構築した。今回は正解ラベルがない前提でモデルを構築する。

教師なし学習としては混合ガウスモデルを利用する。

内容

  • データの読み込み、前処理
  • モデルの構築
  • プロット

データの読み込み、前処理

データの読み込み、前処理はこれまでと同様である。

import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
import numpy as np

# データセット読み込み
iris = sns.load_dataset('iris')
iris.head()

# データ前処理
X_iris = iris.drop('species', axis=1)
X_iris.head()

 

モデルの構築

混合ガウスモデルはsklearn.mixture.GaussianMixureを利用する。

from sklearn.mixture import GaussianMixture as gm 
model = gm(n_components=3,covariance_type='full')
model.fit(X_iris)
y_gmm = model.predict(X_iris)
print(y_gmm)
# [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 1 2 1 2
 2 2 2 1 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1]

 

プロット

2次元にプロットするためにはPCAで2次元にする。

from sklearn.decomposition import PCA
pca = PCA(n_components=2)     
pca.fit(X_iris)               
pca_transformed = pca.transform(X_iris)
# データマージ
iris["PCA1"] = pca_transformed[:, 0]
iris["PCA2"] = pca_transformed[:, 1]

 

さらにy_gmmもマージする。

iris["cluster"] = y_gmm

iris.head()

PCA1, 2およびクラスタがすべての一つのデータフレームに収まったのでプロットして検証する。

sns.lmplot("PCA1", "PCA2", hue='species', data=iris, fit_reg=False);
sns.lmplot("PCA1", "PCA2", hue='cluster', data=iris, fit_reg=False);

gmmはほぼ正しく分類できている。seaborn.lmplotはhueのほかにcolを利用してさらにグラフを分割することができる。

 

hue, col, row : strings
Variables that define subsets of the data, which will be drawn on separate facets in the grid. See the *_order parameters to control the order of levels of this variable.

 

sns.lmplot("PCA1", "PCA2", hue='species', col="cluster", data=iris, fit_reg=False);

メタ情報

inarticle



メタ情報

inarticle



-機械学習
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

仕事で始める機械学習 – 3.学習結果を評価しよう – 指標

主な指標 モデル構築後に確認する主な指標は4つある。 正解率 適合率 再現率 F値 正解率 $$ 正解率 = \frac{TP + TN}{TP+FP+TN+FN} $$ 正解率は全データ数に対する正 …

no image

独立性の検定 2つ

ニートの年齢別割合が1996年と2012年で関連性があるか独立性の検定をしてみる。 ニートの割合  1996 2012 15~19歳 9 9 20~24歳 12 17 25~29歳 10 18 30~ …

no image

ジニ係数(再掲)

ジニ係数について修正した。とりあえずコード。 revenue<-read.csv(file=”data.csv”, head=TRUE) revenue$TotalRevenues_n < …

no image

Mahout in Action/chap2

2.1 レコメンドには2種類ある。 collaborative filtering contents based filtering collaborative filteringではコンテンツの内容 …

no image

make_blobsで分類データを作成する

sklearnで分類学習モデルを構築する際にテストデータが必要になる。手で作成したりあらかじめ用意されたデータを使うこともできるが、make_blobsを使ってランダムデータを作成できる。 sklea …

2019年9月
« 8月   10月 »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

side bar top



アーカイブ

カテゴリー