Medial Code Documentation
Loading...
Searching...
No Matches
MedXGB.h
1#ifndef __MEDXGB_H__
2#define __MEDXGB_H__
3#pragma once
5#include <MedProcessTools/MedProcessTools/MedProcessUtils.h>
6#include <xgboost/c_api.h>
7#include "MedProcessTools/MedProcessTools/MedSamples.h"
8
10{
11 string booster; // gbtree or gblinear
12 string objective; // binary:logistic is logistic regression loss function for binary classification
13 float eta; // step size shrinkage
14 float gamma; // minimum loss reduction required to make a further partition
15 int min_child_weight; // minimum sum of instance weight(hessian) needed in a child
16 int max_depth; // maximum depth of a tree
17 int num_round; // the number of rounds to do boosting
18 vector<string> eval_metric; // when not silent, report this metric
19 int silent; // debug mode
20 float missing_value; // which value in the input is representing missing
21 int num_class; // needed for multi:softmax
22 float colsample_bytree;
23 float colsample_bylevel;
24 float subsample;
25 float scale_pos_weight;
26 string tree_method;
27 float lambda;
28 float alpha;
29 int seed; // randomization seed
30 int verbose_eval;
31 float validate_frac; // how much of the training set is used as validation for evaluation. should be between 0 and 1.
32 string split_penalties; // feature-dependent splitting penalty. string format is "number:value,number:value,..."
33 string monotone_constraints; // feature-dependent monotonic constraint. string format is "part_of_feature_name:part_of_feature_name,number:value,..."
34
36 {
37 booster = "gbtree";
38 objective = "binary:logistic";
39 eta = 1.0;
40 gamma = 1.0;
41 min_child_weight = 1;
42 max_depth = 3;
43 num_round = 500;
44 silent = 1;
45 eval_metric.push_back("auc");
46 missing_value = MED_MAT_MISSING_VALUE;
47 num_class = 1; // only set when multiclass
48 colsample_bytree = 1.0;
49 colsample_bylevel = 1.0;
50 subsample = 1.0;
51 scale_pos_weight = 1.0;
52 tree_method = "auto";
53 lambda = 1;
54 alpha = 0;
55 seed = 0;
56 verbose_eval = 0;
57 validate_frac = 0;
58 }
59
60 ADD_CLASS_NAME(MedXGBParams)
61 ADD_SERIALIZATION_FUNCS(booster, objective, eta, gamma, min_child_weight, max_depth, num_round, eval_metric, silent, missing_value, num_class,
62 colsample_bytree, colsample_bylevel, subsample, scale_pos_weight, tree_method, lambda, alpha, seed, verbose_eval, validate_frac, split_penalties, monotone_constraints)
63};
64
65class MedXGB : public MedPredictor
66{
67public:
68 BoosterHandle my_learner = NULL;
69 MedXGBParams params;
70 void init_defaults();
71 int feat_contrib_flags = 0;
72 virtual int init(void *classifier_params)
73 {
74 this->params = *((MedXGBParams *)classifier_params);
75 return 0;
76 };
79 virtual int set_params(map<string, string> &initialization_map);
80
81 // Function
82 MedXGB() { init_defaults(); };
83 ~MedXGB();
84
85 int Learn(float *x, float *y, const float *w, int nsamples, int nftrs);
86 int Learn(float *x, float *y, int nsamples, int nftrs);
87 int Predict(float *x, float *&preds, int nsamples, int nftrs) const;
88 void prepare_mat_handle(float *x, float *y, const float *w, int nsamples, int nftrs, DMatrixHandle &matrix_handle);
89
90 virtual void print(FILE *fp, const string &prefix, int level = 0) const;
91
92 void calc_feature_importance(vector<float> &features_importance_scores,
93 const string &general_params, const MedFeatures *features);
94
96
97 void calc_feature_contribs_conditional(MedMat<float> &mat_x_in, unordered_map<string, float> &contiditional_variables, MedMat<float> &mat_x_out, MedMat<float> &mat_contribs);
98
99 void export_predictor(const string &output_fname);
100
101 int n_preds_per_sample() const;
102
103 void pre_serialization()
104 {
105 const char *out_dptr;
106 bst_ulong len;
107 string cfg_js = "{ \"format\":\"json\" }";
108 if (my_learner != NULL)
109 {
110 if (XGBoosterSaveModelToBuffer(my_learner, cfg_js.c_str(), &len, &out_dptr) != 0)
111 throw runtime_error("failed XGBoosterSaveModelToBuffer\n");
112 serial_xgb.resize(len);
113 memcpy(&serial_xgb[0], out_dptr, len);
114 }
115 else
116 serial_xgb.clear();
117 }
118
119 void post_deserialization()
120 {
121 if (this->my_learner != NULL)
122 XGBoosterFree(this->my_learner);
123 if (!serial_xgb.empty())
124 {
125 DMatrixHandle h_train_empty[1];
126 if (XGBoosterCreate(h_train_empty, 0, &my_learner) != 0)
127 throw runtime_error("failed XGBoosterCreate\n");
128 if (XGBoosterLoadModelFromBuffer(my_learner, &serial_xgb[0], serial_xgb.size()) != 0)
129 throw runtime_error("failed XGBoosterLoadModelFromBuffer\n");
130 serial_xgb.clear();
131 }
132 }
133
134 void prepare_predict_single();
135 void predict_single(const vector<float> &x, vector<float> &preds) const;
136
137 void get_json(const char ***json, int &len, string type)
138 {
139 if (my_learner != NULL)
140 {
141 string no_fmap = "";
142 bst_ulong _len;
143 int succ = XGBoosterDumpModelEx(my_learner, no_fmap.c_str(), 1, type.c_str(), &_len, json);
144 if (succ < 0)
145 HMTHROW_AND_ERR("Error MedXGB::get_json - can't get model\n");
146 len = (int)_len;
147 }
148 else
149 len = 0;
150 }
151
152 ADD_CLASS_NAME(MedXGB)
153 ADD_SERIALIZATION_FUNCS(classifier_type, serial_xgb, params, model_features, features_count, _mark_learn_done)
154
155private:
156 bool _mark_learn_done;
157 bool prepared_single;
158 vector<BoosterHandle> learner_per_thread;
159
160 void translate_split_penalties(string &split_penalties_s);
161 void translate_monotone_constraints(string &monotone_constraints_s);
162 void calc_feature_importance_local(vector<float> &features_importance_scores, string &importance_type);
163 vector<char> serial_xgb;
164};
165
166//=================================================================
167// Joining the MedSerialize Wagon
168//=================================================================
171
172// #endif
173#endif
MedAlgo - APIs to different algorithms: Linear Models, RF, GBM, KNN, and more.
#define ADD_SERIALIZATION_FUNCS(...)
Definition SerializableObject.h:156
#define MEDSERIALIZE_SUPPORT(Type)
Definition SerializableObject.h:142
A class for holding features data as a virtual matrix
Definition MedFeatures.h:47
Definition MedMat.h:63
Base Interface for predictor.
Definition MedAlgo.h:72
int features_count
The model features count used in Learn, to validate when caling predict.
Definition MedAlgo.h:90
MedPredictorTypes classifier_type
The Predicotr enum type.
Definition MedAlgo.h:74
vector< string > model_features
The model features used in Learn, to validate when caling predict.
Definition MedAlgo.h:87
Definition MedXGB.h:66
virtual int set_params(map< string, string > &initialization_map)
The parsed fields from init command.
Definition MedXGB.cpp:488
void calc_feature_contribs(MedMat< float > &x, MedMat< float > &contribs)
Feature contributions explains the prediction on each sample (aka BUT_WHY)
Definition MedXGB.cpp:83
int Predict(float *x, float *&preds, int nsamples, int nftrs) const
Predict should be implemented for each model.
Definition MedXGB.cpp:62
int n_preds_per_sample() const
Number of predictions per sample. typically 1 - but some models return several per sample (for exampl...
Definition MedXGB.cpp:38
int Learn(float *x, float *y, const float *w, int nsamples, int nftrs)
Learn should be implemented for each model.
Definition MedXGB.cpp:179
Definition SerializableObject.h:33
Definition MedXGB.h:10