科学の箱

科学・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

kaggle Titanic Tutorial – 3

DecitionTreeのパラメータを調整する。 まずはMaxDepthから from sklearn.model_selection import LeaveOneOut from sklearn. …

no image

Mahout in Action/chap2

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

no image

SIGNATE お弁当の需要予測-2

データの内容を確認する。 期間を調べる d_train[‘datetime’].min() ‘ ‘2013-11-18’ d_train[‘datetime’].max() ‘ ‘2014-9-9’ …

no image

ジニ係数(再掲)

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

no image

線形回帰とリッジ回帰とラッソ回帰の違い

用語 線形回帰 データから平均二乗誤差を最低にするパラメータΘを求めて、直線で回帰すること $$ y = Θ_0 + Θ_1 \times x $$ コスト関数 損失関数とも呼ばれる。実際のデータと予 …

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

side bar top



アーカイブ

カテゴリー