2015-04-29 15:50:57 -04:00
|
|
|
#include "isaac/model/predictors/random_forest.h"
|
2015-08-06 19:34:26 -07:00
|
|
|
#include "rapidjson/to_array.hpp"
|
2015-08-06 12:05:12 -07:00
|
|
|
|
2015-04-29 15:50:57 -04:00
|
|
|
namespace isaac
|
2015-01-12 13:20:53 -05:00
|
|
|
{
|
|
|
|
|
|
|
|
namespace predictors
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
|
|
random_forest::tree::tree(rapidjson::Value const & treerep)
|
|
|
|
{
|
2015-08-06 19:34:26 -07:00
|
|
|
children_left_ = rapidjson::to_int_array<int>(treerep["children_left"]);
|
|
|
|
children_right_ = rapidjson::to_int_array<int>(treerep["children_right"]);
|
|
|
|
threshold_ = rapidjson::to_float_array<float>(treerep["threshold"]);
|
|
|
|
feature_ = rapidjson::to_float_array<float>(treerep["feature"]);
|
2015-01-12 13:20:53 -05:00
|
|
|
for(rapidjson::SizeType i = 0 ; i < treerep["value"].Size() ; i++)
|
2015-08-06 19:34:26 -07:00
|
|
|
value_.push_back(rapidjson::to_float_array<float>(treerep["value"][i]));
|
2015-01-12 13:20:53 -05:00
|
|
|
D_ = value_[0].size();
|
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<float> const & random_forest::tree::predict(std::vector<int_t> const & x) const
|
|
|
|
{
|
|
|
|
int_t idx = 0;
|
|
|
|
while(children_left_[idx]!=-1)
|
|
|
|
idx = (x[feature_[idx]] <= threshold_[idx])?children_left_[idx]:children_right_[idx];
|
|
|
|
return value_[idx];
|
|
|
|
}
|
|
|
|
|
|
|
|
int_t random_forest::tree::D() const { return D_; }
|
|
|
|
|
|
|
|
random_forest::random_forest(rapidjson::Value const & estimators)
|
|
|
|
{
|
|
|
|
for(rapidjson::SizeType i = 0 ; i < estimators.Size() ; ++i)
|
|
|
|
estimators_.push_back(tree(estimators[i]));
|
2015-02-01 22:28:49 -05:00
|
|
|
D_ = estimators_.front().D();
|
2015-01-12 13:20:53 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<float> random_forest::predict(std::vector<int_t> const & x) const
|
|
|
|
{
|
2015-02-01 22:28:49 -05:00
|
|
|
std::vector<float> res(D_, 0);
|
2015-02-04 22:06:15 -05:00
|
|
|
for(const auto & elem : estimators_)
|
2015-01-12 13:20:53 -05:00
|
|
|
{
|
2015-02-04 22:06:15 -05:00
|
|
|
std::vector<float> const & subres = elem.predict(x);
|
2015-02-01 22:28:49 -05:00
|
|
|
for(int_t i = 0 ; i < D_ ; ++i)
|
2015-01-12 13:20:53 -05:00
|
|
|
res[i] += subres[i];
|
|
|
|
}
|
2015-02-01 22:28:49 -05:00
|
|
|
for(int_t i = 0 ; i < D_ ; ++i)
|
2015-01-12 13:20:53 -05:00
|
|
|
res[i] /= estimators_.size();
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::vector<random_forest::tree> const & random_forest::estimators() const
|
|
|
|
{ return estimators_; }
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|