How To Install TensorFlow on Rocky Linux 10

Machine learning and artificial intelligence have transformed the technology landscape, powering everything from recommendation systems to autonomous vehicles. TensorFlow stands at the forefront of this revolution as Google’s powerful open-source machine learning platform. Rocky Linux 10, released as the “Red Quartz” edition, provides an enterprise-grade, stable foundation perfect for hosting TensorFlow applications. This comprehensive guide walks through every step needed to successfully install TensorFlow on Rocky Linux 10, from system preparation to verification testing.
Rocky Linux 10 brings significant improvements including Python 3.12 support, enhanced x86-64-v3 architecture optimization, and superior compatibility with RHEL 10. These features make it an ideal choice for data scientists, machine learning engineers, and developers looking to build robust AI applications. Whether working on neural network training, deep learning research, or predictive analytics, this tutorial provides everything needed to get TensorFlow running smoothly.
Understanding TensorFlow and Its Applications
TensorFlow is an end-to-end open-source platform for machine learning developed and maintained by Google Brain Team. The framework provides a comprehensive ecosystem of tools, libraries, and community resources that enable researchers to push machine learning boundaries while allowing developers to build and deploy ML-powered applications efficiently.
The platform’s flexibility allows implementation across various hardware configurations, from laptops to large-scale distributed systems. TensorFlow supports multiple programming languages including Python, JavaScript, and C++, though Python remains the most popular choice. Major organizations like Twitter, PayPal, Intel, Lenovo, and Airbus rely on TensorFlow for production machine learning workloads.
Common applications include image recognition, natural language processing, speech recognition, time series forecasting, and recommendation systems. TensorFlow comes in two primary variants: CPU-only versions for general computing and GPU-accelerated versions for intensive computational tasks. Virtual environment installation is strongly recommended to maintain clean dependency management and avoid conflicts with system-level Python packages.
System Requirements and Prerequisites
Hardware Requirements
Successful TensorFlow installation requires specific hardware capabilities. The minimum CPU specification is a 64-bit x86_64-v3 processor with AVX (Advanced Vector Extensions) support. Rocky Linux 10 specifically optimizes for x86-64-v3 architecture, providing enhanced performance for mathematical operations crucial to machine learning workloads.
RAM requirements depend heavily on intended workload. Eight gigabytes represents the absolute minimum for basic TensorFlow operations, but 16GB or more is strongly recommended for training complex models or processing large datasets. Storage requirements include at least 20GB of free space to accommodate the operating system, updates, TensorFlow installation, and workspace for model training.
GPU acceleration remains optional but provides dramatic performance improvements for deep learning tasks. NVIDIA GPUs with CUDA 11.x support and Compute Capability 3.5 or higher work best with TensorFlow. A minimum of 6GB VRAM is recommended for GPU-accelerated training, though more intensive models may require 8GB or higher.
Software Requirements
Rocky Linux 10 must be fully installed and updated before proceeding. The system supports Python 3.9, 3.11, and 3.12, all compatible with current TensorFlow versions. The pip package manager version 19.0 or higher is required for proper TensorFlow installation. An active internet connection enables downloading packages and dependencies, while sudo privileges are necessary for system-level package installation.
Pre-Installation Checklist
Verify system architecture compatibility using the uname -m command, which should return x86_64. Check available disk space with df -h to ensure sufficient storage. Confirm network connectivity by pinging external servers. Document the current Python version if already installed, as this information helps troubleshoot potential compatibility issues later.
Preparing Your Rocky Linux 10 System
Updating System Packages
System updates form the foundation of stable TensorFlow installation. Updates address security vulnerabilities, fix bugs, and ensure compatibility with latest software packages. Open a terminal and refresh the package cache first.
sudo dnf makecache --refresh
This command downloads the latest package metadata from configured repositories. Next, perform a full system update to bring all installed packages to their latest versions.
sudo dnf update -y
The -y flag automatically confirms all prompts, streamlining the update process. Depending on how long since the last update, this process may take several minutes. After major updates, especially kernel updates, reboot the system to ensure all changes take effect properly.
sudo reboot
Installing Essential Development Tools
TensorFlow and its dependencies require compilation tools and libraries. Rocky Linux groups common development packages together for convenient installation.
sudo dnf groupinstall "Development Tools" -y
This command installs gcc, g++, make, and other essential build utilities. Additional development libraries support Python package compilation.
sudo dnf install gcc libffi-devel openssl-devel zlib-devel bzip2-devel readline-devel sqlite-devel -y
Each package serves specific purposes. The gcc compiler handles C code compilation, libffi-devel provides foreign function interface support, openssl-devel enables SSL/TLS functionality, while zlib-devel, bzip2-devel, readline-devel, and sqlite-devel support various Python modules and data compression operations.
Installing Python 3 on Rocky Linux 10
Rocky Linux 10 takes a unique approach to Python management, avoiding a default system-wide Python installation to prevent conflicts with system utilities. Users must explicitly install Python for application development.
sudo dnf install python3 -y
This command installs the default Python 3 version for Rocky Linux 10, typically Python 3.12 or Python 3.11. Verify successful installation by checking the Python version.
python3 --version
The output should display something like “Python 3.12.0” or similar. For projects requiring specific Python versions, install them explicitly.
sudo dnf install python3.11 -y
Rocky Linux 10 maintains separate platform-python for system utilities and user-installable Python for application development, preventing system breakage from user modifications.
Installing pip and Virtual Environment Tools
The pip package manager handles Python package installation and dependency resolution. Install pip alongside Python development packages and virtual environment tools.
sudo dnf install python3-pip python3-virtualenv python3-devel -y
The python3-devel package provides header files necessary for compiling Python C extensions, which many scientific packages including TensorFlow depend upon. Verify pip installation successfully.
pip3 --version
The output displays the installed pip version along with its location and associated Python version. Version 19.0 or higher is required for TensorFlow installation.
Creating a TensorFlow Virtual Environment
Understanding Python Virtual Environments
Python virtual environments create isolated spaces for project-specific dependencies. Each virtual environment maintains its own Python interpreter copy and installed packages, preventing conflicts between different projects requiring different package versions. This isolation proves essential for machine learning projects where specific TensorFlow versions may work better with particular model architectures.
Virtual environments protect the system Python installation from modifications that could break system utilities. They enable easy dependency management through requirements files and allow testing different package versions without affecting other projects. Every serious Python developer should utilize virtual environments for professional development work.
Creating the Project Directory
Organize TensorFlow projects in dedicated directories for better file management. Create a project directory in the home folder.
mkdir ~/tensorflow_project
Navigate into this newly created directory.
cd ~/tensorflow_project
Alternatively, use more descriptive names reflecting specific projects.
mkdir ~/ml_image_classifier
cd ~/ml_image_classifier
Good directory naming conventions improve project organization, especially when managing multiple machine learning projects simultaneously.
Setting Up the Virtual Environment
Create the virtual environment using Python’s built-in venv module. This module ships with Python 3.3 and later, requiring no additional installation.
python3 -m venv tensorflow_venv
This command creates a new directory named “tensorflow_venv” containing the virtual environment structure. The directory includes a Python interpreter copy, pip package manager, and space for installed packages. Choose meaningful virtual environment names that reflect their purpose.
python3 -m venv venv
Many developers prefer the simple “venv” name for single-purpose projects. The virtual environment creation process takes a few seconds to complete.
Activating the Virtual Environment
Activate the virtual environment to begin using its isolated Python environment.
source tensorflow_venv/bin/activate
After activation, the shell prompt changes to indicate the active environment.
(tensorflow_venv) [user@rocky-linux tensorflow_project]$
The environment name appears in parentheses at the prompt’s beginning. This visual indicator confirms the virtual environment is active. All subsequent pip installations occur within this isolated environment rather than system-wide. The activation script modifies the PATH environment variable, ensuring the virtual environment’s Python interpreter takes precedence over the system version.
Upgrading pip Within Virtual Environment
TensorFlow requires pip version 19.0 or higher. Upgrade pip within the virtual environment to ensure compatibility.
pip install --upgrade pip
This command downloads and installs the latest pip version. Upgrading typically takes less than a minute. Verify the upgraded version.
pip --version
The output should show version 22.0 or higher, confirming pip is ready for TensorFlow installation. Modern pip versions include improved dependency resolution and security features that benefit machine learning package management.
Installing TensorFlow
Understanding TensorFlow Installation Options
TensorFlow offers several installation methods, each suited for different scenarios. The pip installation method provides simplicity and works for most users. Docker containerized installation offers reproducibility and isolation at the system level, useful for production deployments. Building from source enables optimization for specific hardware configurations but requires significant compilation time and expertise.
System-wide installation places TensorFlow in the global Python environment, while virtual environment installation maintains project isolation. Virtual environment installation is strongly recommended for development work. CPU-only TensorFlow suits general machine learning tasks, while GPU-accelerated versions dramatically improve training performance for deep neural networks.
Installing TensorFlow CPU Version
Install TensorFlow within the activated virtual environment using pip.
pip install --upgrade tensorflow
This command downloads TensorFlow and its dependencies from the Python Package Index. The installation process automatically handles dependency resolution, downloading required packages like NumPy, SciPy, and others. Installation typically takes 5-10 minutes depending on internet connection speed.
The TensorFlow package size exceeds 400MB, so patience is necessary. The installation progress displays in the terminal, showing each downloaded package. Alternative command formats achieve the same result.
pip3 install --upgrade tensorflow
Both commands work identically when executing within an activated virtual environment. The --upgrade flag ensures the latest TensorFlow version installs even if an older version exists.
Installing TensorFlow GPU Version (Optional)
GPU-accelerated TensorFlow requires NVIDIA GPU drivers, CUDA Toolkit 11.x, and cuDNN 8.x libraries installed beforehand. Rocky Linux 10 supports CUDA installation through official NVIDIA repositories. Assuming GPU prerequisites are met, install TensorFlow with GPU support.
pip install --upgrade tensorflow[and-cuda]
This command installs TensorFlow along with CUDA libraries for GPU acceleration. The installation package size is larger than the CPU version, often exceeding 500MB. GPU-accelerated TensorFlow automatically detects and utilizes available NVIDIA GPUs during training operations.
Verify GPU detection after installation.
python3 -c "import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))"
Successful GPU detection displays output listing available GPU devices. If no GPUs are detected, verify NVIDIA drivers and CUDA installation.
Verifying TensorFlow Installation
Confirm TensorFlow installed correctly by importing the library and checking its version.
python -c 'import tensorflow as tf; print(tf.__version__)'
This one-line command starts Python, imports TensorFlow, prints the version, and exits. Successful execution displays version numbers like “2.15.0” or “2.16.0” depending on the release date. Alternative verification methods include interactive Python sessions.
python3
Within the Python interpreter, execute import and version check commands.
import tensorflow as tf
print(tf.__version__)
print(tf.config.list_physical_devices())
The first print statement displays the TensorFlow version. The second lists all available physical devices including CPU and GPU. Exit the Python interpreter by typing exit() or pressing Ctrl+D.
Testing TensorFlow Functionality
Create a simple test to verify TensorFlow operations work correctly. Start Python and execute basic tensor operations.
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[5, 6], [7, 8]])
c = tf.matmul(a, b)
print(c)
This test creates two tensor matrices and performs matrix multiplication. Successful execution displays the result matrix without errors. TensorFlow automatically determines whether to use CPU or GPU for computation based on available hardware.
Running Your First TensorFlow Program
Basic TensorFlow Script
Create a standalone Python script file to test TensorFlow functionality outside the interactive interpreter. Use a text editor like nano or vim to create the file.
nano test_tensorflow.py
Add the following code to create and manipulate tensors.
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
# Create tensors
tensor_a = tf.constant([1, 2, 3, 4])
tensor_b = tf.constant([5, 6, 7, 8])
# Perform addition
tensor_sum = tf.add(tensor_a, tensor_b)
print("Tensor A:", tensor_a.numpy())
print("Tensor B:", tensor_b.numpy())
print("Sum:", tensor_sum.numpy())
# Matrix operations
matrix_a = tf.constant([[1, 2], [3, 4]])
matrix_b = tf.constant([[5, 6], [7, 8]])
matrix_product = tf.matmul(matrix_a, matrix_b)
print("Matrix Product:\n", matrix_product.numpy())
Save the file and execute it within the virtual environment.
python test_tensorflow.py
The script displays the TensorFlow version, tensor values, and computation results, confirming TensorFlow operates correctly.
MNIST Dataset Example
The MNIST handwritten digit dataset serves as the “Hello World” of machine learning. TensorFlow includes this dataset for easy testing. Create a new Python script for a complete machine learning workflow.
nano mnist_test.py
Add the following comprehensive example.
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
# Load MNIST dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize pixel values to 0-1 range
x_train, x_test = x_train / 255.0, x_test / 255.0
print(f"Training samples: {len(x_train)}")
print(f"Test samples: {len(x_test)}")
# Build neural network model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# Compile model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Train model
print("Training model...")
model.fit(x_train, y_train, epochs=5, validation_split=0.1, verbose=1)
# Evaluate model
print("\nEvaluating model...")
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)
print(f"\nTest accuracy: {test_accuracy:.4f}")
Execute the script.
python mnist_test.py
The model trains for five epochs, typically achieving 97-98% accuracy on the test set. Training time varies based on CPU performance, usually taking 2-5 minutes on modern processors. GPU acceleration reduces training time significantly.
Verifying CPU/GPU Usage
Monitor which devices TensorFlow utilizes during operations. Create a device verification script.
import tensorflow as tf
print("Available devices:")
print(tf.config.list_physical_devices())
print("\nGPU available:", tf.config.list_physical_devices('GPU'))
print("CPU available:", tf.config.list_physical_devices('CPU'))
This script lists all detected devices. GPU-enabled systems display NVIDIA GPU information including device name and memory capacity. Monitor resource usage during training using system monitoring tools like htop or nvidia-smi for GPU monitoring.
Managing Your TensorFlow Environment
Deactivating the Virtual Environment
Exit the virtual environment when finishing TensorFlow work or switching to different projects.
deactivate
The command returns the shell to its normal state, removing the environment name from the prompt. System Python and packages become active again. Deactivation doesn’t delete the virtual environment or its installed packages, merely suspending its activation.
Reactivating the Virtual Environment
Return to TensorFlow work by reactivating the virtual environment. Navigate to the project directory first.
cd ~/tensorflow_project
source tensorflow_venv/bin/activate
The environment reactivates with all previously installed packages immediately available. No reinstallation is necessary. This workflow enables efficient project switching while maintaining clean separation between different Python environments.
Managing TensorFlow Versions
Install specific TensorFlow versions when project requirements demand particular releases.
pip install tensorflow==2.13.0
This command installs TensorFlow version 2.13.0 specifically, downgrading if a newer version exists or installing fresh if none exists. Check currently installed TensorFlow version at any time.
pip list | grep tensorflow
This command filters the package list to show only TensorFlow-related packages. Upgrade to the latest version when new releases arrive.
pip install --upgrade tensorflow
The upgrade process preserves trained models and saved data, updating only the TensorFlow library code.
Dependency Management
Maintain reproducible environments by documenting installed packages. Generate a requirements file listing all packages and versions.
pip freeze > requirements.txt
This command creates a requirements.txt file containing every installed package with exact version numbers. Share this file with team members or use it to recreate identical environments elsewhere. Install from a requirements file on new systems.
pip install -r requirements.txt
This command reads the requirements file and installs all listed packages at specified versions, ensuring environment consistency across different machines or deployment targets.
Troubleshooting Common Issues
Python Version Compatibility Issues
TensorFlow supports specific Python version ranges. Attempting installation with incompatible Python versions produces errors like “Python version not supported” or “requires Python >=3.9, <3.13”. Check the current Python version.
python3 --version
If the version falls outside TensorFlow’s supported range, install a compatible Python version. Rocky Linux 10 allows multiple Python versions installed simultaneously.
sudo dnf install python3.11 -y
Create virtual environments using specific Python versions.
python3.11 -m venv tensorflow_venv_py311
This approach maintains flexibility for projects with different Python requirements.
pip Version Issues
Outdated pip versions cause installation failures with cryptic error messages. Upgrade pip before installing TensorFlow.
pip install --upgrade pip
If pip itself is broken or missing, reinstall it through the system package manager.
sudo dnf reinstall python3-pip -y
Bootstrap pip manually if dnf installation fails by downloading and running get-pip.py from the official pip website.
Missing Dependencies
Import errors like “No module named ‘tensorflow'” despite successful installation often indicate the virtual environment isn’t activated. Verify activation by checking the shell prompt for the environment name in parentheses. Activate the environment and try again.
source tensorflow_venv/bin/activate
python -c "import tensorflow as tf; print(tf.__version__)"
Missing system libraries cause build failures during installation. Install development packages comprehensively.
sudo dnf install python3-devel gcc gcc-c++ -y
These packages provide compilation tools necessary for building Python extension modules.
ImportError and Module Conflicts
Conflicting package versions create import errors. Clear pip’s cache to force fresh downloads.
pip cache purge
Remove conflicting packages before reinstalling TensorFlow.
pip uninstall tensorflow -y
pip install tensorflow
For persistent conflicts, create a fresh virtual environment from scratch, which provides a clean slate free from accumulated conflicts.
GPU Not Detected
GPU detection failures in TensorFlow typically stem from missing or misconfigured NVIDIA drivers and CUDA libraries. Verify NVIDIA drivers are installed and functioning.
nvidia-smi
This command displays GPU information including driver version, CUDA version, and current GPU usage. If the command fails, install or reinstall NVIDIA drivers. Verify CUDA toolkit installation and version compatibility with TensorFlow requirements. Check CUDA library paths are correctly configured in LD_LIBRARY_PATH environment variable.
Permission Denied Errors
Permission errors when installing packages usually indicate sudo usage within a virtual environment, which breaks the environment’s isolation. Never use sudo with pip inside virtual environments. If encountering permission errors, deactivate the environment, delete it, and recreate it without sudo usage. Proper virtual environment workflow never requires root privileges for package installation.
Best Practices and Optimization
Virtual Environment Best Practices
Create separate virtual environments for each project to maintain clean dependency separation. Use descriptive environment names reflecting project purposes. Document environment creation commands and requirements files in project documentation. Regularly audit installed packages, removing unused dependencies to minimize environment size and potential security vulnerabilities.
Store requirements.txt files in version control alongside project code. Pin package versions in production requirements files for deployment consistency. Use separate requirements files for development and production environments, as development often requires additional testing and debugging tools.
TensorFlow Performance Optimization
Configure TensorFlow logging levels to reduce console clutter during development. Set the logging level using environment variables.
export TF_CPP_MIN_LOG_LEVEL=2
Values range from 0 (all messages) to 3 (only errors). Level 2 suppresses informational and warning messages, displaying only errors.
For GPU systems, configure memory growth to prevent TensorFlow from allocating all GPU memory immediately.
gpus = tf.config.list_physical_devices('GPU')
if gpus:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
This configuration allows memory allocation to grow as needed rather than pre-allocating all available memory.
Optimize CPU performance by configuring thread pools for parallel operations.
tf.config.threading.set_inter_op_parallelism_threads(4)
tf.config.threading.set_intra_op_parallelism_threads(4)
Adjust thread counts based on CPU core availability. Data pipeline optimization through prefetching and caching significantly improves training performance.
Security Considerations
Keep TensorFlow updated to receive security patches and bug fixes. Subscribe to TensorFlow security announcements to stay informed about vulnerabilities. Scan project dependencies regularly for known security issues using tools like Safety or Snyk.
Isolate machine learning workloads from production web servers and databases to limit potential attack surface. Run TensorFlow processes with minimal necessary permissions, never as root user. Validate and sanitize all input data before feeding into models to prevent adversarial attacks.
Backup and Recovery
Maintain version-controlled requirements.txt files for environment reconstruction. Document custom configuration settings and environment variables in project README files. Backup trained models and training checkpoints regularly to prevent data loss. Use cloud storage or remote backup systems for critical machine learning assets.
Test environment recreation procedures periodically to ensure backup documentation remains accurate and complete. Maintain multiple environment snapshots at different project stages for easy rollback if problems arise.
Monitoring and Logging
Configure TensorFlow logging to capture training metrics and model performance data. Use TensorBoard for visualization of training progress, model graphs, and performance metrics. Monitor system resources during training to identify bottlenecks and optimization opportunities.
Set up alerts for training failures or performance degradation in production environments. Log all hyperparameter configurations alongside model training runs for reproducibility and comparison. Profile model execution to identify computational bottlenecks using TensorFlow Profiler.
Next Steps and Advanced Topics
Exploring TensorFlow Ecosystem
TensorFlow Extended (TFX) provides production-ready components for deploying machine learning pipelines at scale. TFX includes data validation, preprocessing, model training, evaluation, and serving components. TensorFlow Lite enables deployment to mobile and embedded devices, optimizing models for resource-constrained environments.
TensorFlow.js brings machine learning to web browsers, allowing client-side inference without server communication. TensorFlow Hub offers pre-trained models ready for transfer learning, dramatically reducing training time and data requirements for common tasks like image classification and natural language processing.
Learning Resources
The official TensorFlow documentation provides comprehensive guides, API references, and tutorials. TensorFlow certification programs offer structured learning paths and professional credentials. Community forums including Stack Overflow, Reddit’s r/MachineLearning, and TensorFlow Discuss provide peer support.
Recommended books include “Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow” by Aurélien Géron and “Deep Learning with Python” by François Chollet. Online courses from Coursera, Udacity, and Fast.ai offer structured learning with hands-on projects.
Alternative Installation Methods
Docker-based TensorFlow deployment provides consistency across different environments. Official TensorFlow Docker images include all dependencies pre-configured. Anaconda and Conda offer alternative package management with scientific computing focus. Building TensorFlow from source enables hardware-specific optimizations and custom builds.
Container platforms like Podman offer rootless container execution, improving security compared to Docker. Kubernetes orchestrates TensorFlow training across multiple nodes for distributed learning. Cloud platforms including Google Cloud AI Platform, AWS SageMaker, and Azure Machine Learning provide managed TensorFlow environments.
Production Deployment Considerations
Scale TensorFlow applications horizontally using distributed training across multiple GPUs or machines. TensorFlow Serving provides high-performance model serving for production inference workloads. Integrate TensorFlow training pipelines with CI/CD systems for automated model retraining.
Cloud deployment options include Google Kubernetes Engine, Amazon EKS, and Azure Kubernetes Service for containerized deployments. Model versioning and A/B testing enable safe model updates without service disruption. Monitoring production models for data drift and performance degradation ensures continued accuracy.
Congratulations! You have successfully installed TensorFlow. Thanks for using this tutorial for installing TensorFlow machine learning on your Rocky Linux 10 system. For additional help or useful information, we recommend you check the official TensorFlow website.