Building Data Products in Python

Building Data Products in Python

2020, Mar 17    

Building data products more closely resembles a blood hound on a trail than a pilot charting a transcontinental flight pattern. I emphasize data products because it is far more encompassing than data analysis or data science and pertains to anyone attempting to make an impact with data. Portability is a concept that extends beyond analysis, software development, or even just programming in general. At the end of the day those interesting and chaotic insights you generate will fall on deaf ears if people are lost in reproducing your work. When your sole focus is the results and not the process, you lose focus on all the intermediate things that need to be in place to support productionalized products.

In general when it comes to working with data, tracking libraries and versions, commenting on code, organizing notebooks, and making your product portable are all things you should keep in the back of your mind if you are going to expend any energy into building something. In this respect, Data Scientists and Analysts have a lot to learn from Software Developers, and this guide is an attempt to automate a great deal of that “not so fun” stuff so that you can spend your time making an impact with data.

Getting Started with Anaconda

If you followed my previous post Setting Up A Data Science Environment on OSX, then you should have a working anaconda installation with conda being in your path. You can test this by running:

conda config --describe

If you peruse that output you may see something like:

# # auto_activate_base (bool)
# #   Automatically activate the base environment during shell
# #   initialization.
# #
auto_activate_base: true

This initializes the base environment when you open your shell because of what conda init added to our .zshrc file. Mine looks like this:

(base) trevor@macbookpro ~ %

The base environment is a conda environment that has all the basics you will need to get started writing Python. If you need a primer on virtual environments Real Python has a great one here.

It is not a good idea to develop everything in the base environment! I personally prefer to leave mine completely unmolested except to update all the packages and conda channels when a new version of python is released. This gives me a nice clean slate to revert back to if a project environment gets out of hand, without having to reinstall the “essentials”. Additionally, the way you write code and the packages you use will change over time and going back to something written 6 months ago will most likely not run if you have been using that environment to develop other things. Or worse, it will run but your analysis will be completely wrong because nulls are handled differently in one of your updated packages that you didn’t install, but is a dependency on some other package you updated because you needed to build an AI companion and she just had to have pocketsphinx 0.1.15 so she could talk to you even if you aren’t connected to the internet…

Anyways, don’t develop in your base environment. Still not sold, then go here maybe someone more experience than I can convince you. If your base environment is automatically activated during the shell initialization (Plain English: Do you see (base) at the beginning of the line when you open your command prompt or terminal?), then run the following:

# Deactivate the base environment:
conda deactivate
# Turn off the auto activation of base
conda config --set auto_activate_base false
# Verify it is off by checking auto_activate_base: true is commented out:
conda config --describe

If you still aren’t certain it is turned off quit your shell and then relaunch it. Mine now looks like this:

trevor@macbookpro ~ %

Building Our First Data Science Environment

I have been using Anaconda and Conda synonymously throughout this point, but that is actually not correct.

Anaconda is a free and open-source distribution of the Python and R programming languages for scientific computing, that aims to simplify package management and deployment.

Keep that in mind for a second, but the two most popular tools for setting up environments in python in order are:

  • PIP
    • PIP -> “Pip Installs Packages” is a recursively named Python package manager that works with virtualenv, which is a tool for creating isolated environments
  • Conda
    • Conda is an environment and package manager used by Anaconda, and it can replace pipenv and pip in Python.

I use Conda because it has a clear file structure with transparent file management, it contains almost every package I could ever need and supports installing others via pip, but it can also be used to manage environments in both Python and R. The following is how I build a conda environments when starting a new project, but you can read more in the docs. Let’s build a new environment called hello_world with python 3.7:

conda create -n hello_world python=3.7 jupyter

Make sure to hit yes when prompted and wait for the install. Once done you should see something like this:

# To activate this environment, use
#
#     $ conda activate hello_world
#
# To deactivate an active environment, use
#
#     $ conda deactivate

If we want to see all environments currently installed run conda info --envs. To activate the hello_world environment run:

conda activate hello_world

Now we are ready to launch a jupyter notebook! Assuming you activated hello_world in the previous step you can do this by running:

jupyter notebook

This launches a browser file system that will allow basic file management as well as create new Python and R scripts.

Creating our Project

This is that part where I said we tend to be off to the races and best practices and such fall by the wayside. In Setting Up A Data Science Environment on OSX, I showed how to install and do a basic configuration of Git. You could create a notebook and start writing Python immediately, but it would be wise to set up a local repository to control versioning of your code.

Let’s create a repository locally for our hello_world project. Relaunch a new shell session and from your home directory:

# Change into the Documents directory
cd Documents
# Make a new 'folder' called HelloWorld_Repo
mkdir HelloWorld_Repo

If you refresh the browser tab where Jupyter launched and then click into Documents you should see a folder called HelloWorld_Repo. Pretty neat huh? If you are on windows and using the command line to make directories and stuff is a bit daunting still, then create a folder in Documents how you normally would. Here is a guide if you need it.

Now we have a place to store files, but we still haven’t actually enabled Git yet. We do so by stepping into the HelloWorld_Repo and then running a command to initialize Git:

# Change from Home directory (aka ~) to Documents
trevor@macbookpro ~ % cd Documents
# Make the HelloWorld_Repo directory just like what was shown above
trevor@macbookpro Documents % mkdir HelloWorld_Repo
# Step into the HelloWorld_Repo directory
trevor@macbookpro Documents % cd HelloWorld_Repo
# Make the HelloWorld_Repo directory a local Git repository
trevor@macbookpro HelloWorld_Repo % git init

This is the first time I’ve shown how to navigate around our computer’s file system pay attention to how everything left of the % changes as we move around. You should only copy and paste everything to the right of the %.

I promise that took me way longer to explain than it does to just do it in real life. Any time you are about to start exploring data in a new way try to remember to initialize your project.

Writing a Python Script (Sort Of)

Time To Get To Work

If you go back to your browser and click into the HelloWorld_Repo folder, you will notice the notebook list is empty. That makes sense because we haven’t created anything yet. To create a notebook you click on the New dropdown and then select our environment name under the Notebook section. If you followed along to this point you will not see our environment listed. This is because Conda no longer automatically configures what is know as Kernels. You can read more about Kernels here. I took this as an opportunity to explain how to install additional packages. In this case the missing package is nb_conda_kernels. A lot of your job from here on out will be getting better at using Google and parsing through “fixes”. Hang in there and if you don’t know something just keep asking and looking and you will eventually find it. For now this one is on me, open a new terminal tab or cd to the home directory:

# Make sure our target environment 'hello_world' is activated
conda activate hello_world
# Install nb_conda_kernels
conda install nb_conda_kernels
# Set the 'hello_world' environment to be on our jupyter notebook
python -m ipykernel install --user --name=hello_world

Now we can relaunch jupyter by activating the environment conda activate hello_world and the running jupyter notebook. I was able to find this solution by first Google “new environment not showing in jupyter” and then I looked for stack overflow and medium articles that addressed the issue I was having. I think this article summed it up best.

There's Our Repo

And there you have it our repo is there and can be used to create new notebooks. This will be important later when we create executable scripts automatically by just clicking save on our notebook. If we click on the hello_world pictured above a new tab will open with a Jupyter notebook called “Untitled”. Clicking on that we can change the notebook name. Additionally, we can see under the logout that the current active environment is our hello_world environment. Let’s change our notebook name to FirstPython.

Please take time to familiarize yourself with the layout of the notebook and how to navigate it. Here is a great write up of jupyter notebook basics.

Back? Great, let’s continue by completing the obligatory coding write of passage hello world! Click in the first cell and type:

print("Hello World!")

Now if you run the cell you will see Hello World! print out to the console.

Hello World!

Sure I know it isn’t particularly all that useful or exciting, but you now have at your disposal the means to cause all kinds of trouble and you don’t have to make me an accessory in the process. If you followed up to this point then you have covered everything needed to create and version control your data insights. Everything from here on out is completely optional, but necessary if you are going to deploy and share your results.

Productionalizing Your Python Script

Ok so now you have written something more interesting than hello world and you want to share that or you want to schedule this script to run or something what do you need to do? Well normally you would download the notebook as a python file so that it has a .py extension instead of the .ipynb. Oh and so it is written in interpretable Python. Change the permissions of that file using chmod and then edit the top of the file to include the path of the executable environment. Finally, you may set it up to run using chron or something like that. Technically, a notebook can be set up to accomplish all this, but I never found it to be straightforward. Rather than do all that we can automatically export the code from our jupyter notebooks into a vanilla Python after each save. Credit goes out to Max Masnick for writing

IPython and Jupyter Notebooks: Automatically Export .py and .html

I stumbled upon this guide while debugging something else and immediately knew it was an answer to a problem I didn’t even know I had. What he has in the article is a good base, but we are going to tweak it to function a little differently so that it will add the environment path to the beginning of the file, prevent the creation of a .py file if they are Untitled or contain “-Copy”, and also comment out the save html portion. Open your jupyter_notebook_config.py file, mine was at ~/.jupyter/jupyter_notebook_config.py:

atom ~/.jupyter/jupyter_notebook_config.py

This is your configuration file for jupyter notebook and there are a ton of things in here that can be tweaked. I may have to explore this further in the future, but for now we are going to write our own code to handle everything above:

# Based off of https://github.com/jupyter/notebook/blob/master/docs/source/extending/savehooks.rst

import io
import os
import sys
from notebook.utils import to_api_path

_script_exporter = None
_html_exporter = None


def script_post_save(model, os_path, contents_manager, **kwargs):
    """convert notebooks to Python script after save with nbconvert
    replaces ipython notebook --script
    """
    from nbconvert.exporters.script import ScriptExporter
    from nbconvert.exporters.html import HTMLExporter

    if model['type'] != 'notebook':
        return
    elif model['name'] == 'Untitled.ipynb':
        return
    elif "-Copy" in model['name']:
        return

    global _script_exporter
    if _script_exporter is None:
        _script_exporter = ScriptExporter(parent=contents_manager)
    log = contents_manager.log

    global _html_exporter
    if _html_exporter is None:
        _html_exporter = HTMLExporter(parent=contents_manager)
    log = contents_manager.log

    # save .py file
    base, ext = os.path.splitext(os_path)
    script, resources = _script_exporter.from_filename(os_path)
    script_fname = base + resources.get('output_extension', '.txt')
    log.info("Saving script /%s",
             to_api_path(script_fname, contents_manager.root_dir))
    with io.open(script_fname, 'w', encoding='utf-8') as f:
        f.write('#!' + sys.executable + '\n')
        f.write('\n'.join(script.split('\n')[2:]))

    # # save html
    # base, ext = os.path.splitext(os_path)
    # script, resources = _html_exporter.from_filename(os_path)
    # script_fname = base + resources.get('output_extension', '.txt')
    # log.info("Saving html /%s", to_api_path(script_fname, contents_manager.root_dir))
    # with io.open(script_fname, 'w', encoding='utf-8') as f:
    #     f.write(script)


c.FileContentsManager.post_save_hook = script_post_save

Look I could explain the code above line for line, but chances are if you could comprehend my explanation then you wouldn’t need me to explain it. Even if your jupyter_notebook_config.py was empty just add this to the end and let’s move on. Note this is a onetime setup so you shouldn’t have to fiddle with it ever again unless you want it to do something besides what we outlined above.

Hello World!

So now, when we hit save a copy of our notebook is converted to vanilla Python and given a .py extension. The top of the file gets the path to the environment we are using to edit the notebook #!/usr/local/anaconda3/envs/hello_world/bin/python. This can now be run from the command line and can even be set up for scheduling with something like chron. Open a new terminal window and don’t activate any conda environment. Run the following:

python ~/Documents/HelloWorld_Repo/FirstPython.py

We just evoked our hello_world environment to run what was a jupyter notebook. Take this a step further to demonstrate some quality of life things adding the code above did for us. Back in jupyter on the FirstPython notebook we can make a copy:

File > Make a Copy…

You should have a notebook open in a new tab that is titled FirstPython-Copy1. You can now click save until you pass out from exhaustion, but you will never see a FirstPython-Copy1.py appear in the your HelloWorld_Repo folder. The same thing happens if you create a new notebook and try to save it without renaming it.

Deploying Your Data Product

One last little bit of cleanup is to make your conda environment exportable, after all I did rant and rave about it at the beginning. I will show you two ways to do this.

Using Only Conda

# Activate the environment you want to share
conda activate hello_world
# Navigate to the directory containing our repository
cd ~/Documents/HelloWorld_Repo
# Finally save our build requirements to an environment.yml file
conda env export --no-builds | grep -v "prefix" > environment.yml

This creates an environment.yml file within our repository folder that can be used to recreate our current active environment name and everything if you navigate to where it is stored and run:

conda env create -f environment.yml

Another Way

Now it is actually common for people not to use conda as their environment manager, but you know we live to serve:

conda list -e > requirements.txt

This requirements.txt file essentially serves the same purpose as environment.yml. Now, you may wonder, “What if I am given a requirements.txt file will I have to use the same environment manager as the person who created it?”, and the answer is no. We can create a conda environment from requirements.txt generated by any number of environment managers:

conda create --name <env> --file requirements.txt

The only thing left to do from here is to determine where you want to deploy your code. I would recommend GitHub, and I will make a guide for the basics of GitHub and how to fix mistakes in repos, such as publishing your username and password not that I’ve ever done that or anything. For now see if you can follow this guide.

Parting Shots

Finally, writing this got me thinking what would be a good set of packages as a sort of vanilla data science install. This is a very nuanced question to answer but I pooled together guides like this one and this is what I came up with:

# Create a python 3.7 environment with jupyter and nb_conda_kernels
conda create -n ds_env python=3.7 jupyter nb_conda_kernels
# Activate the new environment
conda activate ds_env
# Expose this environment to our jupyter notebook
python -m ipykernel install --user --name=ds_env

Now let’s install all the apps we could ever need (at least at first):

# Declare the apps we want to install
declare -a conda_apps=(
"Pandas"
"NumPy"
"SciPy"
"Matplotlib"
"Scikit-Learn"
"xlwt"
"xlrd"
"OpenPyXL"
"XlsxWriter"
"SQLAlchemy"
"Teradata"
"pyodbc"
"Requests"
"BeautifulSoup"
"lxml"
"Selenium"
"PyTorch"
"TensorFlow"
"Theano"
"Keras"
"Flask"
"Django"
)

# Run conda install on each app name with -y
for app in "${conda_apps[@]}"; do
  conda install "$app" -y
done

There you have it, that should give you a bloated but capable environment to tackle statistical analysis on data sets, automate the editing of Excel files, pull data from Databases, scrape the web, automate web workflows, perform machine learning, and build web apps to display your results.

If you read this far then thank you so much. I am always open to feedback and would be willing to explore elaborating on any of the topics mentioned above or even branch into new ones. Feel free to reach out to me via email or connect on social media.