Of course! Here is a comprehensive guide to setting up and using Keras on Ubuntu, covering everything from installation to a simple "Hello World" example.

This guide will focus on the modern, recommended approach: Keras as part of TensorFlow.
Part 1: Installation on Ubuntu
This is the most critical part. We'll use a virtual environment to keep your projects clean and isolated.
Step 1: System Prerequisites
First, ensure your system is up-to-date and has the necessary build tools.
# Update your package list sudo apt update # Install essential build tools and Python libraries sudo apt install -y python3-pip python3-venv build-essential
Step 2: Create and Activate a Virtual Environment
It's a best practice to use a virtual environment for each Python project to avoid dependency conflicts.

# Create a directory for your project (optional but good practice) mkdir my_keras_project cd my_keras_project # Create a virtual environment named 'venv' python3 -m venv venv # Activate the virtual environment source venv/bin/activate # Your terminal prompt should now change to show (venv)
Step 3: Install TensorFlow (which includes Keras)
Now that your virtual environment is active, you can install TensorFlow using pip. TensorFlow 2.x has Keras integrated directly into it as tf.keras.
# Upgrade pip to the latest version pip install --upgrade pip # Install TensorFlow pip install tensorflow
Optional: Install for GPU Support If you have a compatible NVIDIA GPU and want to leverage it for faster training, you need to install a different version of TensorFlow and the CUDA/cuDNN toolkit.
- Check GPU Compatibility: Ensure you have a recent NVIDIA GPU.
- Install NVIDIA Drivers: Install the latest drivers for your GPU.
- Install CUDA Toolkit: Download and install the version of CUDA required by your TensorFlow version (check the TensorFlow GPU support page for details).
- Install cuDNN: Download and install the cuDNN library that matches your CUDA version.
- Install GPU-enabled TensorFlow:
pip install tensorflow[and-cuda]
Step 4: Verify the Installation
To make sure everything is working, run Python and check the versions.
# In your activated virtual environment python
Now, in the Python interpreter:

import tensorflow as tf
import keras
print("TensorFlow Version:", tf.__version__)
print("Keras Version:", keras.__version__)
# Test if TensorFlow can detect a GPU (optional)
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
Press Ctrl+D or type exit() to leave the Python interpreter. If the versions print without errors, your installation is successful!
Part 2: Your First Keras Model (A Simple Example)
Let's build a simple neural network to classify handwritten digits from the famous MNIST dataset. This is the "Hello World" of deep learning.
Import Libraries
Create a Python file (e.g., mnist_model.py) and add the following imports:
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np import matplotlib.pyplot as plt
Load and Prepare the Data
Keras provides the MNIST dataset directly. We'll load it, normalize the pixel values, and prepare it for training.
# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Normalize pixel values to be between 0 and 1
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
# Reshape images to add a channel dimension (for CNNs)
# For a simple model, we can flatten them later. Let's keep them as 28x28 for now.
# x_train = x_train.reshape((-1, 28, 28, 1))
# x_test = x_test.reshape((-1, 28, 28, 1))
print("x_train shape:", x_train.shape)
print(x_train.shape[0], "train samples")
print(x_test.shape[0], "test samples")
Build the Model
We'll use the Keras Sequential API, which is perfect for a simple stack of layers.
model = keras.Sequential(
[
# Input layer: Flatten the 28x28 image into a 1D vector of 784 pixels
keras.Input(shape=(28, 28)),
layers.Flatten(),
# Hidden layer: A dense (fully connected) layer with 128 neurons
# 'relu' (Rectified Linear Unit) is a common activation function
layers.Dense(128, activation="relu"),
# Dropout layer: A regularization technique to prevent overfitting
layers.Dropout(0.2),
# Output layer: A dense layer with 10 neurons (one for each digit 0-9)
# 'softmax' activation converts the output into a probability distribution
layers.Dense(10, activation="softmax"),
]
)
Compile the Model
Before training, we need to configure the model with a loss function, an optimizer, and metrics.
model.compile(
optimizer="adam", # Adam is a popular and effective optimizer
loss="sparse_categorical_crossentropy", # Good for multi-class classification with integer labels
metrics=["accuracy"], # We want to monitor the accuracy during training
)
Train the Model
Now, we fit the model to our training data.
batch_size = 128
epochs = 15
history = model.fit(
x_train,
y_train,
batch_size=batch_size,
epochs=epochs,
validation_split=0.1, # Use 10% of training data for validation
)
You will see the training progress for each epoch, showing the loss and accuracy on both the training and validation sets.
Evaluate the Model
Let's see how our model performs on the test set it has never seen before.
score = model.evaluate(x_test, y_test, verbose=0)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
Make a Prediction
Let's use our trained model to predict the digit for a single image from the test set.
# Pick a random test image
index = 5
image_to_predict = x_test[index]
true_label = y_test[index]
# The model expects a batch of images, so we add a dimension
image_to_predict = np.expand_dims(image_to_predict, axis=0)
# Make the prediction
prediction = model.predict(image_to_predict)
predicted_label = np.argmax(prediction)
print(f"True Label: {true_label}")
print(f"Predicted Label: {predicted_label}")
# Display the image
plt.imshow(x_test[index], cmap='gray')f"True: {true_label}, Predicted: {predicted_label}")
plt.show()
Part 3: Essential Tips and Troubleshooting
Common Issues:
-
ModuleNotFoundError: No module named 'tensorflow'- Cause: You are not in the activated virtual environment, or you installed TensorFlow outside of it.
- Solution: Make sure your terminal prompt shows
(venv)at the beginning and that you runpip install tensorflowafter activating the environment.
-
Slow Training (CPU-only)
- Cause: TensorFlow is using your CPU for computations. This is expected if you don't have a compatible GPU or haven't installed the GPU-enabled version.
- Solution: If you have a good NVIDIA GPU, follow the steps for GPU installation. Training will be significantly faster.
-
CUDA/cuDNN Mismatch Errors
- Cause: The version of CUDA or cuDNN you installed does not match the version required by your TensorFlow build.
- Solution: Carefully check the official TensorFlow installation guide for the exact versions required and ensure you install them correctly.
Useful Resources:
- Official Keras Documentation: https://keras.io/ - The ultimate source of truth.
- Official TensorFlow Tutorials: https://www.tensorflow.org/tutorials - Excellent, step-by-step guides for all levels.
- Keras Examples on GitHub: https://github.com/keras-team/keras/tree/master/examples - Great for seeing more complex models in action.
This guide should give you a solid foundation for working with Keras on Ubuntu. Happy coding
