Table of Contents

    Environment Setup (Python, venv, IDE, GPU/Colab)

    Machine Learning Development Setup

    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.

    Simple definition: A Python development environment is the combination of the Python interpreter, installed packages, project files, editor, runtime settings, and computing resources used to develop and run code.

    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
    Development Environment
    Python + Virtual Environment + Packages + Editor + Project Files → Runnable ML Project

    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
    Recommended course approach: Learn local Python and virtual environments for reproducible project work. Use Colab when browser-based experimentation or optional accelerator access is more convenient.

    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
    Successful Verification The terminal displays the Python version and the location of the interpreter or package manager without reporting that the command is unavailable.
    Common Problem The terminal reports that Python is not recognized or cannot be found.
    Possible Response Reopen the terminal, verify the installation, check whether the correct command is 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/
    Project principle: Keep project source code and documentation inside the project directory. Keep the virtual environment isolated and exclude it from Git.

    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.

    Do Not Copy the virtual environment between unrelated computers or commit the environment directory to Git.
    Recommended Recreate the environment from a documented Python version and dependency file.

    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
    Interpreter check: The displayed path should point to the Python interpreter inside the project's .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
    Installation guidance: Install Deep Learning, deployment, database, and specialized libraries only when they become necessary. A smaller environment is easier to understand and maintain.

    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')"
    Common Mistake Installing a package successfully in one environment while the IDE or notebook runs a different Python interpreter.
    Recommended Compare the interpreter path displayed in the terminal, IDE, and notebook kernel.

    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
    An environment is reproducible only when another authorized user can recreate it from documented instructions and dependencies.

    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.

    Project return process: Open the project directory, reactivate its virtual environment, and verify the interpreter before running the project again.

    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
    Wrong Interpreter Symptom The terminal can import a package, but the Python file or notebook reports that the package is unavailable.
    Likely Correction Select the project virtual environment as the IDE interpreter and select its corresponding notebook kernel.

    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
    Commit these instead: Commit source code, tests, safe configuration templates, dependency files, the README, and environment-creation instructions.

    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
    Expected Result The script displays the interpreter and package versions, trains a small model, calculates an evaluation result, and prints the final success message.
    If It Fails Read the first relevant error, verify the active interpreter, and confirm that the missing package was installed inside the same virtual environment.

    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.

    1

    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.

    2

    Rename the Notebook

    Use a descriptive name that identifies the lesson, experiment, or project purpose.

    3

    Verify the Runtime

    import platform
    import sys
    
    print("Python:", sys.version)
    print("Platform:", platform.platform())
    4

    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__)
    5

    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.

    Hosted-runtime reminder: The runtime can be restarted, disconnected, or replaced. Save important notebooks, source files, metrics, and approved artifacts to persistent storage rather than relying only on temporary runtime storage.

    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
    Unsafe Practice Uploading workplace, customer, employee, financial, or confidential project data to a personal cloud notebook without authorization.
    Responsible Practice Use public, synthetic, personally created, or otherwise appropriately authorized data and follow the applicable data-handling policy.

    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
    Incorrect Assumption Every Machine Learning project requires a GPU.
    Correct Understanding Many foundational lessons and classical Machine Learning workflows run effectively on a CPU. Use a GPU when the framework, model, dataset, and workload can benefit from it.

    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.

    Important: Detecting a GPU at the operating-system level does not guarantee that every Python framework is configured to use it. Verify GPU availability using the framework used by the project.

    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)
    Installation note: PyTorch package selection can depend on the operating system, Python version, accelerator, and supported runtime. Follow the official installation instructions for the environment rather than assuming one command works everywhere.

    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.")
    Avoid Installing GPU drivers, accelerator libraries, and framework packages from unrelated instructions without checking version and platform compatibility.
    Recommended Use the current official framework installation guidance for your operating system, Python version, hardware, and intended framework release.

    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
    A faster processor does not remove the need for efficient data pipelines, suitable batch sizes, and appropriate model selection.

    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
    Unsafe Python
    API_TOKEN = "real-secret-token"
    DATABASE_PASSWORD = "real-password"
    Safer Python Pattern
    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())
    Debugging principle: Before reinstalling packages, identify which interpreter is running, which environment is active, and where the package was installed.

    Recreate an Environment

    If an environment becomes difficult to repair, it may be safer to recreate it from documented dependencies.

    1

    Confirm Important Files Are Saved

    Ensure that source code, notebooks, configuration, documentation, and authorized artifacts are stored safely.

    2

    Deactivate the Environment

    deactivate
    3

    Remove the Old Environment Directory

    Delete only the project's virtual environment directory after verifying that it does not contain manually created project files.

    4

    Create and Activate a New Environment

    python -m venv .venv
    5

    Install Documented Dependencies

    python -m pip install -r requirements.txt
    6

    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

    1

    Create a Project

    Create a directory named ml-environment-check.

    2

    Create a Virtual Environment

    Create and activate a .venv environment inside the project.

    3

    Install Core Packages

    Install NumPy, pandas, Matplotlib, scikit-learn, and JupyterLab.

    4

    Configure the IDE

    Open the project directory and select the interpreter from the virtual environment.

    5

    Run the Environment Check

    Create and execute the verification script provided in this lesson.

    6

    Create a Notebook

    Start JupyterLab, create a notebook, verify the interpreter, and import the core packages.

    7

    Record Dependencies

    Create and review the project's dependency file.

    8

    Initialize Version Control

    Create a Git repository and commit the source, README, dependency file, and .gitignore without committing the virtual environment.

    Common Setup Mistakes

    Mistake Installing every package globally.
    Better Approach Create a project-specific virtual environment and install the required packages inside it.
    Mistake Selecting a different interpreter in the IDE and terminal.
    Better Approach Verify that the terminal, IDE, and notebook use the same project environment.
    Mistake Committing the .venv directory to Git.
    Better Approach Ignore the environment and commit a dependency file and setup instructions.
    Mistake Installing GPU packages before checking compatibility.
    Better Approach Follow the current instructions for the selected ML framework, operating system, Python version, hardware, and runtime.
    Mistake Assuming that Colab runtime files are permanent.
    Better Approach Save important work to approved persistent storage and ensure that the notebook can recreate required runtime setup.
    Mistake Hardcoding database passwords, service tokens, or API keys.
    Better Approach Use approved secret storage or protected runtime environment variables and keep secret files outside Git.

    Knowledge Check

    1

    What is a Python virtual environment?

    Explain how it isolates a project's interpreter and packages.

    2

    Why should each project use its own environment?

    Explain how isolation reduces dependency conflicts and improves reproducibility.

    3

    How can you verify the active interpreter?

    Explain how the executable path helps identify the environment currently running Python.

    4

    Why might a package work in the terminal but fail in the IDE?

    Consider whether the two tools are using different Python interpreters.

    5

    Does every Machine Learning project require a GPU?

    Explain why CPU resources are sufficient for many foundational and classical ML exercises.

    6

    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.

    7

    Why should the virtual environment not be committed?

    Explain why generated environment files are machine-specific and should be recreated from dependency documentation.

    8

    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.