Debian Codegraph @

src/include/xgboost/learner.h

raw symbols SCIP
1 /**
2 * Copyright 2015-2025, XGBoost Contributors
3 *
4 * \brief Learner interface that integrates objective, gbm and evaluation together.
5 * This is the user facing XGBoost training module.
6 * \author Tianqi Chen
7 */
8 #ifndef XGBOOST_LEARNER_H_
9 #define XGBOOST_LEARNER_H_
10
11 #include <dmlc/io.h> // for Serializable
12 #include <xgboost/base.h> // for bst_feature_t, bst_target_t, bst_float, Args, GradientPair, ..
13 #include <xgboost/context.h> // for Context
14 #include <xgboost/gradient.h> // for GradientContainer
15 #include <xgboost/linalg.h> // for Vector, VectorView
16 #include <xgboost/metric.h> // for Metric
17 #include <xgboost/model.h> // for Configurable, Model
18 #include <xgboost/span.h> // for Span
19 #include <xgboost/task.h> // for ObjInfo
20
21 #include <algorithm> // for max
22 #include <cstdint> // for int32_t, uint32_t, uint8_t
23 #include <map> // for map
24 #include <memory> // for shared_ptr, unique_ptr
25 #include <string> // for string
26 #include <utility> // for move
27 #include <vector> // for vector
28
29 namespace xgboost {
30 class FeatureMap;
31 class Metric;
32 class GradientBooster;
33 class ObjFunction;
34 class DMatrix;
35 class Json;
36 struct XGBAPIThreadLocalEntry;
37 template <typename T>
38 class HostDeviceVector;
39 class CatContainer;
40
41 enum class PredictionType : std::uint8_t { // NOLINT
42 kValue = 0,
43 kMargin = 1,
44 kContribution = 2,
45 kApproxContribution = 3,
46 kInteraction = 4,
47 kApproxInteraction = 5,
48 kLeaf = 6
49 };
50
51 /**
52 * @brief Learner class that does training and prediction.
53 * This is the user facing module of xgboost training.
54 * The Load/Save function corresponds to the model used in python/R.
55 * @code
56 *
57 * std::unique_ptr<Learner> learner{Learner::Create(cache_mats)};
58 * learner->Configure(configs);
59 *
60 * for (int iter = 0; iter < max_iter; ++iter) {
61 * learner->UpdateOneIter(iter, train_mat);
62 * LOG(INFO) << learner->EvalOneIter(iter, data_sets, data_names);
63 * }
64 *
65 * @endcode
66 */
67 class Learner : public Model, public Configurable, public dmlc::Serializable {
68 public:
69 ~Learner() override;
70 /*!
71 * \brief Configure Learner based on set parameters.
72 */
73 virtual void Configure() = 0;
74 /*!
75 * \brief update the model for one iteration
76 * With the specified objective function.
77 * \param iter current iteration number
78 * \param train reference to the data matrix.
79 */
80 virtual void UpdateOneIter(std::int32_t iter, std::shared_ptr<DMatrix> train) = 0;
81 /**
82 * @brief Do customized gradient boosting with in_gpair.
83 *
84 * @note in_gpair can be mutated after this call.
85 *
86 * @param iter current iteration number
87 * @param train reference to the data matrix.
88 * @param in_gpair The input gradient statistics.
89 */
90 virtual void BoostOneIter(std::int32_t iter, std::shared_ptr<DMatrix> train,
91 GradientContainer* in_gpair) = 0;
92 /*!
93 * \brief evaluate the model for specific iteration using the configured metrics.
94 * \param iter iteration number
95 * \param data_sets datasets to be evaluated.
96 * \param data_names name of each dataset
97 * \return a string corresponding to the evaluation result
98 */
99 virtual std::string EvalOneIter(int iter,
100 const std::vector<std::shared_ptr<DMatrix>>& data_sets,
101 const std::vector<std::string>& data_names) = 0;
102 /*!
103 * \brief get prediction given the model.
104 * \param data input data
105 * \param output_margin whether to only predict margin value instead of transformed prediction
106 * \param out_preds output vector that stores the prediction
107 * \param layer_begin Beginning of boosted tree layer used for prediction.
108 * \param layer_end End of booster layer. 0 means do not limit trees.
109 * \param training Whether the prediction result is used for training
110 * \param pred_leaf whether to only predict the leaf index of each tree in a boosted tree predictor
111 * \param pred_contribs whether to only predict the feature contributions
112 * \param approx_contribs whether to approximate the feature contributions for speed
113 * \param pred_interactions whether to compute the feature pair contributions
114 */
115 virtual void Predict(std::shared_ptr<DMatrix> data, bool output_margin,
116 HostDeviceVector<bst_float>* out_preds, bst_layer_t layer_begin,
117 bst_layer_t layer_end, bool training = false, bool pred_leaf = false,
118 bool pred_contribs = false, bool approx_contribs = false,
119 bool pred_interactions = false) = 0;
120
121 /*!
122 * \brief Inplace prediction.
123 *
124 * \param p_fmat A proxy DMatrix that contains the data and related meta info.
125 * \param type Prediction type.
126 * \param missing Missing value in the data.
127 * \param [in,out] out_preds Pointer to output prediction vector.
128 * \param layer_begin Beginning of boosted tree layer used for prediction.
129 * \param layer_end End of booster layer. 0 means do not limit trees.
130 */
131 virtual void InplacePredict(std::shared_ptr<DMatrix> p_m, PredictionType type, float missing,
132 HostDeviceVector<float>** out_preds, bst_layer_t layer_begin,
133 bst_layer_t layer_end) = 0;
134
135 /*!
136 * \brief Calculate feature score. See doc in C API for outputs.
137 */
138 virtual void CalcFeatureScore(std::string const& importance_type,
139 common::Span<int32_t const> trees,
140 std::vector<bst_feature_t>* features,
141 std::vector<float>* scores) = 0;
142
143 /*
144 * \brief Get number of boosted rounds from gradient booster.
145 */
146 virtual int32_t BoostedRounds() const = 0;
147 /**
148 * \brief Get the number of output groups from the model.
149 */
150 virtual std::uint32_t Groups() const = 0;
151
152 void LoadModel(Json const& in) override = 0;
153 void SaveModel(Json* out) const override = 0;
154
155 /*!
156 * \brief Set multiple parameters at once.
157 *
158 * \param args parameters.
159 */
160 virtual void SetParams(Args const& args) = 0;
161 /*!
162 * \brief Set parameter for booster
163 *
164 * The property will NOT be saved along with booster
165 *
166 * \param key The key of parameter
167 * \param value The value of parameter
168 */
169 virtual void SetParam(const std::string& key, const std::string& value) = 0;
170
171 /**
172 * @brief Get the number of features of the booster.
173 * @return The number of features
174 */
175 virtual bst_feature_t GetNumFeature() const = 0;
176
177 /*!
178 * \brief Set additional attribute to the Booster.
179 *
180 * The property will be saved along the booster.
181 *
182 * \param key The key of the property.
183 * \param value The value of the property.
184 */
185 virtual void SetAttr(const std::string& key, const std::string& value) = 0;
186 /*!
187 * \brief Get attribute from the booster.
188 * The property will be saved along the booster.
189 * \param key The key of the attribute.
190 * \param out The output value.
191 * \return Whether the key exists among booster's attributes.
192 */
193 virtual bool GetAttr(const std::string& key, std::string* out) const = 0;
194 /*!
195 * \brief Delete an attribute from the booster.
196 * \param key The key of the attribute.
197 * \return Whether the key was found among booster's attributes.
198 */
199 virtual bool DelAttr(const std::string& key) = 0;
200 /*!
201 * \brief Get a vector of attribute names from the booster.
202 * \return vector of attribute name strings.
203 */
204 virtual std::vector<std::string> GetAttrNames() const = 0;
205 /*!
206 * \brief Set the feature names for current booster.
207 * \param fn Input feature names
208 */
209 virtual void SetFeatureNames(std::vector<std::string> const& fn) = 0;
210 /*!
211 * \brief Get the feature names for current booster.
212 * \param fn Output feature names
213 */
214 virtual void GetFeatureNames(std::vector<std::string>* fn) const = 0;
215 /*!
216 * \brief Set the feature types for current booster.
217 * \param ft Input feature types.
218 */
219 virtual void SetFeatureTypes(std::vector<std::string> const& ft) = 0;
220 /*!
221 * \brief Get the feature types for current booster.
222 * \param fn Output feature types
223 */
224 virtual void GetFeatureTypes(std::vector<std::string>* ft) const = 0;
225 /**
226 * @brief Getter for categories.
227 */
228 [[nodiscard]] virtual CatContainer const* Cats() const = 0;
229 /**
230 * @brief Slice the model.
231 *
232 * See InplacePredict for layer parameters.
233 *
234 * @param step step size between slice.
235 * @param out_of_bound Return true if end layer is out of bound.
236 *
237 * @return a sliced model.
238 */
239 virtual Learner* Slice(bst_layer_t begin, bst_layer_t end, bst_layer_t step,
240 bool* out_of_bound) = 0;
241 /*!
242 * \brief dump the model in the requested format
243 * \param fmap feature map that may help give interpretations of feature
244 * \param with_stats extra statistics while dumping model
245 * \param format the format to dump the model in
246 * \return a vector of dump for boosters.
247 */
248 virtual std::vector<std::string> DumpModel(const FeatureMap& fmap,
249 bool with_stats,
250 std::string format) = 0;
251
252 virtual XGBAPIThreadLocalEntry& GetThreadLocal() const = 0;
253 /**
254 * @brief Reset the booster object to release data caches used for training.
255 */
256 virtual void Reset() = 0;
257 /*!
258 * \brief Create a new instance of learner.
259 * \param cache_data The matrix to cache the prediction.
260 * \return Created learner.
261 */
262 static Learner* Create(const std::vector<std::shared_ptr<DMatrix> >& cache_data);
263 /**
264 * \brief Return the context object of this Booster.
265 */
266 virtual Context const* Ctx() const = 0;
267 /*!
268 * \brief Get configuration arguments currently stored by the learner
269 * \return Key-value pairs representing configuration arguments
270 */
271 virtual const std::map<std::string, std::string>& GetConfigurationArguments() const = 0;
272
273 protected:
274 /*! \brief objective function */
275 std::unique_ptr<ObjFunction> obj_;
276 /*! \brief The gradient booster used by the model*/
277 std::unique_ptr<GradientBooster> gbm_;
278 /*! \brief The evaluation metrics used to evaluate the model. */
279 std::vector<std::unique_ptr<Metric> > metrics_;
280 /*! \brief Training parameter. */
281 Context ctx_;
282 };
283
284 struct LearnerModelParamLegacy;
285
286 /**
287 * @brief Strategy for building multi-target models.
288 */
289 enum class MultiStrategy : std::int32_t {
290 kOneOutputPerTree = 0,
291 kMultiOutputTree = 1,
292 };
293
294 /**
295 * @brief Basic model parameters, used to describe the booster.
296 */
297 struct LearnerModelParam {
298 private:
299 /**
300 * @brief Global bias, this is just a scalar value but can be extended to vector when we
301 * support multi-class and multi-target.
302 *
303 * The value stored here is the value before applying the inverse link function, used
304 * for initializing the prediction matrix/vector.
305 */
306 linalg::Vector<float> base_score_;
307
308 LearnerModelParam(LearnerModelParamLegacy const& user_param, ObjInfo t,
309 MultiStrategy multi_strategy);
310
311 public:
312 /**
313 * @brief The number of features.
314 */
315 bst_feature_t num_feature{0};
316 /**
317 * @brief The number of classes or targets.
318 */
319 std::uint32_t num_output_group{0};
320 /**
321 * @brief Current task, determined by objective.
322 */
323 ObjInfo task{ObjInfo::kRegression};
324 /**
325 * @brief Strategy for building multi-target models.
326 */
327 MultiStrategy multi_strategy{MultiStrategy::kOneOutputPerTree};
328
329 LearnerModelParam() = default;
330 LearnerModelParam(Context const* ctx, LearnerModelParamLegacy const& user_param,
331 linalg::Vector<float> base_score, ObjInfo t, MultiStrategy multi_strategy);
332 // This ctor is only used by tests.
333 LearnerModelParam(bst_feature_t n_features, linalg::Vector<float> base_score,
334 std::uint32_t n_groups, bst_target_t n_targets, MultiStrategy multi_strategy)
335 : base_score_{std::move(base_score)},
336 num_feature{n_features},
337 num_output_group{std::max(n_groups, n_targets)},
338 multi_strategy{multi_strategy} {}
339
340 linalg::VectorView<float const> BaseScore(Context const* ctx) const;
341 [[nodiscard]] linalg::VectorView<float const> BaseScore(DeviceOrd device) const;
342
343 void Copy(LearnerModelParam const& that);
344 [[nodiscard]] bool IsVectorLeaf() const noexcept {
345 return multi_strategy == MultiStrategy::kMultiOutputTree;
346 }
347 [[nodiscard]] bst_target_t OutputLength() const noexcept { return this->num_output_group; }
348 [[nodiscard]] bst_target_t LeafLength() const noexcept {
349 return this->IsVectorLeaf() ? this->OutputLength() : 1;
350 }
351
352 /* \brief Whether this parameter is initialized with LearnerModelParamLegacy. */
353 [[nodiscard]] bool Initialized() const { return num_feature != 0 && num_output_group != 0; }
354 };
355
356 } // namespace xgboost
357 #endif // XGBOOST_LEARNER_H_