Download - R -> Python

Transcript
Page 1: R -> Python

R -> Python

Mishima.syk #3

Page 2: R -> Python

自己紹介

• kzfm (@fmkz___)– blog.kzfmix.com– Shizuoka.py

• とある製薬企業の研究員• 日本酒と drum’n’bass 好き

• Python 歴は 6 年くらい– (その前は Perl )

• よく使うのは Flask, Pandas

Page 3: R -> Python

R 使ってますよね?

Page 4: R -> Python

Rstudio とか

アメリカの各州での1990-2010 年におけるUFO 目撃頻度を視覚化する

Page 5: R -> Python

ggplot2 とか

g + geom_point() + facet_wrap(~Species) + geom_smooth(method='lm')

Page 6: R -> Python

R さいこう♡

Page 7: R -> Python

Python も♡

Page 8: R -> Python

今日は R でやっていることをPython でやれるようにする

ツールを紹介します

• Pandas – (DataFrame)

• ggplot – (ggplot の Python 実装 )

• scikit-learn – (python の機械学習ライブラリ )

Page 9: R -> Python

Pandas

http://pandas.pydata.org/

Page 10: R -> Python

Pandas とは何か?

• R でいうところのデータフレームやベクトルに相当するものを提供するライブラリ

• よく分からなければ以下を参考にしてみてください– http://www.slideshare.net/KazufumiOhka

wa/12-20049278

Page 11: R -> Python

Series( ベクトル )>>> a = pd.Series(range(5), index=list(“abcde”)) # 0..5のリストに a..eのインデックス>>> a[list(“ace”)] #indexアクセスa 0c 2e 4dtype: int64>>> a[[0,2,4]] # 0,2,4番目の要素a 0c 2e 4dtype: int64>>> a[(a<1)|(a>3)]  #1より小さい、または 3より大きい要素a 0e 4dtype: int64

Page 12: R -> Python

DataFrame を作成

>>> pd.DataFrame([[1,2,3],[4,5,6]]) 0 1 20 1 2 31 4 5 6

Page 13: R -> Python

DataFrame に列名、行名を追加

>>> x.index = list("ab")>>> x.columns = list("cde")>>> x c d ea 1 2 3b 4 5 6

Page 14: R -> Python

DataFrame の列にアクセス

>>> x["c"]a 1b 4Name: c, dtype: int64>>> x.ca 1b 4Name: c, dtype: int64

Page 15: R -> Python

メソッドを呼ぶ

>>> x.c.mean() # (1+4) / 22.5>>> x.c.sum() # 1+45

Page 16: R -> Python

データフレームの結合

>>> x 0 10 1 01 -2 3

>>> pd.concat([x, x], axis=0) # rbind 0 10 1 01 -2 30 1 01 -2 3

>>> pd.concat([x, x], axis=1) # cbind 0 1 0 10 1 0 1 01 -2 3 -2 3

Page 17: R -> Python

逆引きを Pandas で

• R と大体似たような感じでかけました

– http://blog.kzfmix.com/entry/1387969720

– http://blog.kzfmix.com/entry/1388051876

– http://blog.kzfmix.com/entry/1388138505

Page 18: R -> Python

ggplot

ggplot の python 実装

Page 19: R -> Python

( 前提 )ggplot2 とは

• 良い感じのグラフを手軽にかけるライブラリ

• オブジェクト指向っぽくグラフを作る• Photoshop のレイヤーを重ねるようにグ

ラフを作成していく• ggplot2 のために R を使うとかありがち–私とか

Page 20: R -> Python

( 例 )IRIS

Page 21: R -> Python

散布図

g <- ggplot(data=iris, aes_string(x='Sepal.Length', y='Sepal.Width', color='Petal.Length'))g + geom_point()

Page 22: R -> Python

種毎に分ける

g + geom_point() + facet_wrap(~Species)

Page 23: R -> Python

ラベルを変更

g + geom_point() + facet_wrap(~Species) + xlab("Length") + ylab("Width")

Page 24: R -> Python

線形回帰

g + geom_point() + facet_wrap(~Species) + geom_smooth(method='lm')

Page 25: R -> Python

python でもやりたい

• http://ggplot.yhathq.com/

• すごい!えらい!素敵♡

Page 26: R -> Python

python-ggplot の良いところ

• 画像生成処理をバッチで流せる– R だとちょっと面倒くさい

• API も R 版 ggplot2 と同一のものを提供することを目指しているので R 版 ggplot2 の本が参考になる

• 開発中なので色々不足しているところはあるけどほぼ満足している

Page 27: R -> Python

早速何かやってみます

• Spleen tyrosine kinase (SYK) の阻害活性データから分子量と ALogP のプロットをする

• ChEMBL のデータを利用します

Page 28: R -> Python

データ作成

• pychembldb を使います• 出力を syk.csv として保存– ChEMBL 便利☆

from pychembldb import *

#Inhibition of recombinant Syk#Bioorg. Med. Chem. Lett. (2009) 19:1944-1949assay = chembldb.query(Assay).filter_by(chembl_id="CHEMBL1022010").one()print '"ID","IC50","ALOGP","MWT"'

for act in assay.activities: if act.standard_relation == "=": print '"{}",{},{},{}'.format(act.compound.molecule.chembl_id, act.standard_value, act.compound.molecule.property.alogp, act.compound.molecule.property.mw_freebase)

Page 29: R -> Python

データはこんな感じ

ID IC50 ALOGP MWT pIC500 CHEMBL475575 4.0 1.99 426.47 8.3979401 CHEMBL162 3.0 3.82 466.53 8.5228792 CHEMBL473229 9.0 3.52 397.49 8.0457573 CHEMBL475250 30.0 2.38 401.41 7.5228794 CHEMBL475251 41.0 3.88 470.45 7.3872165 CHEMBL515756 50.0 3.21 339.43 7.3010306 CHEMBL105427 60.0 1.23 454.50 7.2218497 CHEMBL30873 90.0 3.59 320.43 7.0457578 CHEMBL474361 230.0 1.13 286.33 6.6382729 CHEMBL515271 300.0 3.93 312.30 6.52287910 CHEMBL474362 310.0 3.08 335.45 6.50863811 CHEMBL443514 500.0 2.69 270.31 6.30103012 CHEMBL105740 940.0 3.32 439.53 6.02687213 CHEMBL470716 2000.0 3.84 304.37 5.69897014 CHEMBL470717 3800.0 3.23 299.28 5.420216

Page 30: R -> Python

pandas で読み込んで ggplot で描画

import pandas as pdfrom ggplot import *import numpy as np

d = pd.read_csv("syk.csv")d["pIC50"] = 9 - np.log10(d["IC50"])

p = ggplot(aes(x='MWT', y='ALOGP', color="pIC50", size="pIC50"), data=d) + geom_point()#print pggsave("2dplot.png", p)

Page 31: R -> Python

出来ました☆

Page 32: R -> Python

ヒストグラムもp = ggplot(aes(x="pIC50"), data=d) + geom_histogram()ggsave("hist.png", p)

Page 33: R -> Python

( おまけ ) 時系列データ

p = ggplot(aes(x='Date', y='nw'), data=d) + \ geom_point(color='lightblue') + \ stat_smooth(span=.15, color='black', se=True) + \ ggtitle("Simple Diet") + \ xlab("Date") + \ ylab("Weight")

Page 34: R -> Python

視覚化は ggplot で OK

続いて機械学習

Page 35: R -> Python

Scikit-learn

機械学習♡

Page 36: R -> Python

色々出来る

Page 37: R -> Python

今日使うもの

• PCA• RandamForest• 交差検定 <- 便利 !

Page 38: R -> Python

今回は RDKit との連携例

• pychembldb でデータを取ってきて• RDKit でフィンガープリントを出して• Scikit-learn で–クラスタリング• PCA でケミストリースペースの把握

–予測モデル作成• RandamForest

Page 39: R -> Python

pychembldb

from pychembldb import *

#Inhibition of recombinant Syk#Bioorg. Med. Chem. Lett. (2009) 19:1944-1949assay = chembldb.query(Assay).filter_by(chembl_id="CHEMBL1022010").one()

for act in assay.activities: if act.standard_relation == "=": print act.compound.molecule.structure.molfile, "\n$$$$"

先に使った SYK のデータからsdf を作っておく

Page 40: R -> Python

ケミストリースペースの把握

Page 41: R -> Python

PCAfrom rdkit import Chemfrom rdkit.Chem import AllChem, DataStructsfrom sklearn.decomposition import PCAfrom ggplot import *import numpy as npimport pandas as pd

suppl = Chem.SDMolSupplier('syk.sdf')

fps = []for mol in suppl: fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2) arr = np.zeros((1,)) DataStructs.ConvertToNumpyArray(fp, arr) fps.append(arr)

Morgan フィンガープリントを作ってScikit-learn で扱えるように

NumpyArray に変換

Page 42: R -> Python

PCApca = PCA(n_components=2)pca.fit(fps)v = pca.components_d = pd.DataFrame(v).Td.columns = ["PCA1", "PCA2"]g = ggplot(aes(x="PCA1", y="PCA2"), data=d) + geom_point(color="lightblue") + xlab("PCA1") + ylab("PCA2")ggsave("pca.png", g)

PCA で第二主成分まで計算して、X に第一、 Y に第二主成分をプロット

Page 43: R -> Python

結果

Page 44: R -> Python

予測モデル

Page 45: R -> Python

RandamForestfrom rdkit import Chemfrom rdkit.Chem import AllChem, DataStructsfrom sklearn import cross_validationfrom sklearn.ensemble import RandomForestClassifierimport numpy as npimport pandas as pd

d = pd.read_csv("syk.csv")d["pIC50"] = 9 - np.log10(d["IC50"])d["ACT"] = d.pIC50.apply(lambda x: 1 if x > 8 else 0)

先に使った SYK のデータ pIC50 をもとめて8 オーダーより強いものを活性ありとした

(0: 活性あり、 1: 活性なし )

Page 46: R -> Python

RandamForestsuppl = Chem.SDMolSupplier('syk.sdf')

fps = []for mol in suppl: fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2) arr = np.zeros((1,)) DataStructs.ConvertToNumpyArray(fp, arr) fps.append(arr)

RDKit で sdf を読み込み MorganFingerprintを計算し、それを Scikit-learn で使えるように

NumpyArray に変換

Page 47: R -> Python

RandamForestx_train, x_test, y_train, y_test = cross_validation.train_test_split(fps, d, test_size=0.4, random_state=0)

print x_train.shape, y_train.shapeprint x_test.shape, y_test.shaperf = RandomForestClassifier(n_estimators=100, random_state=1123)

rf.fit(x_train, y_train[:,5])

print "predict\n", rf.predict(x_test)print "\nresult\n", y_test[:,5]#print y_test[:,[0,5]]

データを訓練、テストセットにわけ、RandamForest でモデルをつくり

テスト

Page 48: R -> Python

Resultpredict[0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]result[0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

Page 49: R -> Python

Python で機械学習するのもオススメです!


Top Related