On this page:
<r15-require>
<r15-provide>
<r15-run>
<*>

2.17 Slicing and binary serialization🔗ℹ

dmatrix-slice selects a subset of rows (by index, in the order given), and dmatrix-save-binary! writes a DMatrix to XGBoost’s fast binary format that make-dmatrix-from-uri reads back. This example slices rows '(2 0) from a 3×2 matrix — reordering them — then saves and reloads the slice.

(require ffi/vector
         racket/file
         xgboost)

(provide run-example)

(define (run-example)
  (define dm
    (make-dmatrix (f32vector 1.0 2.0  3.0 4.0  5.0 6.0)
                  #:nrow 3 #:ncol 2 #:missing -1.0))
  (define sliced (dmatrix-slice dm '(2 0)))
  (define sliced-values (dmatrix->list sliced))
  (define tmp (make-temporary-file "xgboost-dmatrix-~a.buffer"))
  (when (file-exists? tmp) (delete-file tmp))
  (define loaded-summary
    (dynamic-wind
      void
      (lambda ()
        (dmatrix-save-binary! sliced tmp)
        (define loaded (make-dmatrix-from-uri tmp))
        (hash 'rows (dmatrix-rows loaded) 'cols (dmatrix-cols loaded)
              'values (dmatrix->list loaded)))
      (lambda () (when (file-exists? tmp) (delete-file tmp)))))
  (hash 'sliced-values sliced-values 'loaded-summary loaded-summary))

The harness "test/15-dmatrix-slicing-binary.rkt" prints the sliced values and the reloaded shape, and asserts both equal the expected reordered rows '((5.0 6.0) (1.0 2.0)).

<*> ::=