How to Set Up Your Jupyter Notebook and Python Virtual Environment for Machine Learning

Emily Ekdahl
2 min readApr 3, 2021

--

If you’re like me, you have to remind yourself of the commands each time you set up a new project. I’m writing it down here for me and for you!

image credit: https://unsplash.com/@sadswim

The first time

Open your bash or zsh profile.

For example, I use zsh.

zshconfig

If you used bash and vim, it would look something like this.

vim ~/.bash_profile

Hit i to go into insert mode.

Export the path to your project as a variable to make your life easier.

export MY_ML_PROJECT_PATH="$HOME/fancy_new_ml_project"

Hit ESC to exit insert mode.

Save and close your bash or zsh profile with :wq

Make a directory with that variable you created above.

mkdir -p $MY_ML_PROJECT_PATH

Check your versions of python and pip.

python3 --versionpython3 -m pip --version

Upgrade pip if you need to do so.

python3 -m pip install --user -U pip

Install python virtual environment package with pip.

python3 -m pip install --user -U virtualenv

Navigate to your project directory and create your virtual environment.

cd $MY_ML_PROJECT_PATHpython3 -m virtualenv my_env_name_of_choice

Activate your virtual environment.

source my_env_name_of_choice/bin/activate # on Linux or macOS
.\my_env_name_of_choice\Scripts\activate # on Windows

Install these packages and/or your ML packages of choice.

python3 -m pip install -U jupyter matplotlib numpy pandas scipy scikit-learn seaborn

Name and register the virtual environment to Jupyter Notebook.

python3 -m ipykernel install --user --name=ml

When you start your new project inside Jupyter Notebook, make sure the new virtual environment you named and registered is selected!

Every time

Whenever you need to navigate to your project after setup, follow these steps.

cd $MY_ML_PROJECT_PATH
source my_env_name_of_choice/bin/activate
# on Linux or macOS
.\my_env_name_of_choice\Scripts\activate # on Windows

Have fun!

--

--