Total Pageviews

Thursday, September 10, 2026

๐Ÿง  Keras with Python Simple Two-Layer Neural Network – Real-Life House Price Prediction

๐Ÿง  Keras with Python
Simple Two-Layer Neural Network – Real-Life House Price Prediction

๐Ÿ“˜ What is Keras?

Keras is a high-level deep learning API that makes it easier to create, train, evaluate and use neural networks with Python.

Instead of manually implementing every mathematical operation of a neural network, Keras provides ready-made components such as Dense layers, activation functions, optimizers and loss functions.

Keras is commonly used for applications such as image classification, text processing, prediction, pattern recognition and many other machine-learning tasks.

๐Ÿ  Real-Life Example: House Price Prediction

Imagine a real-estate company wants to estimate the price of a house. Two important pieces of information are available:

  • ๐Ÿ“ House Area in square feet
  • ๐Ÿ›️ Number of Bedrooms

A neural network can learn the relationship between these input features and the house price.

House Area + Bedrooms
↓
Neural Network
↓
Predicted House Price

๐Ÿ”ท Two-Layer Neural Network Architecture

In this example, the neural network contains two trainable Dense layers.

๐Ÿ“ฅ
Input
2 Features
Area + Bedrooms
➡️
⚙️
Layer 1
10 Neurons
ReLU
➡️
๐Ÿ“ค
Layer 2
1 Neuron
Linear Output
2 Inputs → 10 Hidden Neurons → 1 Output

๐Ÿ“Š Sample Training Dataset

For simplicity, house prices are represented in ₹ Lakhs. The dataset below is only an educational example.

Area (sq.ft.) Bedrooms Price (₹ Lakhs)
800 2 40
1000 2 50
1200 3 65
1500 3 80
1800 4 100
2200 4 120

⚙️ Step 1: Install Required Libraries

Install TensorFlow and NumPy using:

pip install tensorflow numpy

TensorFlow provides Keras, while NumPy is used for numerical arrays.

๐Ÿ’ป Step 2: Complete Python Code

import numpy as np
from tensorflow import keras
from tensorflow.keras import layers

# --------------------------------
# 1. Training Data
# --------------------------------

# Input:
# Column 1 = House Area
# Column 2 = Number of Bedrooms

X = np.array([
    [800, 2],
    [1000, 2],
    [1200, 3],
    [1500, 3],
    [1800, 4],
    [2200, 4]
], dtype=float)

# Target values: House Price in ₹ Lakhs

y = np.array([
    40,
    50,
    65,
    80,
    100,
    120
], dtype=float)


# --------------------------------
# 2. Create Two-Layer Model
# --------------------------------

model = keras.Sequential([

    # Layer 1: Hidden Layer
    layers.Dense(
        10,
        activation="relu",
        input_shape=(2,)
    ),

    # Layer 2: Output Layer
    layers.Dense(
        1,
        activation="linear"
    )
])


# --------------------------------
# 3. Compile the Model
# --------------------------------

model.compile(
    optimizer="adam",
    loss="mean_squared_error",
    metrics=["mae"]
)


# --------------------------------
# 4. Train the Model
# --------------------------------

model.fit(
    X,
    y,
    epochs=500,
    verbose=0
)


# --------------------------------
# 5. Evaluate the Model
# --------------------------------

loss, mae = model.evaluate(
    X,
    y,
    verbose=0
)

print("Mean Absolute Error:", mae)


# --------------------------------
# 6. Predict Price of a New House
# --------------------------------

new_house = np.array([
    [1600, 3]
], dtype=float)

prediction = model.predict(
    new_house,
    verbose=0
)

print(
    "Predicted House Price:",
    prediction[0][0],
    "Lakhs"
)

๐Ÿ” Step-by-Step Code Description

1️⃣ Import NumPy and Keras

import numpy as np
from tensorflow import keras
from tensorflow.keras import layers

NumPy is used to store and process numerical data. Keras is imported from TensorFlow to create the neural network.

2️⃣ Prepare the Input Data

X = np.array([
    [800, 2],
    [1000, 2],
    [1200, 3],
    [1500, 3]
])

Each row represents one house. The first value represents the area and the second value represents the number of bedrooms.

3️⃣ Prepare the Target Values

y = np.array([
    40,
    50,
    65,
    80
])

These values represent the corresponding house prices in ₹ Lakhs.

4️⃣ Create the First Layer

layers.Dense(
    10,
    activation="relu",
    input_shape=(2,)
)

The first Dense layer contains 10 neurons. It receives two input features:

  • House Area
  • Number of Bedrooms

The ReLU activation function allows the network to learn non-linear relationships.

5️⃣ Create the Second Layer

layers.Dense(
    1,
    activation="linear"
)

The second layer contains one neuron because we want to predict one numerical value: house price.

A linear activation is suitable for a basic regression problem because the output is a continuous numerical value.

6️⃣ Compile the Model

model.compile(
    optimizer="adam",
    loss="mean_squared_error",
    metrics=["mae"]
)
  • Adam: Optimizer that updates the model parameters during training.
  • Mean Squared Error: Measures the squared difference between actual and predicted prices.
  • MAE: Mean Absolute Error, which gives the average absolute prediction error.

7️⃣ Train the Model

model.fit(
    X,
    y,
    epochs=500
)

The fit() function trains the neural network. During training, Keras adjusts the weights and biases to reduce the prediction error.

8️⃣ Predict a New House

new_house = np.array([
    [1600, 3]
])

prediction = model.predict(new_house)

The new house has:

  • ๐Ÿ“ Area = 1600 sq.ft.
  • ๐Ÿ›️ Bedrooms = 3

The trained network estimates the price of this new house.

๐Ÿงฉ Understanding the Two Layers

Layer Neurons Activation Purpose
Layer 1 10 ReLU Learns patterns from area and bedrooms.
Layer 2 1 Linear Produces the predicted house price.

๐Ÿ“ Mathematics Behind the Model

A neuron first calculates a weighted sum:

z = w₁x₁ + w₂x₂ + b

where:

  • x₁ = house area
  • x₂ = number of bedrooms
  • w₁, w₂ = learned weights
  • b = bias

The first layer applies ReLU:

ReLU(z) = max(0,z)

The output layer then produces the predicted continuous value.

Predicted Price = w₁h₁ + w₂h₂ + ... + b

๐Ÿ”„ How the Model Learns

Training Data
➡️
Neural Network
➡️
Prediction
➡️
Calculate Loss
➡️
Update Weights

This process is repeated for many epochs. The optimizer gradually changes the weights and biases so that the predicted prices become closer to the training values.

๐Ÿ–ฅ️ Example Output

Mean Absolute Error: 1.8

Predicted House Price: 85.4 Lakhs

The exact numerical result may differ slightly between runs because neural networks normally begin with randomly initialized weights.

๐Ÿ“š Important Keras Terms

Term Meaning
Sequential Creates a model where layers are arranged one after another.
Dense A fully connected neural-network layer.
ReLU Activation function commonly used in hidden layers.
Linear Suitable for producing continuous numerical outputs.
Epoch One complete pass through the training dataset.
Optimizer Algorithm used to update the model's weights and biases.

๐ŸŽฏ Summary

  1. Collect house information.
  2. Prepare input and target data.
  3. Create a Keras Sequential model.
  4. Add the first Dense layer with 10 neurons.
  5. Add the second Dense layer with 1 output neuron.
  6. Compile the model.
  7. Train the model using fit().
  8. Evaluate the model.
  9. Give a new house as input.
  10. Use predict() to estimate its price.
๐Ÿ  House Data → ๐Ÿง  Keras Model → ๐Ÿ“š Training → ๐Ÿ”ฎ Price Prediction
๐Ÿง  Keras & Python Neural Network Learning Module
Created by Bijan Krishna Paul

No comments:

Post a Comment