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)?
    ) throws

    Parameters

    call

    Function 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

    booster

    BoosterHandle pointer.

  • Initialize Booster from buffer.

    Declaration

    Swift

    public convenience init(
        buffer: BufferModel
    ) throws

    Parameters

    buffer

    Model serialized as buffer.

  • Initialize new Booster.

    Declaration

    Swift

    public convenience init(
        with data: [Data] = [],
        from path: String? = nil,
        config: String? = nil,
        parameters: [Parameter] = [],
        validateParameters: Bool = true
    ) throws

    Parameters

    with

    Data that will be cached.

    from

    Loads model from path.

    config

    Loads model from config.

    parameters

    Array of parameters to be set.

    validateParameters

    If 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 -> String

    Return 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 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

    from

    Data to predict from.

    outputMargin

    Whether to output the raw untransformed margin value.

    treeLimit

    Limit number of trees in the prediction. Zero means use all trees.

    predictionLeaf

    Each record indicating the predicted leaf index of each sample in each tree.

    predictionContributions

    Each record indicating the feature contributions (SHAP values) for that prediction.

    approximateContributions

    Approximate the contributions of each feature.

    predictionInteractions

    Indicate the SHAP interaction values for each pair of features.

    training

    Whether the prediction will be used for traning.

    validateFeatures

    Validate booster and data features.

  • 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 -> Float

    Parameters

    features

    Features to base prediction at.

    outputMargin

    Whether to output the raw untransformed margin value.

    treeLimit

    Limit number of trees in the prediction. Zero means use all trees.

    predictionLeaf

    Each record indicating the predicted leaf index of each sample in each tree.

    predictionContributions

    Each record indicating the feature contributions (SHAP values) for that prediction.

    approximateContributions

    Approximate the contributions of each feature.

    predictionInteractions

    Indicate the SHAP interaction values for each pair of features.

    training

    Whether the prediction will be used for traning.

    missingValue

    Value in features representing missing values.

  • Declaration

    Swift

    public func serialized() throws -> SerializedBuffer

    Return Value

    Everything states in buffer.

  • Saves modes into file.

    Declaration

    Swift

    public func save(
        to path: String
    ) throws

    Parameters

    to

    Path to output file.

  • Declaration

    Swift

    public func raw() throws -> RawModel

    Return 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 -> String

    Parameters

    features

    Array of features.

    featureMap

    Name of the file containing feature map.

    withStatistics

    Controls whether the split statistics are output.

    format

    Desired 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 dumped method 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

    features

    Array of features, you can override ones stored in self.features with this.

    featureMap

    Name of the file containing feature map.

    withStatistics

    Controls whether the split statistics are output.

    format

    Desired 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

    featureMap

    Path to the feature map.

    importance

    Type 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
    ) throws

    Parameters

    model

    Buffer to load from.

  • Loads model from file.

    Declaration

    Swift

    public func load(
        model path: String
    ) throws

    Parameters

    model

    Path of file to load model from.

  • Loads model from config.

    Declaration

    Swift

    public func load(
        config: String
    ) throws

    Parameters

    model

    Config 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 -> Int

    Return Value

    The output version of the model.

  • Get attribute string from the Booster.

    Declaration

    Swift

    public func attribute(
        name: String
    ) throws -> String?

    Parameters

    name

    Name 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
    ) throws

    Parameters

    attribute

    Name of attribute.

    value

    Value of attribute.

  • Set string parameter.

    Declaration

    Swift

    public func set(
        parameter: String,
        value: String
    ) throws

    Parameters

    parameter

    Name of parameter.

    value

    Value of parameter.

  • Update for one iteration, with objective function calculated internally.

    Declaration

    Swift

    public func update(
        iteration: Int,
        data: Data,
        validateFeatures: Bool = true
    ) throws

    Parameters

    iteration

    Current iteration number.

    data

    Training data.

    validateFeatures

    Whether to validate features.

  • Update for one iteration with custom objective.

    Declaration

    Swift

    public func update(
        data: Data,
        objective: ObjectiveFunction,
        validateFeatures: Bool = true
    ) throws

    Parameters

    data

    Training data.

    objective

    Objective function returning gradient and hessian.

    validateFeatures

    Whether 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
    ) throws

    Parameters

    data

    Training data.

    gradient

    The first order of gradient.

    hessian

    The second order of gradient.

    validateFeatures

    Whether to validate features.

  • Evaluate array of data.

    Declaration

    Swift

    public func evaluate(
        iteration: Int,
        data: [Data],
        function: EvaluationFunction? = nil
    ) throws -> [String: [String: String]]

    Parameters

    iteration

    Current iteration.

    data

    Data to evaluate.

    function

    Custom 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

    iteration

    Current iteration.

    data

    Data to evaluate.

    function

    Custom function for evaluation.

    Return Value

    Dictionary in format [data_name: [eval_name: eval_value]]

  • Validate features.

    Declaration

    Swift

    public func validate(
        features: [Feature]
    ) throws

    Parameters

    features

    Features to validate.

  • Validate features.

    Declaration

    Swift

    public func validate(
        data: DMatrix
    ) throws

    Parameters

    data

    Data which features will be validated.

  • Validate features.

    Declaration

    Swift

    public func validate(
        data: [DMatrix]
    ) throws

    Parameters

    data

    Array of data which features will be validated.

  • 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()
    ) throws

    Parameters

    to

    File where graph will be saved, .svg extension will be added if rendered remains SVGRenderer.

    featureMap

    Path to the feature map, if provided, replaces default f0, f1, … feature names.

    importance

    Type of importance to plot.

    label

    Label of graph.

    title

    Title of graph.

    xAxisLabel

    Label of X-axis.

    yAxisLabel

    Label of Y-axis.

    maxNumberOfFeatures

    Maximum number of top features displayed on plot. If None, all features will be displayed.

    graphOrientation

    Orientaton of ploted graph.

    enableGrid

    urn the axes grids on or off.

    size

    Size of ploted graph.

    renderer

    Renderer to use.

  • 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
    ) throws

    Parameters

    iterations

    Number of training iterations, but training can be stopped early.

    startIteration

    N. of starting iteration.

    trainingData

    Data to train on.

    evaluationData

    Data to evaluate on, if provided.

    evaluationFunction

    Custom evaluation function.

    beforeIteration

    Callback called before each iteration.

    callbacks

    Array of callbacks called at each iteration.

    afterIteration

    Callback called after each iteration.