ランダムフォレストアルゴリズムは、すべての可能な機能のサブセットのみを考慮し、トレーニングデータのブートストラップサブサンプルで訓練される決定木のアンサンブルです。
したがって、特定の一連の機能を使用するように強制されたツリーに対しては、手動で作成することはあまり難しくありません。私は下でこれを行うクラスを書いた。これはで、は堅牢な入力検証などを実行しませんが、sklearnのランダムフォレストfit
のソースを参照してください。これはあなたにそれを自分で構築する方法の味を与えることを意味している。
FixedFeatureRFC.py
ここ
import numpy as np
from sklearn.tree import DecisionTreeClassifier
class FixedFeatureRFC:
def __init__(self, n_estimators=10, random_state=None):
self.n_estimators = n_estimators
if random_state is None:
self.random_state = np.random.RandomState()
def fit(self, X, y, feats_fixed=None, max_features=None, bootstrap_frac=0.8):
"""
feats_fixed: indices of features (columns of X) to be
always used to train each estimator
max_features: number of features that each estimator will use,
including the fixed features.
bootstrap_frac: size of bootstrap sample that each estimator will use.
"""
self.estimators = []
self.feats_used = []
self.n_classes = np.unique(y).shape[0]
if feats_fixed is None:
feats_fixed = []
if max_features is None:
max_features = X.shape[1]
n_samples = X.shape[0]
n_bs = int(bootstrap_frac*n_samples)
feats_fixed = list(feats_fixed)
feats_all = range(X.shape[1])
random_choice_size = max_features - len(feats_fixed)
feats_choosable = set(feats_all).difference(set(feats_fixed))
feats_choosable = np.array(list(feats_choosable))
for i in range(self.n_estimators):
chosen = self.random_state.choice(feats_choosable,
size=random_choice_size,
replace=False)
feats = feats_fixed + list(chosen)
self.feats_used.append(feats)
bs_sample = self.random_state.choice(n_samples,
size=n_bs,
replace=True)
dtc = DecisionTreeClassifier(random_state=self.random_state)
dtc.fit(X[bs_sample][:,feats], y[bs_sample])
self.estimators.append(dtc)
def predict_proba(self, X):
out = np.zeros((X.shape[0], self.n_classes))
for i in range(self.n_estimators):
out += self.estimators[i].predict_proba(X[:,self.feats_used[i]])
return out/self.n_estimators
def predict(self, X):
return self.predict_proba(X).argmax(axis=1)
def score(self, X, y):
return (self.predict(X) == y).mean()
意図したとおり上記のクラスが動作するかどうかを確認するテストスクリプトです:
test.py
import numpy as np
from sklearn.datasets import load_breast_cancer
from FixedFeatureRFC import FixedFeatureRFC
rs = np.random.RandomState(1234)
BC = load_breast_cancer()
X,y = BC.data, BC.target
train = rs.rand(X.shape[0]) < 0.8
print "n_features =", X.shape[1]
fixed = [0,4,21]
maxf = 10
ffrfc = FixedFeatureRFC(n_estimators=1000)
ffrfc.fit(X[train], y[train], feats_fixed=fixed, max_features=maxf)
for feats in ffrfc.feats_used:
assert len(feats) == maxf
for f in fixed:
assert f in feats
print ffrfc.score(X[~train], y[~train])
出力される。アサーションの
n_features = 30
0.983739837398
なし我々が固定されるために選択された特徴が各ランダム機能サブサンプルおよび各特徴サブサンプルのサイズが必要max_features
大きさであったことを使用したことを示す、失敗しません。保持されているデータの精度が高いことは、分類器が適切に動作していることを示します。
ランダムフォレストの性質、および実際には機械学習全体がハード入力/制御ではなく、データの値に基づいているということです。あなたの質問の背景についてもっと教えてください。なぜここで変数を選ぶのですか? – Michal
@Michal:質問を編集して詳細を追加しました。 – Patthebug