RandomForestClassifier
에는 옵션이 없지만 임의의 포리스트 알고리즘은 모든 가능한 기능의 하위 집합 만 고려하고 교육 데이터의 부트 스트랩 하위 샘플에 대해 교육되는 결정 트리의 앙상블입니다.
그래서 특정 기능 집합을 사용하도록 강요받은 나무에 대해 수동으로 직접 만드는 것은 그리 어렵지 않습니다. 아래에서이 작업을 수행 할 클래스를 작성했습니다. 이것은 이 아니며은 강력한 입력 유효성 검사 또는 그와 유사한 작업을 수행하지만 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