How to Install TensorFlow on Ubuntu 24.04
Step-by-step tutorial to install TensorFlow on Ubuntu 24.04 LTS with Python 3 virtual environment, pip, and optional NVIDIA CUDA GPU acceleration.

6 min read
Step-by-step tutorial to install TensorFlow on Ubuntu 24.04 LTS with Python 3 virtual environment, pip, and optional NVIDIA CUDA GPU acceleration.
- Prerequisites and Supported Releases
- Step 1: Updating System and Installing Python Development Tools
- Step 2: Creating a Dedicated Python Virtual Environment
Artificial intelligence, predictive analytics, and deep learning architectures rely on computational frameworks capable of executing complex tensor mathematical graphs at scale. When you install tensorflow on ubuntu 24.04, you deploy Google's production-grade machine learning platform, equipped with high-level Keras APIs, distributed training engines, and extensive mathematical kernel optimizations.
Ubuntu 24.04 LTS ships with Python 3.12 and strictly enforces PEP 668 (externally managed environment standards). Consequently, attempting to run global pip install commands will result in deliberate system blocks to protect underlying APT package dependencies. Deploying TensorFlow inside an isolated Python virtual environment (venv) ensures clean dependency isolation, reproducible library versions, and conflict-free package management.
In this guide, you will learn how to configure the foundational Python development environment, create an isolated virtual workspace, install the official TensorFlow release, configure optional NVIDIA CUDA GPU acceleration, and test device recognition using an interactive Python script.
TensorFlow is an open-source, end-to-end machine learning platform developed by Google for training and deploying deep neural networks, natural language processing models, and computer vision algorithms. This step-by-step tutorial demonstrates how to install TensorFlow on Ubuntu 24.04 LTS using an isolated Python 3 virtual environment, configure pip package management under PEP 668 guidelines, set up optional NVIDIA CUDA GPU acceleration, and execute a neural network verification model.
Prerequisites and Supported Releases
This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat). The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.
Before proceeding, ensure you have the following requirements satisfied:
- A workstation or server running Ubuntu 24.04 LTS (64-bit architecture).
- A user account with active sudo administrative privileges.
- Python 3 and pip installed (or ready to install).
- Optional: An authentic NVIDIA GPU with proprietary drivers and CUDA Toolkit for hardware acceleration.
Step 1: Updating System and Installing Python Development Tools
Before configuring machine learning runtimes, ensure your system package lists are up to date and install essential Python 3 development libraries, virtual environment support, and compiler toolchains.
Because compiling native C++ extensions for machine learning wheels requires header files and basic compilation tools, install python3-dev, python3-pip, python3-venv, and build-essential using the standard APT package manager.
These foundational packages prevent wheel compilation errors during package installations.
# Refresh package repository index
sudo apt update && sudo apt upgrade -y
# Install Python 3 development headers, venv, and build tools
sudo apt install -y python3-dev python3-pip python3-venv build-essential
Step 2: Creating a Dedicated Python Virtual Environment
Create a dedicated project workspace directory in your user home folder and initialize an isolated Python virtual environment named tf-env.
Activating this environment modifies your current shell's $PATH so that all subsequent python and pip commands execute exclusively within the isolated directory, adhering strictly to Ubuntu 24.04's PEP 668 standards.
Upgrade foundational packaging tools including pip, setuptools, and wheel before installing complex scientific packages.
# Create project directory
mkdir -p ~/tensorflow_project && cd ~/tensorflow_project
# Initialize Python virtual environment
python3 -m venv tf-env
# Activate the virtual environment
source tf-env/bin/activate
# Upgrade pip to latest release within the virtual environment
pip install --upgrade pip setuptools wheel
Step 3: Installing TensorFlow via Pip
With the virtual environment active, install TensorFlow. In modern releases (TensorFlow 2.x), the standard tensorflow wheel automatically bundles CPU mathematical optimizations alongside GPU capabilities when compatible NVIDIA driver libraries are detected.
Execute the pip install command to fetch TensorFlow and its core mathematical dependencies, including NumPy, Keras, and TensorBoard.
The installation process downloads pre-compiled wheels, avoiding tedious local C++ compilation.
# Install the latest stable TensorFlow release
pip install tensorflow
Step 4: Configuring Optional NVIDIA GPU Acceleration
If your system contains a modern NVIDIA GPU (such as RTX, Quadro, or Tesla), hardware acceleration speeds up model training by 10x to 50x compared to CPU execution.
To utilize GPU compute, ensure you have installed the proprietary NVIDIA display driver and NVIDIA CUDA Toolkit. You must also install NVIDIA's cuDNN deep learning libraries inside your virtual environment using pip.
Run the following pip commands to install matching CUDA and cuDNN runtime packages directly into your environment and export the dynamic library paths:
# Install NVIDIA CUDA and cuDNN wheels inside the virtual environment
pip install nvidia-cuda-runtime-cu12 nvidia-cudnn-cu12
# Export library path for the active session
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${VIRTUAL_ENV}/lib/python3.12/site-packages/nvidia/cuda_runtime/lib/:${VIRTUAL_ENV}/lib/python3.12/site-packages/nvidia/cudnn/lib/
Step 5: Verifying TensorFlow Installation and Device Detection
Verify that TensorFlow can be imported cleanly and inspect the physical devices detected by the runtime.
Execute a Python command in your terminal to query available CPU and GPU computing units, confirm TensorFlow version, and verify tensor arithmetic execution.
A successful test confirms that the tensor memory allocator and mathematical kernels initialize properly.
# Verify version and list physical compute devices
python3 -c "import tensorflow as tf; print('TensorFlow Version:', tf.__version__); print('Physical Devices:', tf.config.list_physical_devices())"
Step 6: Building and Training a Baseline Neural Network
Confirm complete mathematical execution by creating and running a test script that builds a synthetic sequential neural network, compiles it with an Adam optimizer, and trains it across multiple epochs.
Write the test script and execute it inside your virtual environment.
The script verifies forward passes, backpropagation loss calculation, and weight optimization.
# Create test training script
cat << 'EOF' > test_tf_model.py
import tensorflow as tf
import numpy as np
print("Running baseline TensorFlow neural network verification...")
# Generate synthetic linear regression data
X_train = np.random.rand(1000, 10).astype(np.float32)
y_train = (np.sum(X_train, axis=1, keepdims=True) > 5.0).astype(np.float32)
# Build a simple sequential classifier
model = tf.keras.Sequential([
tf.keras.layers.Dense(32, activation='relu', input_shape=(10,)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train model for 5 epochs
history = model.fit(X_train, y_train, epochs=5, batch_size=32, verbose=1)
print("
TensorFlow model compiled and trained successfully!")
print("Final Epoch Accuracy:", history.history['accuracy'][-1])
EOF
# Execute test model
python3 test_tf_model.py
Step 7: Monitoring Model Training with TensorBoard
TensorBoard provides visual inspection of machine learning metrics, loss curves, computational graph architectures, and weight histograms.
When training complex neural networks, logging data to a directory using the tf.keras.callbacks.TensorBoard callback allows real-time visualization in your web browser.
Start the TensorBoard dashboard on local port 6006 to explore model metrics.
# Launch TensorBoard web dashboard
tensorboard --logdir=logs/ --port=6006 --bind_all
Step 8: Installing JupyterLab for Interactive Model Development
Data scientists and machine learning engineers typically develop TensorFlow models using interactive Jupyter Notebooks. You can install JupyterLab directly inside your active virtual environment.
Launch JupyterLab from your project folder to build, visualize, and document models interactively in your web browser without affecting global system packages.
# Install JupyterLab and Matplotlib
pip install jupyterlab matplotlib
# Launch JupyterLab server
jupyter lab --no-browser
Troubleshooting and Common Errors
When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:
pip install fails with 'error: externally-managed-environment'
Resolution: Ubuntu 24.04 strictly enforces PEP 668 to prevent damaging system Python packages. You must activate a virtual environment (source tf-env/bin/activate) before running pip install commands. Never use --break-system-packages on production workstations.
TensorFlow warning: 'Could not load dynamic library libcudart.so'
Resolution: This indicates missing CUDA runtime libraries. Ensure NVIDIA proprietary drivers are installed, run pip install nvidia-cuda-runtime-cu12, and export $LD_LIBRARY_PATH to include the virtual environment's CUDA libraries.
System crashes or freezes during model training due to out-of-memory
Resolution: Limit GPU memory allocation by adding tf.config.experimental.set_memory_growth(gpu, True) in your Python script, or decrease training batch_size from 64 to 16.
Security Best Practices and Hardening
Never load untrusted pre-trained model files (such as pickled .pkl or legacy .h5 files) from unknown sources, as arbitrary Python code can execute during deserialization.
Use isolated virtual environments for distinct projects to avoid package dependency conflicts and reduce security blast radiuses.
Regularly run pip audit inside your virtual environment to identify known vulnerabilities in machine learning dependencies.
Do not execute model training scripts or launch JupyterLab servers under the root administrative user account.
Related Ubuntu Tutorials and Documentation
Deepen your Linux system administration skills with our related production-tested guides:
- How to Install NVIDIA CUDA Toolkit on Ubuntu 24.04 — Deploy the foundational NVIDIA CUDA Toolkit and driver stack for maximum GPU compute.
- How to Install Anaconda Python on Ubuntu 24.04 — Alternative conda environment management for scientific computing and AI.
- How to Install OpenCV on Ubuntu 24.04 — Combine computer vision processing with TensorFlow deep neural networks.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
tf-env and pytorch-env) to avoid conflicting CUDA runtime wheel versions.deactivate in your terminal to return to your standard system shell environment.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
Rajesh Ray
I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides
Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!