Sub topic 4
Isolating projects with virtual environments
This chapter assumes you know basic Python and pip, can use a command line, and understand that an ML project has Python packages such as PyTorch or scikit-learn. You will create an isolated environment for one project and install packages into it.
Why isolation matters
A virtual environment is a directory containing a separate Python interpreter and package location. Packages installed there do not normally affect your operating system Python or another project.
Without isolation, two projects can require incompatible versions:
- Project A needs
numpy==1.26. - Project B needs
numpy==2.0. - Installing one version globally can break the other project.
A virtual environment gives each project its own package set. It does not copy every operating-system library, GPU driver, or data file. Those require other reproducibility techniques, such as lock files and containers.
Create and use an environment
From the project directory, create an environment named .venv:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install scikit-learn
python -c "import sklearn; print(sklearn.__version__)"The venv module creates the environment. Activation changes your shell’s PATH, so python and pip refer to .venv. Using python -m pip is safer than calling pip directly because it clearly selects the pip belonging to that Python interpreter.
On Windows PowerShell, activate it with:
py -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pipWhen the environment is active, your prompt usually includes (.venv). Check which interpreter is being used:
python -c "import sys; print(sys.executable)"
python -m pip listExit the environment with:
deactivateThe .venv directory is machine-specific and usually should not be committed to Git. Add it to .gitignore:
.venv/Connect isolation to dependency management
A virtual environment isolates an installation, but it does not record a complete, repeatable dependency solution by itself. A file such as requirements.in can declare direct dependencies:
scikit-learn
torchA lock tool can then resolve direct and indirect dependencies into a locked file. New environments should install from that locked file rather than choosing versions independently. This gives you both local isolation and a known dependency tree.
> [!NOTE] > Activation is a convenience, not a security boundary. Scripts can use the environment directly through .venv/bin/python, or .venv\Scripts\python.exe on Windows.
Exercise
Why might installing a package globally be unsafe for two ML projects?
Show answer
The projects may require incompatible versions of the same package. Separate virtual environments let each project use its own version.