特徴量間の無相関化

回転行列による線形変換で、観測データの相関をなくす。
また、アヤメデータセット(iris dataset)の花びら(peatal)データに対して無相関化を行い、オリジナルデータとスコアがどう変わるかモデリングして比較する。

手順:

  1. 特徴量間のスケールが違う場合は、はじめに標準化によるスケールを揃える。
  2. 標準化後の観測データから、相関行列を求める。(標準化しない場合は。分散・共分散行列を求める)
  3. 相関行列(共分散行列)の固有ベクトルを求める。
  4. 固有ベクトルから回転行列を作成する。
  5. 回転行列により、特徴量を線形変換する。(回転行列は、固有ベクトルを並べた行列の逆行列)また、分散・行分散行列をもとめて、共分散が0になっていることを確認する。
  6. 散布図で線形変換後の分布状況を確認
  7. 線形変換前と後で分類モデルのスコアを比較 (ロジスティック回帰で比較)


線形変換の方法については以下で復習

https://www.dropbox.com/s/kyq2j8hb7ijagk4/liner_transformation.pdf?dl=0


参考サイト:

In [1]:
from sklearn.datasets import load_iris

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
/usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
  import pandas.util.testing as tm
In [0]:
# load data
data = load_iris()
In [3]:
data.keys()
Out[3]:
dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])
In [4]:
print(data.DESCR)
.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
                
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

.. topic:: References

   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...
In [5]:
# transform data to dataframe
x = pd.DataFrame(data=data.data, columns=data.feature_names)
x.head()
Out[5]:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2
In [0]:
# 従属変数の取り出し
target = data.target
In [7]:
# petal関連データ取り出し
petal_data = x[['petal length (cm)', 'petal width (cm)']].copy()
petal_data.head()
Out[7]:
petal length (cm) petal width (cm)
0 1.4 0.2
1 1.4 0.2
2 1.3 0.2
3 1.5 0.2
4 1.4 0.2
In [8]:
petal_data.corr()
Out[8]:
petal length (cm) petal width (cm)
petal length (cm) 1.000000 0.962865
petal width (cm) 0.962865 1.000000

petal length と petal width の相関が0.96あるが、その相関を0になるように線形変換する。

1. 標準化

変数間のスケールに違いがそんなに無いので、省略

2. 分散・共分散行列(または、相関行列)を求める

(標準化してあるデータの場合は、相関行列になる)

In [9]:
cov = petal_data.cov()
cov
Out[9]:
petal length (cm) petal width (cm)
petal length (cm) 3.116278 1.295609
petal width (cm) 1.295609 0.581006

3. 固有ベクトルを求める

2.で求めた共分散行列の固有ベクトルを求める

In [0]:
eigenvalue, eigenvector  = np.linalg.eig(cov)
In [11]:
eigenvector
Out[11]:
array([[ 0.92177769, -0.38771882],
       [ 0.38771882,  0.92177769]])
In [12]:
eigenvalue
Out[12]:
array([3.66123805, 0.03604607])

4. 固有ベクトルから回転行列を作成する

In [13]:
# 回転行列の作成
rotation_matrix = np.matrix(eigenvector)
rotation_matrix
Out[13]:
matrix([[ 0.92177769, -0.38771882],
        [ 0.38771882,  0.92177769]])
In [14]:
petal_data.head()
Out[14]:
petal length (cm) petal width (cm)
0 1.4 0.2
1 1.4 0.2
2 1.3 0.2
3 1.5 0.2
4 1.4 0.2

5. 回転行列により、特徴量を線形変換する

固有ベクトルにより作った行列が新しい基底となる。なので、新しい基底により線形変換するには、元のベクトルに新しい基底の逆行列をかければよい

In [15]:
np.linalg.inv(rotation_matrix)
Out[15]:
matrix([[ 0.92177769,  0.38771882],
        [-0.38771882,  0.92177769]])
In [0]:
# 線形変換関数の作成
def liner_transform(rows, rotation_matrix):
    '''
    ・rows:データフレームの1レコード
    ・rotation_matrix : 固有ベクトルを並べた行列(np.matrix)
    return : 線形変換後のベクトル(np.array)
    '''
    # データフレームをnp.array化
    vectors = rows.to_numpy()

    # 線形変換:固有ベクトルを並べた行列の逆行列×対象ベクトル
    matrix_result = np.linalg.inv(rotation_matrix).dot(vectors) # resultの中身は、np.matrix
    
    array_result = np.array(matrix_result.tolist()[0])
    
    return array_result
In [0]:
# データを線形変換する。
lt_data = petal_data.apply(liner_transform, rotation_matrix=rotation_matrix, axis=1)
In [18]:
lt_data[:10]
Out[18]:
0      [1.368032534196416, -0.3584508130554763]
1      [1.368032534196416, -0.3584508130554763]
2    [1.2758547649332217, -0.31967893079962895]
3     [1.4602103034596106, -0.3972226953113239]
4      [1.368032534196416, -0.3584508130554763]
5    [1.7221096064976944, -0.29041092129663015]
6      [1.4068044164522635, -0.266273043792282]
7     [1.4602103034596106, -0.3972226953113239]
8      [1.368032534196416, -0.3584508130554763]
9     [1.4214384212037632, -0.4894004645745183]
dtype: object
In [0]:
# dataframeに変換
lt_petal_data = pd.DataFrame(data=lt_data, columns=['lt_data'])
lt_petal_data['lt_petal_lenght'] = lt_petal_data.lt_data.apply(lambda x: x[0])
lt_petal_data['lt_petal_width'] = lt_petal_data.lt_data.apply(lambda x: x[1])
lt_petal_data.drop(columns='lt_data', inplace=True)
In [20]:
lt_petal_data.head()
Out[20]:
lt_petal_lenght lt_petal_width
0 1.368033 -0.358451
1 1.368033 -0.358451
2 1.275855 -0.319679
3 1.460210 -0.397223
4 1.368033 -0.358451
In [21]:
lt_petal_data.corr()
Out[21]:
lt_petal_lenght lt_petal_width
lt_petal_lenght 1.000000e+00 2.462441e-15
lt_petal_width 2.462441e-15 1.000000e+00

2変数間の相関が0になっている。

6. 散布図で線形変換後の分布を確認

In [0]:
# 無相関化前のpetal length と petal width の分布図描画用データ
petal_data['target'] = target
Setosa_data = petal_data[petal_data.target == 0][['petal length (cm)', 'petal width (cm)']]
Versicolour_data = petal_data[petal_data.target == 1][['petal length (cm)', 'petal width (cm)']]
Virginica_data = petal_data[petal_data.target == 2][['petal length (cm)', 'petal width (cm)']]
In [0]:
# 無相関化後のpetal length と petal width の分布図描画用データ
lt_petal_data['target'] = target
lt_Setosa_data = lt_petal_data[lt_petal_data.target == 0][['lt_petal_lenght', 'lt_petal_width']]
lt_Versicolour_data = lt_petal_data[lt_petal_data.target == 1][['lt_petal_lenght', 'lt_petal_width']]
lt_Virginica_data = lt_petal_data[lt_petal_data.target == 2][['lt_petal_lenght', 'lt_petal_width']]
In [24]:
# 散布図で分布状況を比較
fig = plt.figure(figsize=(18,5))
# 無相関化前の分布
ax1 = fig.add_subplot(1,2,1)
ax1.set_xlim(0, 8)
ax1.set_ylim(-1, 4)
ax1.set_title('plot of original data')
ax1.set_xlabel('petal length')
ax1.set_ylabel('petal width')
ax1.grid(True)
ax1.scatter(Setosa_data['petal length (cm)'], Setosa_data['petal width (cm)'], s=50, c='b',
            marker='o', label='Setosa', alpha=0.5)
ax1.scatter(Versicolour_data['petal length (cm)'], Versicolour_data['petal width (cm)'], s=50,
            c='r', marker='D', label='Versicolour', alpha=0.5)
ax1.scatter(Virginica_data['petal length (cm)'], Virginica_data['petal width (cm)'], s=50,
            c='g', marker='s', label='Virginica', alpha=0.5)
ax1.legend(loc='upper left', fontsize=14)

# 無相関化後の分布
ax2 = fig.add_subplot(1,2,2)
ax2.set_xlim(0, 8)
ax2.set_ylim(-2, 3)
ax2.set_title('plot of liner transformed data')
ax2.set_xlabel('petal length')
ax2.set_ylabel('petal width')
ax2.grid(True)
ax2.scatter(lt_Setosa_data.lt_petal_lenght, lt_Setosa_data.lt_petal_width, s=50, c='b',
            marker='o', label='Setosa', alpha=0.5)
ax2.scatter(lt_Versicolour_data.lt_petal_lenght, lt_Versicolour_data.lt_petal_width, s=50,
            c='r', marker='D', label='Versicolour', alpha=0.5)
ax2.scatter(lt_Virginica_data.lt_petal_lenght, lt_Virginica_data.lt_petal_width, s=50,
            c='g', marker='s', label='Virginica', alpha=0.5)
ax2.legend(loc='upper left', fontsize=14)
plt.show()

右側のグラフを見ると、2変数間の相関が無くなっているのがわかる。

7. 線形変換前と後で分類モデルのスコアを比較

無相関化前と後のpetal_lengthとpetal_widthのデータからロジスティック回帰で多クラス分類を行い、スコアを比較する

7-1 無相関化前のデータでモデリング

In [0]:
x_train, x_test ,y_train, y_test = train_test_split(petal_data[['petal length (cm)', 'petal width (cm)']],
                                                    petal_data['target'],
                                                    test_size=0.4,
                                                    random_state=0,
                                                    stratify=petal_data['target'])
In [56]:
logreg = LogisticRegression()
logreg.fit(x_train, y_train)
Out[56]:
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
                   intercept_scaling=1, l1_ratio=None, max_iter=100,
                   multi_class='auto', n_jobs=None, penalty='l2',
                   random_state=None, solver='lbfgs', tol=0.0001, verbose=0,
                   warm_start=False)
In [57]:
y_pred = logreg.predict(x_test)

print(metrics.accuracy_score(y_test, y_pred))
0.9833333333333333

7-2 無相関化後のデータでモデリング

In [0]:
x_train, x_test ,y_train, y_test = train_test_split(lt_petal_data[['lt_petal_lenght', 'lt_petal_width']],
                                                    lt_petal_data['target'],
                                                    test_size=0.4,
                                                    random_state=0,
                                                    stratify=lt_petal_data['target'])
In [59]:
logreg = LogisticRegression()
logreg.fit(x_train, y_train)
Out[59]:
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
                   intercept_scaling=1, l1_ratio=None, max_iter=100,
                   multi_class='auto', n_jobs=None, penalty='l2',
                   random_state=None, solver='lbfgs', tol=0.0001, verbose=0,
                   warm_start=False)
In [60]:
y_pred = logreg.predict(x_test)

print(metrics.accuracy_score(y_test, y_pred))
0.9833333333333333

スコアは同じだった。住宅価格の予想問題で相関が高い変数が多かったので、そこで使って結果を比較してみる。

In [0]: