Keras Binary Classification with Sequential Model

In this tutorial, you’ll learn how to implement binary classification with Keras using the Sequential model. This beginner-friendly guide walks you through data prep, model building, training, and prediction—all using standalone Keras.

Binary classification is a supervised learning task where we classify data into one of two classes (e.g., Spam or Not Spam, Fraud or Legitimate).

Binary classification is a type of machine learning task where the goal is to classify inputs into one of two categories.


Real-World Examples:

  • Spam vs  Not Spam (email filtering)

  •  Disease vs  No Disease (medical diagnosis)

  •  Customer will churn vs  Will stay (business analytics)

  • Fraudulent vs  Legitimate transaction (finance)


How It Works:

A binary classifier learns from labeled data, where each example is tagged as class 0 or 1. It then tries to predict the correct label for new, unseen examples.


Output:

Typically:

  • The model outputs a probability between 0 and 1

  • Then applies a threshold (e.g., 0.5) to decide:

    • > 0.5 → Class 1

    • ≤ 0.5 → Class 0

This tutorial demonstrates how to build a simple binary classifier using only standalone Keras.

Why Use Keras for Binary Classification?

Keras is a powerful and beginner-friendly deep learning library that makes building neural networks super simple. It’s built for ease of use, speed of experimentation, and scalability.


Top Reasons to Use Keras:

1. Easy to Learn & Use

  • Intuitive API — you can build a model in just a few lines of code.

  • Ideal for beginners and prototyping.

2. Built on Top of TensorFlow

  • Combines simplicity with the power and performance of TensorFlow.

  • Easily scalable for large datasets or GPU training.

3. Modular & Flexible

  • You can plug in different layers, loss functions, optimizers, etc., like Lego blocks.

  • Supports both Sequential and Functional APIs.

4. Well-Documented & Actively Maintained

  • Tons of tutorials, guides, and community support.

  • Maintained by the TensorFlow team at Google.

5. Real-World Ready

  • Used in industry and research for everything from image classification to NLP and reinforcement learning.

Model architecture:

New to Keras?
Explore the official docs here: Keras Documentation

Building a Binary Classification Model with Keras:

 

1. Install Dependencies:

pip install keras

2. Import Required Libraries:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

3. Generate Sample Dataset:

# Generate synthetic data
np.random.seed(42)
X = np.random.rand(1000, 2)  # 1000 samples, 2 features
y = (X[:, 0] + X[:, 1] > 1).astype(int)  # Label: 1 if sum > 1, else 0

# Split into train & test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Normalize the data
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

4. Build the Keras Model:

# Define the model
model = Sequential([
    Dense(16, activation='relu', input_shape=(2,)),  # Input layer
    Dense(8, activation='relu'),  # Hidden layer
    Dense(1, activation='sigmoid')  # Output layer for binary classification
])

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

5. Train the Model:

# Train the model
model.fit(X_train, y_train, epochs=20, batch_size=32, validation_data=(X_test, y_test))

Output:

6. Evaluate the Model:

loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy:.4f}")

output:

7/7 ━━━━━━━━━━━━━━━━━━━━ 0s 14ms/step - accuracy: 0.9892 - loss: 0.0632
Test Accuracy: 0.9950

7. Make Predictions:

# Predict on new data
new_data = np.array([[0.2, 0.8]])  # Example input
new_data = scaler.transform(new_data)  # Scale it
prediction = model.predict(new_data)
predicted_class = (prediction > 0.5).astype(int)
print(f"Predicted Class: {predicted_class[0][0]}")

output:

1/1 ━━━━━━━━━━━━━━━━━━━━ 0s 144ms/step
Predicted Class: 1

Internal Resources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top