简体   繁体   中英

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

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.

Have a look into avenues to store the model in an interoperable format like ONNX or PMML, which might be readable by a library from a completely different environment.

Whether this works for the case of a RandomForestClassifier I do not know, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM