LGPL
Machine Learning
Random Forest
C++
Licensing

LGPL Machine Learning with Random Forest - C

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Several LGPL-licensed C++ libraries provide Random Forest implementations that you can use in commercial software without open-sourcing your own code. The key libraries are Shark ML (LGPL), dlib (Boost License), mlpack (BSD), and OpenCV's ml module (Apache 2.0). Under the LGPL, you can link against the library dynamically without making your application open-source — you only need to release modifications to the LGPL library itself. This makes LGPL libraries suitable for proprietary machine learning products that need Random Forest classification or regression.

Shark ML (LGPL-3.0)

cpp
1// Install: https://github.com/Shark-ML/Shark
2// License: LGPL-3.0
3
4#include <shark/Algorithms/Trainers/RFTrainer.h>
5#include <shark/Data/Csv.h>
6#include <shark/Models/Trees/RFClassifier.h>
7
8using namespace shark;
9
10int main() {
11    // Load data
12    ClassificationDataset data;
13    importCSV(data, "iris.csv", LAST_COLUMN);
14
15    // Split into train/test
16    ClassificationDataset test = splitAtElement(data, 120);
17
18    // Train Random Forest
19    RFTrainer<unsigned int> trainer;
20    trainer.setNTrees(100);
21    trainer.setMinSplit(5);
22
23    RFClassifier<unsigned int> model;
24    trainer.train(model, data);
25
26    // Predict
27    Data<unsigned int> predictions = model(test.inputs());
28
29    // Evaluate
30    ZeroOneLoss<unsigned int> loss;
31    double error = loss.eval(test.labels(), predictions);
32    std::cout << "Error rate: " << error << std::endl;
33
34    // Feature importance
35    auto importance = model.featureImportances();
36    for (size_t i = 0; i < importance.size(); i++) {
37        std::cout << "Feature " << i << ": " << importance[i] << std::endl;
38    }
39
40    return 0;
41}

OpenCV ml Module (Apache 2.0)

cpp
1// OpenCV's ml module is Apache 2.0 (more permissive than LGPL)
2#include <opencv2/ml.hpp>
3#include <opencv2/core.hpp>
4#include <iostream>
5
6using namespace cv;
7using namespace cv::ml;
8
9int main() {
10    // Prepare training data
11    Mat trainData = (Mat_<float>(6, 2) <<
12        1.0, 2.0,
13        2.0, 3.0,
14        3.0, 3.0,
15        6.0, 5.0,
16        7.0, 8.0,
17        8.0, 8.0);
18
19    Mat labels = (Mat_<int>(6, 1) << 0, 0, 0, 1, 1, 1);
20
21    // Create and configure Random Forest
22    Ptr<RTrees> rf = RTrees::create();
23    rf->setMaxDepth(10);
24    rf->setMinSampleCount(2);
25    rf->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100, 0.01));
26
27    // Train
28    rf->train(trainData, ROW_SAMPLE, labels);
29
30    // Predict
31    Mat testSample = (Mat_<float>(1, 2) << 5.0, 6.0);
32    float prediction = rf->predict(testSample);
33    std::cout << "Prediction: " << prediction << std::endl;
34
35    // Feature importance
36    Mat importance = rf->getVarImportance();
37    std::cout << "Feature importance: " << importance << std::endl;
38
39    // Save and load model
40    rf->save("random_forest.xml");
41    Ptr<RTrees> loaded = RTrees::load("random_forest.xml");
42
43    return 0;
44}

mlpack (BSD License)

cpp
1// mlpack is BSD-3 licensed (very permissive)
2#include <mlpack/methods/random_forest/random_forest.hpp>
3#include <mlpack/core.hpp>
4
5using namespace mlpack;
6
7int main() {
8    // Load data
9    arma::mat data;
10    data::Load("dataset.csv", data, true);
11
12    // Separate features and labels
13    arma::Row<size_t> labels = arma::conv_to<arma::Row<size_t>>::from(
14        data.row(data.n_rows - 1));
15    data.shed_row(data.n_rows - 1);
16
17    // Train Random Forest
18    RandomForest<> rf(data, labels,
19                      2,     // Number of classes
20                      100,   // Number of trees
21                      5,     // Minimum leaf size
22                      0,     // Maximum depth (0 = unlimited)
23                      1e-7); // Minimum gain split
24
25    // Predict
26    arma::Row<size_t> predictions;
27    arma::mat probabilities;
28    rf.Classify(data, predictions, probabilities);
29
30    // Accuracy
31    size_t correct = arma::accu(predictions == labels);
32    std::cout << "Accuracy: " << (double)correct / labels.n_elem << std::endl;
33
34    return 0;
35}

LGPL License Implications

 
1LGPL Requirements for your application:
2┌─────────────────────────────────────────────┐
3Your Proprietary Application4 (closed source, any license)5│                                             │
6Uses LGPL library via dynamic linking     │
7│   ┌───────────────────────────────────┐     │
8│   │ LGPL Library (e.g., Shark ML)     │     │
9│   │ - Must provide source for this    │     │
10│   │ - Must allow relinking            │     │
11│   │ - Must include LGPL notice        │     │
12│   └───────────────────────────────────┘     │
13│                                             │
14You do NOT need to open-source your app     │
15as long as you dynamically link             │
16└─────────────────────────────────────────────┘

Key LGPL compliance rules:

  • Distribute the LGPL library source (or a link to it)
  • Allow users to replace the LGPL library with a modified version (use dynamic linking)
  • Include the LGPL license text
  • If you modify the LGPL library itself, release those modifications under LGPL
  • Your application code remains proprietary

Building with CMake

cmake
1# CMakeLists.txt for Shark ML
2cmake_minimum_required(VERSION 3.14)
3project(RandomForestApp)
4
5find_package(Shark REQUIRED)
6
7add_executable(rf_classifier main.cpp)
8target_link_libraries(rf_classifier ${SHARK_LIBRARIES})
9target_include_directories(rf_classifier PRIVATE ${SHARK_INCLUDE_DIRS})
10
11# For OpenCV
12find_package(OpenCV REQUIRED)
13target_link_libraries(rf_classifier ${OpenCV_LIBS})

License Comparison

LibraryLicenseCommercial UseMust Open Source Your CodeMust Release Library Modifications
Shark MLLGPL-3.0YesNo (dynamic link)Yes
OpenCV mlApache 2.0YesNoNo
mlpackBSD-3YesNoNo
dlibBoostYesNoNo
scikit-learnBSD-3YesNoNo

Common Pitfalls

  • Static linking an LGPL library into a proprietary binary: LGPL requires that users can replace the library with a modified version. Static linking makes this impossible without your source code. Either use dynamic linking (shared libraries) or release your application under a compatible open-source license.
  • Confusing LGPL with GPL: LGPL (Lesser GPL) allows proprietary applications to link against the library. GPL requires the entire application to be open-sourced. Check the exact license version — LGPL-2.1 and LGPL-3.0 have different requirements for linking.
  • Not distributing the LGPL license text: Even with dynamic linking, you must include the LGPL license text with your distribution and clearly state which components are LGPL. Failing to do so violates the license terms.
  • Modifying LGPL library source without releasing changes: If you fix a bug or add a feature to the LGPL library itself, you must make those modifications available under LGPL. Changes to your own application code remain proprietary.
  • Assuming all "open source" ML libraries have the same license: Libraries range from public domain to AGPL. Always check the specific license before integrating. Some licenses (AGPL) require open-sourcing your application even for server-side use — not just distribution.

Summary

  • Use Shark ML (LGPL), OpenCV ml (Apache), or mlpack (BSD) for Random Forest in C++
  • LGPL allows commercial use without open-sourcing your code — link dynamically
  • If you modify the LGPL library itself, release those modifications under LGPL
  • OpenCV, mlpack, and dlib use more permissive licenses with fewer restrictions
  • Always verify the exact license version and compliance requirements before deployment

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.