2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

scikit-learnを使用した主成分分析(PCA)

Last updated at Posted at 2019-10-27

#はじめに
こんな方にオススメ。
・説明変数の特徴量大小を把握したい
・前処理でデータの次元削減対象を知りたい
・すぐ動かせるサンプルースが知りたい

#ソース

import numpy as np
import pandas as pd
import urllib.request 
import matplotlib.pyplot as plt
%matplotlib inline
import sklearn
from sklearn.decomposition import PCA #主成分分析器
from sklearn.datasets import load_iris

# データセット読み込み
iris = load_iris()
df=pd.DataFrame(iris.data, columns=iris.feature_names)
# アヤメの種類を列末に追加(3種類)
df["CLASS"]=iris.target
df.head()

image.png

# 説明変数の組み合わせとアヤメの種類をプロット
from pandas import plotting 
plotting.scatter_matrix(df.iloc[:, 0:4], figsize=(8, 8), c=list(df.iloc[:, 4]), alpha=0.5)
plt.show()

image.png

# 行列の標準化
dfs = df.iloc[:, 0:4].apply(lambda x: (x-x.mean())/x.std(), axis=0)
dfs.head()

image.png

#主成分分析
pca = PCA()
pca.fit(dfs)
feature = pca.transform(dfs)

# 標準化後のプロット
from pandas import plotting 
plotting.scatter_matrix(pd.DataFrame(feature, 
                        columns=dfs.columns), 
                        figsize=(8, 8), c=list(df.iloc[:, 4]), alpha=0.5) 
plt.show()

image.png

# 寄与率算出
f_df = pd.DataFrame(pca.explained_variance_ratio_, index=dfs.columns)
f_df.columns=["Feature"]
# アヤメの種類は、第二主成分までで約95%の情報を説明できる
# よって、第三、第四主成分は削減しても影響は小さいと言える
f_df

image.png

# 円グラフ表示
plt.pie(f_df, labels=f_df.index, autopct="%1.1f%%", startangle=90, counterclock=False)
plt.legend()
plt.show()

image.png

# 第一主成分と第二主成分でプロット
plt.figure(figsize=(6, 6))
plt.scatter(feature[:, 0], feature[:, 1], alpha=0.8, c=list(df.iloc[:, 4]))
plt.grid()
plt.xlabel("sepal length (cm)")
plt.ylabel("sepal width (cm)")
plt.show()

参照

2
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?