Chapter 8. Saving your model as an independent Python function

Turn your data model into an independent Python function so that you can run it outside your notebook server environment and use it in intelligent applications.

Prerequisites

  • You have access to the JupyterLab interface.
  • You have developed a prediction model in a Jupyter notebook.
  • Your Jupyter notebook is saved in a Git repository that was created from the Red Hat OpenShift Data Science sample S2I application repositories.

Procedure

  1. In JupyterLab, create a new prediction.py file.
  2. Edit the prediction.py file to define a predict function based on the prediction model in your Jupyter notebook.

    • Include only the code required to make the prediction. For example, you do not need to import libraries that only related to rendering plots in your Jupyter notebook.
    • If any new packages are required to run your prediction, update the contents of the requirements.txt file and run pip install -r requirements.txt to install the new packages.
  3. Test that you can run the independent Python function from your notebook by calling the function in a new notebook cell, for example:

    from prediction import predict
      predict(data)

Verification

  • The predict function runs correctly and returns the expected output when called from the notebook cell.

8.1. Installing Python packages on your notebook server

You can install Python packages that are not part of the default notebook server image by adding the package and the version to a requirements.txt file and then running the pip install command in a notebook cell.

Note

You can also install packages directly, but Red Hat recommends using a requirements.txt file so that it is easier to deploy your model later.

Prerequisites

  • Log in to JupyterHub and open a notebook.

Procedure

  1. Create a new text file using one of the following methods:

    • Click + to open a new launcher and click Text file.
    • Click FileNewText File.
  2. Rename the text file to requirements.txt.

    1. Right-click on the name of the file and click Rename Text. The Rename File dialog opens.
    2. Enter requirements.txt in the New Name field and click Rename.
  3. Add the packages to install to the requirements.txt file.

    altair

    You can specify the exact version to install by using the == (equal to) operator, for example:

    altair==4.1.0

    To install multiple packages at the same time, place each package on a separate line.

  4. Install the packages in requirements.txt to your server using a notebook cell.

    1. Create a new cell in your notebook and enter the following command.

      !pip install -r requirements.txt
    2. Run the cell by pressing Shift and Enter.
    Important

    This installs the package on your notebook server, but you must still run the import directive in a code cell to use the package in your code.

    import altair

Verification