A Swift interface for XGBoost


https://github.com/ddxgz/XGBoost.swift/workflows/macOS/badge.svg https://github.com/ddxgz/XGBoost.swift/workflows/Ubuntu/badge.svg

A Swift interface for XGBoost.

The current interface is wrapping around the C API of XGBoost, tries to conform to the Python API. Document see docs.

If you run into any problem, please file an issue or even better a pull request.

Installation and dependency library


You can follow XGBoost document for installation or build library. Develop and tested under macOS 10.15 with brew install xgboost. The C header file and library are located through pkg-config, it should work directly. Otherwise, place an pkg-config file as /usr/local/lib/pkgconfig/xgboost.pc with content:


Name: xgboost
Description: XGBoost
Version: 1.1.0
Cflags: -I${includedir}
Libs: -L${libdir} -lxgboost

Please read through the following links for more configuration detail.


Ubuntu is tested by using Swift’s docker image, the latest version is Ubuntu18.04 for now. Please follow XGBoost document for installation or build library. Or you can check the Dockerfile `Dockerfile_test_ubuntu` that used for testing.

Swift package manager

It evovles fastly, please constantly check the version.

.package(url: "https://github.com/ddxgz/XGBoost.swift.git", from: "0.6.0")


Still in early development, use with caution. See more examples in docs.

let train = try DMatrix(fromFile: "data/agaricus.txt.train")
let test = try DMatrix(fromFile: "data/agaricus.txt.test")

let params = [
    ("objective", "binary:logistic"),
    ("max_depth", "9"),
    ("eval_metric", "auc"),
    ("eval_metric", "aucpr"),
// Construct booster while boosting
let bst = try xgboost(params: params, data: train, numRound: 10)

let pred = bst.predict(data: test)

let cvResult = try xgboostCV(data: train, numRound: 10)

// Use callbacks
// The `SimplePrintEvalution` and `EarlyStop` are builtin simple example of callback.
// You can also define a custom callback that conforms to XGBCallback protocol, see
// more in the document of protocol.
let callbacks = [SimplePrintEvalution(period: 5),
                 EarlyStop(stoppingRounds: 5)]

let bst = try xgboost(data: train, numRound: 10, evalSet: [(test, "test")],
                        callbacks: callbacks)

// save and load model as binary
let modelBin = "bst.bin"
try bst.saveModel(toFile: modelBin)
let bstLoaded = try xgboost(data: train, numRound: 0, modelFile: modelBin)

// save and load model as json
let modelJson = "bst.json"
bst.saveModel(toFile: modelJson) 
let bstJsonLoaded = try xgboost(data: train, numRound: 0, modelFile: modelJson)

// save model config
try bst.saveConfig(toFile: "config.json")



  • Swift Tools 5.2.0
View More Packages from this Author


Last updated: Wed Jun 29 2022 23:31:22 GMT-0500 (GMT-05:00)