Booster
public class Booster
Booster model.
Encapsulates BoosterHandle, the model of xgboost, that contains low level routines for training, prediction and evaluation.
-
Pointer to underlying BoosterHandle.
Declaration
Swift
public var booster: BoosterHandle? -
Version of underlying XGBoost system library.
Declaration
Swift
public static var systemLibraryVersion: (major: Int, minor: Int, patch: Int) -
Register callback function for LOG(INFO) messages.
Declaration
Swift
public static func registerLogCallback( _ call: (@convention(c) (UnsafePointer<Int8>?) -> Void)? ) throwsParameters
callFunction to be called with C-String as parameter. Use String(cString: $0!) co convert it into Swift string.
-
Initialize Booster with an existing BoosterHandle pointer.
Declaration
Swift
public init( booster: BoosterHandle? )Parameters
boosterBoosterHandle pointer.
-
Initialize Booster from buffer.
Declaration
Swift
public convenience init( buffer: BufferModel ) throwsParameters
bufferModel serialized as buffer.
-
Initialize new Booster.
Declaration
Parameters
withData that will be cached.
fromLoads model from path.
configLoads model from config.
parametersArray of parameters to be set.
validateParametersIf true, parameters will be valided. This basically adds parameter validate_parameters=1.
-
Serializes and unserializes booster to reset state and free training memory.
Declaration
Swift
public func reset() throws -
Declaration
Swift
public func config() throws -> StringReturn Value
Booster’s internal configuration in a JSON string.
-
Declaration
Swift
public func attributes() throws -> [String : String]Return Value
Attributes stored in the Booster as a dictionary.
-
predict(from:outputMargin: treeLimit: predictionLeaf: predictionContributions: approximateContributions: predictionInteractions: training: validateFeatures: ) Predict from data.
Declaration
Swift
public func predict( from data: DMatrix, outputMargin: Bool = false, treeLimit: UInt32 = 0, predictionLeaf: Bool = false, predictionContributions: Bool = false, approximateContributions: Bool = false, predictionInteractions: Bool = false, training: Bool = false, validateFeatures: Bool = true ) throws -> ArrayWithShape<Float>Parameters
fromData to predict from.
outputMarginWhether to output the raw untransformed margin value.
treeLimitLimit number of trees in the prediction. Zero means use all trees.
predictionLeafEach record indicating the predicted leaf index of each sample in each tree.
predictionContributionsEach record indicating the feature contributions (SHAP values) for that prediction.
approximateContributionsApproximate the contributions of each feature.
predictionInteractionsIndicate the SHAP interaction values for each pair of features.
trainingWhether the prediction will be used for traning.
validateFeaturesValidate booster and data features.
-
predict(features:outputMargin: treeLimit: predictionLeaf: predictionContributions: approximateContributions: predictionInteractions: training: missingValue: ) Predict directly from array of floats, will build Data structure automatically with one row and features.count features.
Declaration
Swift
public func predict( features: FloatData, outputMargin: Bool = false, treeLimit: UInt32 = 0, predictionLeaf: Bool = false, predictionContributions: Bool = false, approximateContributions: Bool = false, predictionInteractions: Bool = false, training: Bool = false, missingValue: Float = Float.greatestFiniteMagnitude ) throws -> FloatParameters
featuresFeatures to base prediction at.
outputMarginWhether to output the raw untransformed margin value.
treeLimitLimit number of trees in the prediction. Zero means use all trees.
predictionLeafEach record indicating the predicted leaf index of each sample in each tree.
predictionContributionsEach record indicating the feature contributions (SHAP values) for that prediction.
approximateContributionsApproximate the contributions of each feature.
predictionInteractionsIndicate the SHAP interaction values for each pair of features.
trainingWhether the prediction will be used for traning.
missingValueValue in features representing missing values.
-
Declaration
Swift
public func serialized() throws -> SerializedBufferReturn Value
Everything states in buffer.
-
Saves modes into file.
Declaration
Swift
public func save( to path: String ) throwsParameters
toPath to output file.
-
Declaration
Swift
public func raw() throws -> RawModelReturn Value
Model as binary raw bytes.
-
Dump model into a string.
Declaration
Swift
public func dumped( features: [Feature]? = nil, featureMap: String = "", withStatistics: Bool = false, format: ModelFormat = .text ) throws -> StringParameters
featuresArray of features.
featureMapName of the file containing feature map.
withStatisticsControls whether the split statistics are output.
formatDesired output format type.
Return Value
Formated output into ModelFormat format.
-
Dump model into an array of strings. In most cases you will want to use
dumpedmethod to get output in expected format.Declaration
Swift
public func rawDumped( features: [Feature]? = nil, featureMap: String = "", withStatistics: Bool = false, format: ModelFormat = .text ) throws -> [String]Parameters
featuresArray of features, you can override ones stored in self.features with this.
featureMapName of the file containing feature map.
withStatisticsControls whether the split statistics are output.
formatDesired output format type.
Return Value
Raw output from XGBoosterDumpModelEx provided as array of strings.
-
Get feature importance of each feature.
Declaration
Swift
public func score( featureMap: String = "", importance: Importance = .weight ) throws -> (features: [String: Int], gains: [String: Float]?)Parameters
featureMapPath to the feature map.
importanceType of importance you want to compute.
Return Value
Tuple of features and gains, in case importance = weight, gains will be nil.
-
Loads model from buffer.
Declaration
Swift
public func load( modelBuffer buffer: BufferModel ) throwsParameters
modelBuffer to load from.
-
Loads model from file.
Declaration
Swift
public func load( model path: String ) throwsParameters
modelPath of file to load model from.
-
Loads model from config.
Declaration
Swift
public func load( config: String ) throwsParameters
modelConfig to load from.
-
Save the current checkpoint to rabit.
Declaration
Swift
public func saveRabitCheckpoint() throws -
Initialize the booster from rabit checkpoint.
Declaration
Swift
public func loadRabitCheckpoint() throws -> IntReturn Value
The output version of the model.
-
Get attribute string from the Booster.
Declaration
Swift
public func attribute( name: String ) throws -> String?Parameters
nameName of attribute to get.
Return Value
Value of attribute or nil if not set.
-
Set string attribute.
Declaration
Swift
public func set( attribute: String, value: String ) throwsParameters
attributeName of attribute.
valueValue of attribute.
-
Set string parameter.
Declaration
Swift
public func set( parameter: String, value: String ) throwsParameters
parameterName of parameter.
valueValue of parameter.
-
Update for one iteration, with objective function calculated internally.
Declaration
Swift
public func update( iteration: Int, data: Data, validateFeatures: Bool = true ) throwsParameters
iterationCurrent iteration number.
dataTraining data.
validateFeaturesWhether to validate features.
-
Update for one iteration with custom objective.
Declaration
Swift
public func update( data: Data, objective: ObjectiveFunction, validateFeatures: Bool = true ) throwsParameters
dataTraining data.
objectiveObjective function returning gradient and hessian.
validateFeaturesWhether to validate features.
-
Boost the booster for one iteration, with customized gradient statistics.
Declaration
Swift
public func boost( data: Data, gradient: [Float], hessian: [Float], validateFeatures: Bool = true ) throwsParameters
dataTraining data.
gradientThe first order of gradient.
hessianThe second order of gradient.
validateFeaturesWhether to validate features.
-
Evaluate array of data.
Declaration
Swift
public func evaluate( iteration: Int, data: [Data], function: EvaluationFunction? = nil ) throws -> [String: [String: String]]Parameters
iterationCurrent iteration.
dataData to evaluate.
functionCustom function for evaluation.
Return Value
Dictionary in format [data_name: [eval_name: eval_value, …], …]
-
Evaluate data.
Declaration
Swift
public func evaluate( iteration: Int, data: Data, function: EvaluationFunction? = nil ) throws -> [String: String]Parameters
iterationCurrent iteration.
dataData to evaluate.
functionCustom function for evaluation.
Return Value
Dictionary in format [data_name: [eval_name: eval_value]]
-
Validate features.
Declaration
Swift
public func validate( features: [Feature] ) throwsParameters
featuresFeatures to validate.
-
Validate features.
Declaration
Swift
public func validate( data: DMatrix ) throwsParameters
dataData which features will be validated.
-
Validate features.
Declaration
Swift
public func validate( data: [DMatrix] ) throwsParameters
dataArray of data which features will be validated.
-
saveImportanceGraph(to:featureMap: importance: label: title: xAxisLabel: yAxisLabel: maxNumberOfFeatures: graphOrientation: enableGrid: size: renderer: ) Saves plot with importance based on fitted trees.
Declaration
Swift
public func saveImportanceGraph( to fileName: String, featureMap: String = "", importance: Importance = .weight, label: String = "Feature importance", title: String = "Feature importance", xAxisLabel: String = "Score", yAxisLabel: String = "Features", maxNumberOfFeatures: Int? = nil, graphOrientation: BarGraph<String, Float>.GraphOrientation = .horizontal, enableGrid: Bool = true, size: Size = Size(width: 1000, height: 660), renderer: Renderer = SVGRenderer() ) throwsParameters
toFile where graph will be saved, .svg extension will be added if rendered remains SVGRenderer.
featureMapPath to the feature map, if provided, replaces default f0, f1, … feature names.
importanceType of importance to plot.
labelLabel of graph.
titleTitle of graph.
xAxisLabelLabel of X-axis.
yAxisLabelLabel of Y-axis.
maxNumberOfFeaturesMaximum number of top features displayed on plot. If None, all features will be displayed.
graphOrientationOrientaton of ploted graph.
enableGridurn the axes grids on or off.
sizeSize of ploted graph.
rendererRenderer to use.
-
train(iterations:startIteration: trainingData: objectiveFunction: evaluationData: evaluationFunction: beforeIteration: callbacks: afterIteration: ) Train booster.
Declaration
Swift
public func train( iterations: Int, startIteration: Int? = nil, trainingData: Data, objectiveFunction: ObjectiveFunction? = nil, evaluationData: [Data] = [], evaluationFunction: EvaluationFunction? = nil, beforeIteration: BeforeIteration = DefaultBeforeIteration, callbacks: [Callback] = [], afterIteration: AfterIteration = DefaultAfterIteration ) throwsParameters
iterationsNumber of training iterations, but training can be stopped early.
startIterationN. of starting iteration.
trainingDataData to train on.
evaluationDataData to evaluate on, if provided.
evaluationFunctionCustom evaluation function.
beforeIterationCallback called before each iteration.
callbacksArray of callbacks called at each iteration.
afterIterationCallback called after each iteration.
View on GitHub
Booster Class Reference