1

パイプラインを使用してRandomizedSearchCVを使用して機能の選択とハイパーパラメータの最適化を実行しています。RandomizedSearchCVは同じrandom_stateを使用して異なる結果を返します

from sklearn.cross_validation import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.feature_selection import SelectKBest 
from sklearn.grid_search import RandomizedSearchCV 
from sklearn.pipeline import make_pipeline 
from scipy.stats import randint as sp_randint 

rng = 44 

X_train, X_test, y_train, y_test = 
    train_test_split(data[features], data['target'], random_state=rng) 


clf = RandomForestClassifier(random_state=rng) 
kbest = SelectKBest() 
pipe = make_pipeline(kbest,clf) 

upLim = X_train.shape[1] 
param_dist = {'selectkbest__k':sp_randint(upLim/2,upLim+1), 
    'randomforestclassifier__n_estimators': sp_randint(5,150), 
    'randomforestclassifier__max_depth': [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, None], 
    'randomforestclassifier__criterion': ["gini", "entropy"], 
    'randomforestclassifier__max_features': ['auto', 'sqrt', 'log2']} 
clf_opt = RandomizedSearchCV(pipe, param_distributions= param_dist, 
          scoring='roc_auc', n_jobs=1, cv=3, random_state=rng) 
clf_opt.fit(X_train,y_train) 
y_pred = clf_opt.predict(X_test) 
train_test_splitRandomForestClassiferのため、私は一定の random_state使用しています

、およびRandomizedSearchCV:ここでは、コードの概要です。しかし、上記のコードの結果は、何度か実行すると少し異なります。具体的には、コードにいくつかのテストユニットがあり、これらのわずかに異なる結果がテストユニットの失敗につながります。 random_stateを使用しているため同じ結果が得られるはずはありませんか?私のコードで、コードの一部にランダム性を生む何かがありませんか?

答えて

1

私は通常、自分の質問に答えます!私はこれと同様の質問をした他の人のためにここに残します:

ランダムなシードを定義しました。コードは次のとおりです:

from sklearn.cross_validation import train_test_split 
from sklearn.ensemble import RandomForestClassifier 
from sklearn.feature_selection import SelectKBest 
from sklearn.grid_search import RandomizedSearchCV 
from sklearn.pipeline import make_pipeline 
from scipy.stats import randint as sp_randint 

seed = np.random.seed(22) 

X_train, X_test, y_train, y_test = 
    train_test_split(data[features], data['target']) 


clf = RandomForestClassifier() 
kbest = SelectKBest() 
pipe = make_pipeline(kbest,clf) 

upLim = X_train.shape[1] 
param_dist = {'selectkbest__k':sp_randint(upLim/2,upLim+1), 
    'randomforestclassifier__n_estimators': sp_randint(5,150), 
    'randomforestclassifier__max_depth': [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, None], 
    'randomforestclassifier__criterion': ["gini", "entropy"], 
    'randomforestclassifier__max_features': ['auto', 'sqrt', 'log2']} 
clf_opt = RandomizedSearchCV(pipe, param_distributions= param_dist, 
          scoring='roc_auc', n_jobs=1, cv=3) 
clf_opt.fit(X_train,y_train) 
y_pred = clf_opt.predict(X_test) 

他人を助けることを願っています!

+0

元のコードが期待どおりに機能しない理由がわかりませんが(私はあまりにも怠けています)、このソリューションは完璧なものではありません。ここでは、これらの3つのコンポーネント間の操作の順序が常に同じであると仮定していますが、これはこのコードでは問題ありませんが、より複雑なタスクでは問題を引き起こす可能性があります。基本的に、複数のランダムストリームから1つのランダムストリームへの切り替えです。 – sascha

+0

@サシャー:あなたのコメントありがとう!私は主な原因を見つけるのはまだ興味があります。 'scipy.stats.randint'の使用が問題を引き起こしたと思いますか? – MhFarahani

関連する問題