離婚後の日記

離婚した。

6章 アルゴリズムチェーンとパイプライン

間が空いてしまって色々忘れる。

継続しなければならない。

 

6章

f:id:jahjha:20190504162736j:plain

前処理を検証用テストデータにも適用してしまうと過度な汎化が起きる。(?

例えばMinMaxを全データにかけてしまうと、汎化能力が上がる(場合もある)が

実際にはテストデータは未知なものであり、訓練データの最小最大を越えることだってあり得る。

その意味で前処理は訓練データのみに適用し.fitしなければならない。

 

・Pipeline

便利。今までやってきたことはこれで省略化できる。

from sklearn.pipeline import Pipeline

pipe=Pipeline([("scaler",MinMaxScaler()),("svm",SVC())])

"scaler"のインスタンス、"svm"のインスタンスを作成し順次処理していく。

このインスタンスは2つに限られるわけではない。

(6.4汎用パイプラインインターフェイスに詳しいがよくわからん。たぶん意味はあってる)

・make_pipeline

インスタンスに名前をつけるのが面倒なのでこれもイケる。

from sklearn.pipeline import make_pipeline
pipe_long =Pipeline([("scaler",MinMaxScaler()),("svm",SVC(C=100))])
pipe_short=make_pipeline(MinMaxScaler(),SVC(C=100))

#pipe_longとpipe_shortは全く同じ動作を行う。make_pipeline作成時、各インスタンスは全小文字に自動命名される。

 

6.5グリッドサーチ

以下例でグリッドサーチできる。

pipe=make_pipeline(StandardScaler(),PolynomialFeatures(),Ridge())

param_grid={"polynomialfeatures__degree":[1,2,3],"ridge__alpha":[0.001,0.01,0.1,1,10,100]}

#XXX__YYY __はアンダーバー2つ

grid =GridSearchCV(pipe,param_grid=param_grid,cv=5,n_jobs=-1)
grid.fit(X_train,y_train)

 

6.6モデル選択のグリッドサーチ

以下例でモデル選択のグリッドサーチもできる。

(もう少し例が欲しい。これでRFのほうが良ければ結果にRFが出てくる?それを見てもう一度Pipeでセットするということか?)

pipe=Pipeline([("preprocessing",StandardScaler()),("classifier",SVC())])

param_grid =[
{"classifier":[SVC()],"preprocessing":[StandardScaler(),None],
"classifier__gamma":[0.001,0.01,0.1,1,10,100],
"classifier__C":[0.001,0.01,0.1,1,10,100]},
{"classifier":[RandomForestClassifier(n_estimators=100)],
"preprocessing":[None],"classifier__max_features":[1,2,3]}
]

#RFは前処理がいらないので"preprocessing"は[None]。

 

grid = GridSearchCV(pipe,param_grid,cv=5)
grid.fit(X_train,y_train)

 # ↓結果↓
Best params:
{'classifier': SVC(C=10, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape=None, degree=3, gamma=0.01, kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False), 'classifier__C': 10, 'classifier__gamma': 0.01, 'preprocessing': StandardScaler(copy=True, with_mean=True, with_std=True)}
Best cross-validattion score:0.9859154929577465
Test set score:0.9790209790209791