Search code examples
pythonxmlpython-3.xpredictionpmml

Use PMML models in Python


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.


Solution

  • 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).