How to save a trained machine learning model in python and load it in C++ for prediction?

Viewed 1218

This code will help you to get the model.pkl file that I need to open in C++

# Load libraries
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
from sklearn.externals import joblib

# Load data
iris = datasets.load_iris()
features = iris.data
target = iris.target

# Create decision tree classifer object
classifer = RandomForestClassifier()

# Train model
model = classifer.fit(features, target)

# Save the model as pickle file
joblib.dump(model, "model.pkl")

So, from the above code, we got model.pkl file, which is a machine learning model (random forest classifier). Now I need to read model.pkl file using C++ and test the model using sample data (new_observation). I can do it in python as follows:

from sklearn.externals import joblib
# Load model from file 
classifer = joblib.load("model.pkl")
# Create new observation
new_observation = [[ 5.2,  3.2,  1.1,  0.1]]
# Predict observation's class
classifer.predict(new_observation)

But need to do this using C++, basically, I need equivalent code of the above 4 lines (python to C++) which I don't know.

0 Answers
Related