Build Your First Neural Network in Python Using Keras

Recently, I was working on a small project to predict customer satisfaction scores for a retail store in the USA. I wanted to experiment with a simple neural network using Python and Keras to see how accurately I could model the data.

The problem was that most tutorials I found were either too advanced or skipped important steps. So, I decided to create this simple, step-by-step Python guide to help beginners build their first neural network in Keras, the easy way.

In this tutorial, I’ll walk you through everything, from setting up your Python environment to training and evaluating your first neural network. Even if you’ve never built a neural network before, by the end of this article, you’ll have a working model and a solid understanding of how it all fits together.

What is a Neural Network?

A neural network is a machine learning model inspired by how the human brain works.
It consists of layers of neurons (nodes) that process data and learn patterns to make predictions.

In Python, the Keras library (which runs on top of TensorFlow) makes it incredibly simple to build and train neural networks. You don’t need to be a math expert; just some basic Python knowledge is enough to get started.

Set Up the Python Environment

Before we start coding, let’s set up our Python environment. You’ll need to install the following libraries:

pip install tensorflow numpy pandas scikit-learn

Once installed, open your favorite Python IDE (like VS Code, PyCharm, or Jupyter Notebook). We’re now ready to build our first neural network in Python using Keras.

Step 1 – Import the Required Python Libraries

First, we’ll import all the necessary Python libraries. These include TensorFlow (for Keras), NumPy (for numerical operations), and scikit-learn (for data splitting and scaling).

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow import keras
from tensorflow.keras import layers

This setup ensures we have all the tools we need for data handling, model building, and evaluation.

Step 2 – Prepare the Dataset

For this example, I’ll use a synthetic dataset that simulates customer satisfaction scores for a retail store in the USA. Each record includes features like age, income, store visits, and purchase frequency.

Let’s create a small dataset using Python and NumPy.

# Create a sample dataset using NumPy
np.random.seed(42)
data_size = 1000

age = np.random.randint(18, 70, data_size)
income = np.random.randint(30000, 120000, data_size)
visits = np.random.randint(1, 10, data_size)
purchases = np.random.randint(1, 5, data_size)

# Target variable (satisfaction score between 0 and 1)
satisfaction = (0.3 * (income / 120000) + 0.2 * (visits / 10) + 0.5 * (purchases / 5)) + np.random.normal(0, 0.05, data_size)
satisfaction = np.clip(satisfaction, 0, 1)

# Combine into a pandas DataFrame
df = pd.DataFrame({
    'Age': age,
    'Income': income,
    'Visits': visits,
    'Purchases': purchases,
    'Satisfaction': satisfaction
})

print(df.head())

This dataset mimics real-world behavior; higher income and more purchases usually lead to higher satisfaction.

Step 3 – Split the Data into Training and Testing Sets

Next, we’ll separate our features and target variable, then split them into training and testing sets. This allows the neural network to learn from one part of the data and be evaluated on unseen data.

# Define features (X) and target (y)
X = df[['Age', 'Income', 'Visits', 'Purchases']]
y = df['Satisfaction']

# Split the dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Scale the features for better model performance
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

Scaling ensures that all features contribute equally to the learning process.

Step 4 – Build the Neural Network Model in Python

Now comes the fun part: building the neural network. We’ll use Keras’ Sequential API to stack layers one after another.

# Build the neural network
model = keras.Sequential([
    layers.Dense(16, activation='relu', input_shape=(X_train_scaled.shape[1],)),
    layers.Dense(8, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

# Compile the model
model.compile(optimizer='adam', loss='mse', metrics=['mae'])

Here’s what each part does:

  • Dense layers are fully connected layers that learn relationships between inputs and outputs.
  • Activation functions like ReLU and Sigmoid help the model learn complex, non-linear patterns.
  • Adam optimizer automatically adjusts learning rates for faster convergence.

Step 5 – Train the Neural Network

Once the model is built, we can train it using our training data. Keras makes this easy with the fit() function.

# Train the model
history = model.fit(X_train_scaled, y_train, epochs=50, batch_size=32, validation_split=0.2, verbose=1)

This code trains the model for 50 epochs, meaning it will go through the dataset 50 times to improve accuracy. The validation split helps monitor performance on unseen data during training.

Step 6 – Evaluate the Model

After training, we’ll evaluate the model on the test data to see how well it performs. We’ll measure the mean absolute error (MAE), the smaller, the better.

# Evaluate the model
test_loss, test_mae = model.evaluate(X_test_scaled, y_test)
print(f"Test MAE: {test_mae:.4f}")

If your MAE is below 0.05, you’ve built a pretty solid model for this simple dataset.

Step 7 – Make Predictions with the Neural Network

Now that our Python neural network is trained, let’s use it to make predictions. We’ll predict satisfaction scores for a few new customers.

# Predict satisfaction for new data
new_customers = np.array([[35, 75000, 5, 3],
                          [50, 45000, 2, 1],
                          [28, 98000, 8, 4]])

new_customers_scaled = scaler.transform(new_customers)
predictions = model.predict(new_customers_scaled)

print("Predicted Satisfaction Scores:")
print(predictions)

This step shows how easily you can deploy your trained neural network to predict real-world outcomes.

Step 8 – Visualize Training Progress (Optional)

It’s always helpful to visualize how your model’s performance improved over time. We can use Matplotlib to plot the loss and MAE curves.

import matplotlib.pyplot as plt

plt.plot(history.history['mae'], label='Training MAE')
plt.plot(history.history['val_mae'], label='Validation MAE')
plt.title('Model Accuracy Over Epochs')
plt.xlabel('Epochs')
plt.ylabel('Mean Absolute Error')
plt.legend()
plt.show()

You can refer to the screenshot below to see the output.

C:\Users\GradyArchie\Downloads\images\Build Your First Neural Network in Python Using Keras.jpg

This gives you a quick visual understanding of how well your neural network learned during training.

Alternate Method – Use the Functional API in Keras

If you want more flexibility, you can build the same neural network using the Keras Functional API. This approach is useful when your model has multiple inputs or outputs.

# Functional API example
inputs = keras.Input(shape=(X_train_scaled.shape[1],))
x = layers.Dense(16, activation='relu')(inputs)
x = layers.Dense(8, activation='relu')(x)
outputs = layers.Dense(1, activation='sigmoid')(x)

model_func = keras.Model(inputs, outputs)
model_func.compile(optimizer='adam', loss='mse', metrics=['mae'])
model_func.fit(X_train_scaled, y_train, epochs=50, batch_size=32, validation_split=0.2)

Both methods produce similar results, but the Functional API gives you more control over complex architectures.

Key Takeaways

  • Python and Keras make it easy to build neural networks without deep math knowledge.
  • Always scale your features before training.
  • Use ReLU for hidden layers and Sigmoid for output layers in regression-like tasks.
  • Start small — fewer layers can often perform surprisingly well.

When I first built this model, I was amazed at how simple and powerful Python’s Keras library made the process. From defining layers to training and evaluating results, everything felt intuitive and beginner-friendly.

If you follow the steps above, you’ll not only build your first neural network in Python but also understand how each part contributes to the final prediction. As you gain confidence, you can experiment with deeper networks, dropout layers, or even convolutional models for image tasks.

You may also like to read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.