Use PMML models in Python

10,357

Solution 1

After some research I found the solution to this: the 'openscoring' library.

Using it is very simple:

import subprocess
from openscoring import Openscoring
import numpy as np

p = subprocess.Popen('java -jar openscoring-server-executable-1.4.3.jar',
             shell=True)

os = Openscoring("http://localhost:8080/openscoring")

# Deploying a PMML document DecisionTreeIris.pmml as an Iris model:   
os.deployFile("Iris", "DecisionTreeIris.pmml")

# Evaluating the Iris model with a data record:
arguments = {
    "Sepal_Length" : 5.1,
    "Sepal_Width" : 3.5,
    "Petal_Length" : 1.4,
    "Petal_Width" : 0.2
}
result = os.evaluate("Iris", arguments)
print(result)

This returns the value of the target variable in a dictionary. There is no need to go outside of Python to use PMML models anymore (you just have to run the server with Java, which can be done with Python as well as I showed above).

Solution 2

You could use PyPMML to apply PMML in Python, for example:

from pypmml import Model

model = Model.fromFile('DecisionTreeIris.pmml')
result = model.predict({
    "Sepal_Length" : 5.1,
    "Sepal_Width" : 3.5,
    "Petal_Length" : 1.4,
    "Petal_Width" : 0.2
})

For more info about other PMML libraries, be free to see: https://github.com/autodeployai

Share:
10,357
Tendero
Author by

Tendero

Electronic Engineer from University of Buenos Aires.

Updated on June 05, 2022

Comments

  • Tendero
    Tendero almost 2 years

    I've found many topics related to this on the Internet but I could find no solutions.

    Suppose I want to download any PMML model from this examples list, and run them in Python (Python 3 preferably). Is there any way to do this?

    I'm looking for a way to import a PMML that was deployed OUTSIDE Python and import it to use it with this language.