Environment Setup (Python, venv, IDE, GPU/Colab)
Environment Setup: Python, venv, IDE, GPU, and Colab
Set up a clean, isolated, reproducible, and beginner-friendly development environment for Python, data analysis, Machine Learning, Deep Learning, and practical course projects.
Introduction
Before writing Machine Learning code, you need a reliable development environment. The environment includes Python, installed libraries, a code editor or notebook application, project files, and the computing resources used to execute the code.
A correctly configured environment helps prevent package conflicts, missing dependencies, inconsistent results, and confusion about which Python installation is executing a program.
This lesson presents two practical setup paths. You can configure a local environment on your computer or use Google Colab through a web browser. Local development provides greater control, while Colab can be convenient for learning, notebooks, and optional accelerator access.
Learning Objectives
By the End of This Lesson
- Understand the components of a Python development environment
- Install or verify a supported Python 3 installation
- Create and activate a project-specific virtual environment
- Install packages inside the correct environment
- Configure Visual Studio Code or another suitable IDE
- Install and use Jupyter Notebook or JupyterLab
- Create a clean Machine Learning project structure
- Record project dependencies for reproducibility
- Use Google Colab for browser-based practical work
- Understand when CPU, GPU, and cloud runtimes are appropriate
- Verify whether a compatible ML framework can access a GPU
- Troubleshoot common environment and package problems
- Protect credentials, data, and local configuration files
Prerequisites
Recommended Knowledge
- Basic computer and file-management skills
- Basic familiarity with folders and file extensions
- Basic terminal or command-prompt navigation
- Permission to install software on the selected computer
- Internet access for downloading tools and packages
Before Installing Software
- Follow the applicable organizational software-installation policy
- Download software only from official or approved sources
- Do not disable security software to complete an installation
- Do not use confidential data in an unapproved environment
- Confirm whether administrator permission is required
Environment Components
| Component | Purpose |
|---|---|
| Python Interpreter | Executes Python source code |
| Virtual Environment | Isolates project packages from other projects |
| Package Manager | Installs and manages Python libraries |
| IDE or Code Editor | Supports writing, running, navigating, and debugging code |
| Notebook Environment | Combines executable code, results, text, and visualizations |
| Project Repository | Organizes source code, tests, configuration, and documentation |
| CPU | Runs general Python, data-processing, and many ML workloads |
| GPU | Accelerates supported parallel workloads, especially some Deep Learning operations |
| Cloud Notebook | Provides a browser-based hosted execution environment |
Choose a Setup Path
Local Environment
- Provides control over files and installed packages
- Supports IDEs, scripts, notebooks, Git, and local tools
- Can work without continuous internet access after setup
- Requires installation and environment maintenance
Google Colab
- Runs notebooks through a web browser
- Requires little local installation
- Can provide optional accelerator runtimes
- Runtime storage and installed packages may be temporary
| Situation | Suggested Starting Point |
|---|---|
| You want the quickest browser-based learning setup | Google Colab |
| You want to learn professional project organization | Local Python environment |
| You have limited local computing resources | Colab or another approved cloud environment |
| You need local Git, testing, APIs, and deployment tools | Local Python environment |
| You are learning basic Python and classical ML | Either local CPU or Colab |
Install Python
Install a supported Python 3 version from an official or approved source. During installation, ensure that the Python command can be accessed from your terminal when the installer provides that option.
After installation, open a new terminal and verify Python:
python --version
On some systems, the Python 3 command may be:
python3 --version
Verify the package installer:
python -m pip --version
If your system uses python3, use:
python3 -m pip --version
python or python3, and
confirm that the interpreter is available through the system path.
Create a Project Directory
Keep each major Machine Learning project in its own directory. This makes environment isolation, version control, documentation, and cleanup easier.
mkdir ml-environment-check
cd ml-environment-check
A useful starter structure is:
ml-environment-check/
|
|-- README.md
|-- requirements.txt
|-- notebooks/
|-- src/
| `-- environment_check.py
|-- tests/
|-- data/
|-- models/
`-- reports/
What Is a Virtual Environment?
A virtual environment is an isolated Python environment created for a particular project. It has its own interpreter reference and installed package collection.
Suppose one project requires one version of a library while another project requires a different version. Separate virtual environments help prevent the packages of one project from interfering with the packages of another.
Global Installation
- Packages are shared across projects
- Upgrades can affect unrelated work
- Dependencies become harder to reproduce
- Administrative permission may be required
Project Virtual Environment
- Packages are isolated by project
- Dependencies are easier to document
- Experiments are easier to reproduce
- The project can be removed without affecting other environments
Create a Virtual Environment
Run the following command from the project directory:
python -m venv .venv
If your system uses python3, run:
python3 -m venv .venv
The .venv directory contains the isolated environment.
The leading dot is a naming convention and does not change the
environment's purpose.
Activate the Virtual Environment
Windows Command Prompt
.venv\Scripts\activate
Windows PowerShell
.venv\Scripts\Activate.ps1
Linux or macOS
source .venv/bin/activate
After activation, the terminal prompt commonly displays the environment name. Verify the active interpreter:
python -c "import sys; print(sys.executable)"
Verify that pip belongs to the same environment:
python -m pip --version
.venv directory.
Install the Core Course Packages
Upgrade the package installer inside the active environment:
python -m pip install --upgrade pip
Install the foundational data and Machine Learning packages:
python -m pip install numpy pandas matplotlib seaborn scikit-learn jupyterlab
| Package | Purpose |
|---|---|
| NumPy | Numerical arrays and mathematical operations |
| pandas | Tabular data loading, cleaning, and transformation |
| Matplotlib | General data visualization |
| Seaborn | Statistical visualization built on Matplotlib |
| scikit-learn | Preprocessing, classical ML algorithms, and evaluation |
| JupyterLab | Interactive notebooks and related development tools |
Inspect Installed Packages
Display the installed packages:
python -m pip list
Display information about a particular package:
python -m pip show scikit-learn
Verify the core imports:
python -c "import numpy, pandas, sklearn; print('Core packages are available')"
Record Project Dependencies
A dependency file records the libraries required to recreate the environment.
One option is to export the current environment:
python -m pip freeze > requirements.txt
Review the generated file before committing it. Recreate an environment from that file using:
python -m pip install -r requirements.txt
| Dependency Practice | Purpose |
|---|---|
| Record required packages | Helps another user reproduce the environment |
| Record compatible versions | Reduces unexpected behavior from dependency changes |
| Document the Python version | Clarifies interpreter compatibility |
| Review dependency files | Prevents unnecessary or private packages from being included accidentally |
| Test environment recreation | Verifies that the documentation is sufficient |
Deactivate the Environment
When you finish working in the project environment, deactivate it:
deactivate
Deactivation returns the terminal to its previous Python environment. It does not delete packages or project files.
Install and Configure an IDE
An Integrated Development Environment, commonly called an IDE, provides tools for writing, running, navigating, testing, and debugging code. A lighter code editor can provide similar features through extensions.
| Tool | Suitable Use |
|---|---|
| Visual Studio Code | Python scripts, notebooks, Git, debugging, testing, and extensions |
| PyCharm | Structured Python development and project navigation |
| JupyterLab | Interactive data exploration and notebook-based learning |
| Google Colab | Browser-based notebook execution and cloud runtime access |
Visual Studio Code Setup
- Install Visual Studio Code from an official or approved source
- Install the supported Python extension
- Install notebook support when you plan to use notebooks
- Open the project directory rather than only one individual file
- Select the interpreter inside the project's .venv directory
- Open a new integrated terminal after selecting the environment
- Verify the interpreter path before installing packages
Start JupyterLab
Activate the project environment and start JupyterLab:
jupyter lab
JupyterLab normally opens in a web browser. Create a Python notebook and select the kernel associated with the current virtual environment.
Verify the Notebook Kernel
import sys
print(sys.executable)
print(sys.version)
The executable path should point to the intended environment.
Notebook Practices
- Run cells in a clear top-to-bottom order
- Restart the kernel and run all cells before finalizing work
- Move stable reusable logic into Python modules
- Remove unnecessary output before committing notebooks
- Do not display confidential information in output cells
- Record the environment and package requirements
Add the Environment to Git Ignore Rules
The virtual environment contains generated and machine-specific files. It should not normally be committed to Git.
Add these patterns to the project .gitignore file:
# Python virtual environments
.venv/
venv/
env/
# Python-generated files
__pycache__/
*.py[cod]
# Notebook temporary data
.ipynb_checkpoints/
# Local secrets and environment variables
.env
.env.*
!.env.example
# Generated datasets and models
data/raw/*
data/processed/*
models/*
# Keep documentation placeholders
!data/raw/README.md
!data/processed/README.md
!models/README.md
Verify the Local ML Environment
Create src/environment_check.py with the following
content:
import sys
import matplotlib
import numpy as np
import pandas as pd
import sklearn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
print("Python:", sys.version.split()[0])
print("Python executable:", sys.executable)
print("NumPy:", np.__version__)
print("pandas:", pd.__version__)
print("Matplotlib:", matplotlib.__version__)
print("scikit-learn:", sklearn.__version__)
dataset = load_iris(as_frame=True)
X = dataset.data
y = dataset.target
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.20,
random_state=42,
stratify=y
)
model = DecisionTreeClassifier(
max_depth=3,
random_state=42
)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = accuracy_score(
y_test,
predictions
)
print(f"Environment test accuracy: {accuracy:.3f}")
print("Machine Learning environment is working.")
Run the file from the project directory:
python src/environment_check.py
Google Colab Setup
Google Colab provides a hosted notebook environment that runs through a web browser. It can be useful when you do not want to configure a complete local setup or when an available accelerator runtime is suitable for the lesson.
Create or Open a Notebook
Open Colab using an appropriate account and create a new notebook or upload an existing notebook that you are authorized to use.
Rename the Notebook
Use a descriptive name that identifies the lesson, experiment, or project purpose.
Verify the Runtime
import platform
import sys
print("Python:", sys.version)
print("Platform:", platform.platform())
Check Installed Packages
import numpy as np
import pandas as pd
import sklearn
print("NumPy:", np.__version__)
print("pandas:", pd.__version__)
print("scikit-learn:", sklearn.__version__)
Install a Missing Package When Required
Packages installed in a hosted notebook runtime may not remain available after the runtime is reset. Record required installation commands near the beginning of the notebook.
Working with Files in Colab
Colab notebooks can work with uploaded files, generated files, and connected storage. Use only data that you are authorized to place in that environment.
File-Handling Practices
- Do not upload confidential data to an unapproved runtime
- Do not place credentials directly in notebook cells
- Avoid displaying private data in notebook output
- Remove temporary files when they are no longer required
- Record how a public or synthetic dataset was obtained
- Save important project files outside temporary runtime storage
- Review notebook output before sharing the notebook
CPU vs GPU
A CPU is suitable for Python programming, data preparation, SQL access, visualization, and many classical Machine Learning algorithms. A GPU can accelerate supported highly parallel numerical calculations, especially certain Deep Learning workloads.
| Workload | Common Starting Resource |
|---|---|
| Python fundamentals | CPU |
| Small pandas datasets | CPU |
| Classical scikit-learn models | CPU for most course exercises |
| Basic visualization | CPU |
| Small neural-network examples | CPU or GPU |
| Large image, language, or neural-network training | A compatible GPU may provide significant acceleration |
| Model inference | Depends on model size, latency, and deployment requirements |
Enable an Accelerator in Colab
When a Deep Learning lesson requires an accelerator, open the notebook's runtime settings and select an available hardware accelerator. Availability and usage limits depend on the current Colab environment and account.
After changing the runtime type, the runtime may restart. Run the notebook setup and import cells again.
General NVIDIA Runtime Check
nvidia-smi
If a compatible NVIDIA runtime is available, the command can display information about the GPU and driver environment.
Verify GPU Access with PyTorch
If PyTorch is installed in the environment, use:
import torch
print("PyTorch version:", torch.__version__)
print("CUDA available:", torch.cuda.is_available())
if torch.cuda.is_available():
print("GPU:", torch.cuda.get_device_name(0))
else:
print("PyTorch is using the CPU.")
Select the execution device in a reusable way:
import torch
device = torch.device(
"cuda"
if torch.cuda.is_available()
else "cpu"
)
print("Selected device:", device)
Verify GPU Access with TensorFlow
If TensorFlow is installed in a supported environment, inspect the detected GPU devices:
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
gpu_devices = tf.config.list_physical_devices(
"GPU"
)
print("Detected GPU devices:", gpu_devices)
if gpu_devices:
print("TensorFlow can detect at least one GPU.")
else:
print("TensorFlow is using the available CPU environment.")
Understand GPU Memory Limits
A GPU has its own memory. A model, its parameters, input batches, activations, gradients, and temporary calculations may all use GPU memory during training.
When GPU Memory Is Insufficient
- Reduce the training batch size
- Use a smaller model
- Reduce image or sequence size when appropriate
- Remove unused tensors or restart the runtime
- Use mixed precision only when it is supported and understood
- Use gradient accumulation when appropriate
- Monitor memory consumption during experiments
Environment Security
Development environments may contain credentials, database connections, datasets, model artifacts, notebook outputs, and external-service access. These resources must be protected.
Security Checklist
- Install software and packages from trusted or approved sources
- Use project-specific virtual environments
- Do not run unknown notebooks or scripts without reviewing them
- Do not hardcode passwords, keys, or tokens
- Use approved secret-management or environment-variable mechanisms
- Keep secret files outside Git
- Use least-privilege access for databases and cloud services
- Protect downloaded datasets and generated model artifacts
- Review notebook outputs before sharing
- Remove access when it is no longer required
API_TOKEN = "real-secret-token"
DATABASE_PASSWORD = "real-password"
import os
api_token = os.environ["API_TOKEN"]
database_password = os.environ[
"DATABASE_PASSWORD"
]
Common Setup Problems
| Problem | Possible Cause | Recommended Check |
|---|---|---|
| Python command is unavailable | Python is not installed or not available through the command path | Verify installation and try the appropriate Python 3 command |
| Package import fails | Package is installed in a different environment | Compare the running interpreter with the installation location |
| IDE cannot find a package | The IDE selected the wrong interpreter | Select the interpreter inside the project .venv directory |
| Notebook cannot find a package | The notebook uses the wrong kernel | Select the kernel associated with the project environment |
| PowerShell blocks activation | Script-execution policy restricts the activation script | Follow the approved organizational procedure or use another supported shell |
| Package installation is denied | Permission, network, proxy, or policy restriction | Use the virtual environment and approved package source |
| Different result on another computer | Different code, data, dependencies, or random settings | Compare Git revision, data version, package versions, and configuration |
| GPU is not detected | Unsupported package, runtime, driver, or hardware configuration | Review the framework's current compatibility requirements |
| Colab files disappear | Files were stored only in the temporary runtime | Save required files to approved persistent storage |
Environment Diagnostic Commands
Use these commands to inspect the active environment:
python --version
python -m pip --version
python -m pip list
python -c "import sys; print(sys.executable)"
python -c "import sys; print(sys.path)"
python -c "import numpy; print(numpy.__version__)"
Inside Python or a notebook:
import os
import platform
import sys
print("Python version:", sys.version)
print("Interpreter:", sys.executable)
print("Operating system:", platform.platform())
print("Working directory:", os.getcwd())
Recreate an Environment
If an environment becomes difficult to repair, it may be safer to recreate it from documented dependencies.
Confirm Important Files Are Saved
Ensure that source code, notebooks, configuration, documentation, and authorized artifacts are stored safely.
Deactivate the Environment
deactivate
Remove the Old Environment Directory
Delete only the project's virtual environment directory after verifying that it does not contain manually created project files.
Create and Activate a New Environment
python -m venv .venv
Install Documented Dependencies
python -m pip install -r requirements.txt
Run the Verification Script and Tests
Confirm that the project works in the newly created environment.
Setup Verification Checklist
Local Environment
- Python 3 is installed and available in the terminal
- The project has its own directory
- The .venv virtual environment has been created
- The virtual environment activates successfully
- The Python executable points to the project environment
- Core packages import successfully
- The IDE uses the same Python interpreter
- The notebook uses the correct kernel
- The environment-check script runs successfully
- The virtual environment is ignored by Git
Colab Environment
- The notebook opens and executes Python cells
- Required packages are available or installed at runtime
- The selected runtime matches the lesson requirement
- GPU access is verified through the selected framework when required
- Important files are saved outside temporary runtime storage
- No confidential data or credentials are exposed
- The notebook can restart and run from the beginning
Reproducibility
- The Python version is documented
- Dependencies are recorded
- Setup steps are documented in the README
- Source code and configuration are version controlled
- Datasets and model artifacts use appropriate managed storage
- Secrets are excluded from the repository
Hands-On Setup Activity
Create a Project
Create a directory named ml-environment-check.
Create a Virtual Environment
Create and activate a .venv environment inside the
project.
Install Core Packages
Install NumPy, pandas, Matplotlib, scikit-learn, and JupyterLab.
Configure the IDE
Open the project directory and select the interpreter from the virtual environment.
Run the Environment Check
Create and execute the verification script provided in this lesson.
Create a Notebook
Start JupyterLab, create a notebook, verify the interpreter, and import the core packages.
Record Dependencies
Create and review the project's dependency file.
Initialize Version Control
Create a Git repository and commit the source, README, dependency file, and .gitignore without committing the virtual environment.
Common Setup Mistakes
Knowledge Check
What is a Python virtual environment?
Explain how it isolates a project's interpreter and packages.
Why should each project use its own environment?
Explain how isolation reduces dependency conflicts and improves reproducibility.
How can you verify the active interpreter?
Explain how the executable path helps identify the environment currently running Python.
Why might a package work in the terminal but fail in the IDE?
Consider whether the two tools are using different Python interpreters.
Does every Machine Learning project require a GPU?
Explain why CPU resources are sufficient for many foundational and classical ML exercises.
Why must GPU availability be checked through the framework?
Explain why hardware detection alone does not prove that a selected framework can use the GPU.
Why should the virtual environment not be committed?
Explain why generated environment files are machine-specific and should be recreated from dependency documentation.
What happens when a Colab runtime restarts?
Explain why temporary files and runtime-installed packages may need to be recreated.
Lesson Summary
| Component | Main Point |
|---|---|
| Python | Provides the interpreter used to execute course code |
| Virtual Environment | Isolates project dependencies |
| pip | Installs and manages Python packages |
| Dependency File | Supports environment recreation and reproducibility |
| IDE | Supports coding, navigation, debugging, testing, and notebooks |
| JupyterLab | Supports interactive code, explanation, data inspection, and visualization |
| Google Colab | Provides a browser-based hosted notebook environment |
| CPU | Supports general Python, data processing, and many ML workloads |
| GPU | Can accelerate compatible highly parallel and Deep Learning workloads |
| Interpreter Selection | Must remain consistent across the terminal, IDE, and notebook |
| Security | Credentials and confidential data must not be exposed in code or notebooks |
| Reproducibility | Requires documented Python, dependencies, setup, code, and configuration |
Key Takeaway
A reliable Machine Learning development environment uses a supported Python installation, a project-specific virtual environment, documented dependencies, a correctly configured IDE or notebook kernel, and secure handling of data and credentials. Begin with a CPU environment for foundational work, use a compatible GPU when the workload benefits from it, and use Colab when a browser-based hosted runtime is appropriate.
Get Machine Learning updates by email
Short, practical lessons and course updates from Rumman Ansari. No spam.