๐ 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.
↓
Neural Network
↓
Predicted House Price
๐ท Two-Layer Neural Network Architecture
In this example, the neural network contains two trainable Dense layers.
2 Features
Area + Bedrooms
10 Neurons
ReLU
1 Neuron
Linear 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:
where:
- x₁ = house area
- x₂ = number of bedrooms
- w₁, w₂ = learned weights
- b = bias
The first layer applies ReLU:
The output layer then produces the predicted continuous value.
๐ How the Model Learns
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
- Collect house information.
- Prepare input and target data.
- Create a Keras Sequential model.
- Add the first Dense layer with 10 neurons.
- Add the second Dense layer with 1 output neuron.
- Compile the model.
- Train the model using
fit(). - Evaluate the model.
- Give a new house as input.
- Use
predict()to estimate its price.
Created by Bijan Krishna Paul
No comments:
Post a Comment