Scikit-learn
human-activity-recognition
wearable
wrist
time-series
cpu
scikit-learn
WISP / src /wisp_fast /search_forest.py
Zipeng365's picture
wisp-har 0.2.0: accelerated implementation with speed (exact/fast) and HMM sequence (subject/recording) options
ac7f7cb verified
Raw History Blame Contribute Delete
1.71 kB
"""Avoid repeated sklearn parameter introspection for built-in WISP forest trees."""
from contextlib import contextmanager
import numpy as np
from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier, ExtraTreeClassifier
from sklearn.utils import check_random_state
@contextmanager
def forest_fit_plan(forest):
"""Use the same per-tree constructor parameters and sklearn seed stream.
The hook is local to this one estimator and removed before it is serialized.
Tree growth, bootstrap samples, sample/class weights and parallel schedules
remain sklearn's own. Only the two built-in release forest types qualify.
"""
if type(forest) not in (RandomForestClassifier, ExtraTreesClassifier):
yield
return
prototype = forest.estimator
if type(prototype) not in (DecisionTreeClassifier,ExtraTreeClassifier):
yield
return
constructor = type(prototype)
params = prototype.get_params(deep=False)
params.update({name:getattr(forest,name) for name in forest.estimator_params})
max_seed = np.iinfo(np.int32).max
def make_estimator(append=True,random_state=None):
# sklearn._set_random_states draws one int for these non-nested trees.
if random_state is not None:
params["random_state"] = check_random_state(random_state).randint(max_seed)
else:
params["random_state"] = forest.random_state
tree = constructor(**params)
if append:
forest.estimators_.append(tree)
return tree
forest._make_estimator = make_estimator
try:
yield
finally:
del forest._make_estimator