GUEST0 pt
クイズ・バイオインフォの森
8. 次元削減

8. 次元削減

目次

1. 乱数の固定

Text
# library
import pandas as pd
import numpy as np
import pickle


# 乱数の固定
import random
import numpy as np
def fix_seeds(seed=0):
    random.seed(seed)
    np.random.seed(seed)


fix_seeds(42)

2. PCA

Text
# libraries
from sklearn.decomposition import PCA


maxv = df.replace([np.inf], 0).max().max()
df = df.replace([np.inf], maxv + 1).replace([-np.inf, np.nan], 0)


pca = PCA()
pca.fit(df)
data = pd.DataFrame(pca.transform(df))
data.index = df.index
data.columns = [f'col_{i}' for i in range(len(data.T))]

3. tSNE

4. MDS

5. UMAP

Text
# libraries
from umap.umap_ import UMAP


maxv = df.replace([np.inf], 0).max().max()
df = df.replace([np.inf], maxv + 1).replace([-np.inf, np.nan], 0)


data = pd.DataFrame(UMAP().fit_transform(df))
data.index = df.index
data.columns = [f'col_{i}' for i in range(len(data.T))]

6. まとめ

Text
# library
import pandas as pd
import numpy as np
import pickle
from sklearn.decomposition import PCA
from umap.umap_ import UMAP


# 乱数の固定
import random
import numpy as np
def fix_seeds(seed=0):
    random.seed(seed)
    np.random.seed(seed)


fix_seeds(42)


# 次元削減の関数
def decompsition(df, method): # index = 化合物, column = Pathway
  	# infとnanに対する前処理
    maxv = df.replace([np.inf], 0).max().max()
    df = df.replace([np.inf], maxv + 1).replace([-np.inf, np.nan], 0)


    if method == 'PCA':
        pca = PCA()
        pca.fit(df)
        data = pd.DataFrame(pca.transform(df))
        data.index = df.index
        data.columns = [f'col_{i}' for i in range(len(data.T))]
    elif method == 'UMAP':
        # data = pd.DataFrame(umap.UMAP().fit_transform(df))
        data = pd.DataFrame(UMAP().fit_transform(df))
        data.index = df.index
        data.columns = [f'col_{i}' for i in range(len(data.T))]
    else:
        return None


    return data


# 結果の保存先のディレクトリ名に用いるタイムスタンプ出力関数
def now():
    return str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S'))


# 結果を保存する関数
def pickle_save(path, data):
    with open(f'{path}', 'wb') as tf:
        pickle.dump(data, tf)


# 実行例
# PCA
res_pca = decompsition(df_score, 'PCA')
pickle_save(f"{TEMP_DIR}/decomposition/{no}/PCA.pkl", res_pca)


# UMAP
res_umap = decompsition(df_score, 'UMAP')
pickle_save(f"{TEMP_DIR}/decomposition/{no}/UMAP.pkl", res_umap)

7. 可視化

7.1. matplotlib

7.2. bokeh

Text
# bokeh libraries
from bokeh.plotting import output_notebook, figure, show
from bokeh.io import save


output_notebook()


# 可視化の関数
def plot_decomposition(res_decomposition, title, path=None, no=None, output='html'):
    # dataset definition
    df = res_decomposition.iloc[:, :2]
    df['index'] = df.index


    # hover definition
    tooltips=[
        ('name', '@index')
    ]


    # Plot
    p = figure(
        width = 750, height = 600, title=f'{title}',
        x_axis_label = 'Axis 1', y_axis_label = 'Axis 2', tooltips=tooltips
    )
    p.scatter(
        x = 'col_0', y = 'col_1',
        source = df,
        color = 'blue',
        size = 8, alpha = 0.2
    )


    # output
    if output == 'html':
        os.makedirs(f'{path}', exist_ok=True)
        save(p, filename=f'{path}/decompsition_{title}.html')
    elif output == 'notebook':
        show(p)
    else:
      pass

実行例 (PCA)

Text
no = now()
plot_decomposition(res_pca, 'PCA', no, 'notebook')

実行例 (UMAP)

Text
no = now()
plot_decomposition(res_pca, 'PCA', no, 'notebook')

広告を取得中...
8. 次元削減 | バイオインフォの森