October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Machine Learning with C++: Build Classifiers with dlib

A practical guide to classification with dlib in C++: train a binary SVM, scale features, build multiclass models with one-vs-one or one-vs-all, and evaluate them correctly.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes—you can train binary and multiclass classifiers entirely in C++ with dlib. Start with dlib’s svm_c_trainer for a two-class support-vector machine, then wrap a binary trainer with one-vs-one or one-vs-all machinery for multiple classes. Use scaled features, validate on data not used for training, and inspect a confusion matrix instead of trusting a single accuracy number.

What dlib provides for classification

dlib is a modular C++ toolkit that includes supervised-learning algorithms, support-vector machines (SVMs), feature representations, and multiclass utilities. Its machine-learning toolkit is described in Davis E. King’s 2009 paper, DLIB-ML: A Machine Learning Toolkit (Journal of Machine Learning Research, volume 10, pages 1755–1758).

The examples below use dlib sample vectors. A sample is a fixed-length numeric feature vector; its label identifies the class. The quality of those features usually matters more than changing a kernel.

Install dlib and build an example

The official examples use CMake and a compiler with C++14 support. From a dlib source checkout:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
cd examples
mkdir build
cd build
cmake ..
cmake --build . --config Release

On platforms where you use vcpkg, the project README documents vcpkg install dlib. Package-manager versions and integration details can change, so check the package metadata used by your toolchain.

dlib 20.0, released May 27, 2025, added auto_train_multiclass_svm_linear_classifier(), which searches for linear-SVM settings automatically. Use it when a linear model is appropriate and you want dlib to select settings rather than hand-tuning them.

Train a binary SVM with svm_c_trainer

svm_c_trainer is dlib’s binary C-SVM trainer and uses sequential minimal optimization (SMO). It expects a binary-classification problem: every training label must identify one of two sides of the boundary. In the usual representation, labels are +1 and -1; do not pass arbitrary multiclass IDs such as 0, 1, and 2 directly.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Minimal two-class example

#include <dlib/svm_threaded.h>
#include <dlib/matrix.h>
#include <iostream>
#include <vector>

int main() {
    using sample_type = dlib::matrix<double, 2, 1>;
    using kernel_type = dlib::linear_kernel<sample_type>;

    std::vector<sample_type> samples;
    std::vector<double> labels;

    sample_type a, b, c, d;
    a = 2, 2;   b = 3, 2;       // positive class
    c = -2, -1; d = -3, -2;    // negative class
    samples = {a, b, c, d};
    labels  = {+1, +1, -1, -1};

    dlib::svm_c_trainer<kernel_type> trainer;
    trainer.set_c(10.0);
    dlib::decision_function<kernel_type> df = trainer.train(samples, labels);

    sample_type test;
    test = 1, 1;
    const double score = df(test);
    std::cout << (score > 0 ? "positive" : "negative")
              << " (decision score: " << score << ")n";
}

The returned decision function produces a real-valued score. Its sign determines the predicted side: a positive score is the class represented by +1, and a negative score is the class represented by -1. The distance from zero is useful as a confidence-like margin, but it is not automatically a calibrated probability.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose features, labels, and hyperparameters carefully

  • Keep dimensions consistent. Every sample must have the same number of features as the sample type.
  • Scale numeric features. Standardizing each feature using statistics computed on the training split prevents a large-unit feature from dominating a kernel or dot product. Apply the same saved transformation to validation and production data.
  • Encode exactly two classes. Map application labels to +1 and -1 for the binary trainer, retaining the mapping for predictions.
  • Tune C on validation data. A larger C penalizes training errors more heavily and can overfit noisy data; a smaller C allows a wider-margin model with more training violations.
  • Match the kernel to the data. A linear kernel is fast and compact when classes are close to linearly separable. Nonlinear kernels can model curved boundaries but generally increase training cost and make scaling more important.

Turn binary models into a multiclass classifier

For N classes, dlib can build a multiclass classifier from a binary trainer. The two standard strategies differ in how many binary models they train and how predictions are combined.

Strategy Binary models Prediction rule Practical considerations
One-vs-one N*(N-1)/2 Each pair of classes votes; the class with the most votes wins. Each model sees only two classes, which can simplify boundaries. Training and storage grow quadratically with the number of classes, while pairwise errors are easy to inspect.
One-vs-all N One classifier scores each class against all other classes; the strongest score wins. Fewer models than one-vs-one, but each classifier faces class imbalance and a more heterogeneous negative set. Per-class scores and errors are useful diagnostics.

One-vs-one in dlib

Use one_vs_one_trainer when pairwise separation is attractive or when you want models whose training data is limited to a pair of classes. The wrapper accepts a binary trainer type and combines the resulting pairwise decisions by voting. The exact template aliases depend on the sample and trainer types in your dlib version; the pattern is:

Rank #3
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
using sample_type = dlib::matrix<double, 2, 1>;
using binary_trainer = dlib::svm_c_trainer<dlib::linear_kernel<sample_type>>;
using multiclass_trainer = dlib::one_vs_one_trainer<binary_trainer>;

// Configure the binary trainer, supply samples with class IDs,
// then train the multiclass wrapper according to the dlib headers
// for your installed release.

Unlike the binary SVM example, multiclass training uses application class IDs (for example, 0, 1, and 2). The wrapper creates the required binary labelings internally.

One-vs-all in dlib

one_vs_all_trainer trains one binary classifier per class. For class k, that classifier treats k as positive and every other class as negative, then the wrapper selects the class with the best output. This can be substantially cheaper than one-vs-one for many classes, but inspect class-specific recall because a rare class may be overwhelmed by its larger negative pool.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Automatic linear multiclass training in dlib 20.0

In dlib 20.0 (released May 27, 2025), auto_train_multiclass_svm_linear_classifier() searches for linear-SVM settings automatically. It is a useful starting point for linearly separable, high-dimensional features, but it does not remove the need for a held-out evaluation, feature preprocessing, or an application-specific error analysis.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate with held-out data and a confusion matrix

Training accuracy measures how well the model fits examples it has already seen. Split data before fitting preprocessing parameters or the model, reserve a test set, and report errors by class. For limited datasets, use cross-validation; dlib’s API includes cross_validate_multiclass_trainer for multiclass validation.

  1. Shuffle data with a recorded seed, then create stratified training and test partitions so every important class appears in both when possible.
  2. Compute scaling statistics only from the training partition and apply that transformation unchanged to validation and test samples.
  3. Train the binary or multiclass model on the training partition.
  4. Predict every test sample and fill a confusion matrix: rows are actual classes and columns are predicted classes (or state the opposite convention explicitly).
  5. Calculate per-class precision, recall, and error counts. A single overall accuracy can hide a class that is consistently misclassified.

The official multiclass example uses three geometric classes to demonstrate API mechanics. It is a teaching example, not a benchmark for production accuracy, latency, or memory use.

Diagnose common failures

Training rejects the labels

Check that a binary trainer receives exactly two label values and that the sample and label vectors have equal lengths. Convert external labels to the required binary encoding before calling train().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Predictions are unstable or one class dominates

Inspect feature scales, class counts, and the confusion matrix. Standardize features, choose C and kernel parameters using validation data, and consider one-vs-one when one-vs-all negatives create severe imbalance.

The model performs well in training but poorly on new data

Reduce leakage, evaluate on untouched data, and retune C or kernel parameters. Keep the complete preprocessing pipeline—including feature order and scaling statistics—with the serialized model.

The multiclass build does not compile

Confirm that your installed dlib headers match the example’s API, use a C++14-capable compiler, and inspect the trainer template aliases in that release. dlib’s examples and API headers are the authoritative reference for exact wrapper signatures.

Choosing a strategy

  • Choose one-vs-one when pairwise boundaries are natural, class-specific diagnostics matter, or the number of classes is modest.
  • Choose one-vs-all when you need only N models, can manage class imbalance, and want a straightforward per-class scoring setup.
  • Choose a linear model for large, sparse, or already well-engineered feature vectors; consider nonlinear kernels only when validation demonstrates a meaningful improvement.
  • Use dlib 20.0’s automatic linear multiclass routine as a tuning baseline, not as a substitute for proper data splitting and error analysis.

Further reading

For the mathematical background behind SVMs, regularization, optimization, and kernels, dlib’s reading list recommends Learning with Kernels: Support Vector Machines, Regularization, Optimization, and Beyond. The canonical dlib machine-learning citation is Davis E. King’s 2009 JMLR article, DLIB-ML: A Machine Learning Toolkit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can dlib’s svm_c_trainer train three or more classes directly?

No. It is a binary C-SVM trainer. Use a multiclass wrapper such as one-vs-one or one-vs-all, or use dlib’s automatic linear multiclass SVM routine in dlib 20.0.

Does a positive dlib SVM score mean a probability?

No. The decision function’s sign selects a class; the magnitude is a margin-like score and is not automatically calibrated as a probability.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.