Saving & Exporting Deep Learning Models

Model को train करने के बाद उसे save करना ज़रूरी होता है ताकि उसे:

  • Future में reuse किया जा सके
  • Production में deploy किया जा सके
  • किसी और प्लेटफॉर्म पर इस्तेमाल किया जा सके (e.g., mobile, web, edge devices)

🔷 🔹 Why Save Models?

ReasonBenefit
Training time बचानाबार-बार retrain करने की ज़रूरत नहीं
Deployment possibleWeb, mobile, or production में model use
Sharing & Reuseदूसरों से share करना या reuse करना

🔶 1. PyTorch में Model Saving & Loading

✅ 1.1 Only Weights Save करें

torch.save(model.state_dict(), "model_weights.pth")

🔁 Load Only Weights

model = MyNet()  # same structure
model.load_state_dict(torch.load("model_weights.pth"))
model.eval()

✅ 1.2 Save Full Model (Structure + Weights)

torch.save(model, "full_model.pth")

🔁 Load Full Model

model = torch.load("full_model.pth")
model.eval()

⚠️ Recommended method: save state_dict() instead of full model, for more flexibility and safety.


✅ 1.3 Export for Production (TorchScript)

example_input = torch.randn(1, 2)
traced = torch.jit.trace(model, example_input)
traced.save("model_scripted.pt")

🔁 Load TorchScript Model

model = torch.jit.load("model_scripted.pt")
model.eval()

🔶 2. TensorFlow / Keras में Model Saving

✅ 2.1 Save Entire Model (.h5 or .keras)

model.save("my_model.h5")
# OR
model.save("my_model.keras") # Recommended in latest TF

🔁 Load:

from tensorflow.keras.models import load_model
model = load_model("my_model.h5")

✅ 2.2 Save Weights Only

model.save_weights("weights.h5")

🔁 Load Weights:

model = build_model()  # Define same structure
model.load_weights("weights.h5")

✅ 2.3 Export to TensorFlow Lite (for Mobile/IoT)

converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

with open("model.tflite", "wb") as f:
f.write(tflite_model)

✅ 2.4 Export to TF.js (Browser Use)

pip install tensorflowjs
tensorflowjs_converter --input_format keras my_model.h5 web_model/

📝 Practice Questions:

  1. PyTorch में state_dict क्या होता है और क्यों ज़रूरी है?
  2. Keras में .h5 और .keras में क्या अंतर है?
  3. TorchScript और ONNX में क्या उपयोगिता है?
  4. TensorFlow Lite क्यों और कब use करते हैं?
  5. Model को JSON या TF.js में कैसे export किया जाता है?

🔚 Summary Table

FrameworkSave WeightsSave Full ModelExport Option
PyTorchstate_dict()torch.save()TorchScript / ONNX
Kerassave_weights()model.save()TF Lite, TF.js
TensorFlowcheckpointSavedModel formatTensorFlow Serving

Evaluation Metrics – Confusion Matrix, Precision, Recall

अब हम Deep Learning में सबसे ज़रूरी और ज़्यादा इस्तेमाल होने वाले Evaluation Metrics — विशेषकर Confusion Matrix, Precision, और Recall — को पूरी गहराई से समझेंगे।


🔷 1. What Are Evaluation Metrics?

Evaluation metrics यह मापने के लिए होते हैं कि trained model कितनी सही predictions कर पा रहा है — खासकर classification problems में।


🔶 2. Confusion Matrix (गड़बड़ी मैट्रिक्स)

Confusion matrix classification prediction को चार हिस्सों में तोड़ता है:

Predicted PositivePredicted Negative
Actual Positive (1)✅ TP (True Positive)❌ FN (False Negative)
Actual Negative (0)❌ FP (False Positive)✅ TN (True Negative)

🤖 ये matrix binary और multi-class दोनों में काम करता है।


✅ Python Code (PyTorch compatible)

from sklearn.metrics import confusion_matrix

y_true = [0, 1, 0, 1, 1, 0] # Ground truth
y_pred = [0, 1, 1, 1, 0, 0] # Model predictions

cm = confusion_matrix(y_true, y_pred)
print("Confusion Matrix:\n", cm)

Output:

[[2 1]
[1 2]]

यह कहता है:

  • 2 True Negatives (class 0 सही predict किया)
  • 1 False Positive
  • 1 False Negative
  • 2 True Positives

🔶 3. Precision (सटीकता)

Definition:

Model ने जितने positive predict किए, उनमें से कितने सच में positive थे?

Precision = TP / (TP + FP)

✅ Example:

Model ने 10 images को “cat” कहा, पर केवल 6 ही असली cat थीं →
Precision = 6 / 10 = 0.60

✅ Code:

from sklearn.metrics import precision_score
precision = precision_score(y_true, y_pred)
print("Precision:", precision)

🔶 4. Recall (Sensitivity / True Positive Rate)

Definition:

Total actual positive samples में से कितनों को model ने सही predict किया?

Recall = TP / (TP + FN)

✅ Example:

10 में से 8 असली cats थीं, और model ने 6 को correctly पकड़ा →
Recall = 6 / 8 = 0.75

✅ Code:

from sklearn.metrics import recall_score
recall = recall_score(y_true, y_pred)
print("Recall:", recall)

🔶 5. F1 Score (Precision + Recall का Balance)

Definition:

Precision और Recall का harmonic mean:

F1 = 2 * (Precision * Recall) / (Precision + Recall)

✅ Code:

from sklearn.metrics import f1_score
f1 = f1_score(y_true, y_pred)
print("F1 Score:", f1)

🔷 🔍 Visualization (Optional)

import seaborn as sns
import matplotlib.pyplot as plt

sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel("Predicted")
plt.ylabel("Actual")
plt.title("Confusion Matrix")
plt.show()

🧠 कब क्या Use करें?

MetricUse When…
AccuracyData balanced हो
PrecisionFalse Positive से बचना ज़रूरी हो (e.g. spam)
RecallFalse Negative से बचना ज़रूरी हो (e.g. cancer detection)
F1 ScorePrecision और Recall दोनों ज़रूरी हों

📝 Objective Questions:

  1. Confusion matrix के 4 parts क्या होते हैं?
  2. Precision और Recall में अंतर क्या है?
  3. Precision कब ज़्यादा important होता है?
  4. f1_score metric कब use करते हैं?
  5. Confusion matrix का visualization कैसे करें?

🔚 Summary

MetricFormulaMeaning
PrecisionTP / (TP + FP)Predicted Positives में से सही कितने
RecallTP / (TP + FN)Actual Positives में से सही कितने
F1 ScoreHarmonic mean of P & RBalance of both metrics
Confusion MatrixTP, FP, FN, TNOverall prediction structure

What is Model Evaluation and Deployment

अब आपने deep learning models बनाना, train करना और save/load करना सीख लिया है — अगला ज़रूरी कदम है:Model Evaluation and Deployment

🔷 Part 1: 📊 Model Evaluation

Model को train करने के बाद यह जानना ज़रूरी है कि वो कितना अच्छा काम कर रहा है — इसके लिए हम evaluation metrics का उपयोग करते हैं।


✅ 1. Accuracy (शुद्धता)

  • Classification के लिए सबसे आम metric
  • Formula:
    Accuracy = सही अनुमान / कुल उदाहरण
# Keras
model.evaluate(X_test, y_test)

# PyTorch
with torch.no_grad():
preds = model(X_test)
predicted = preds.round()
acc = (predicted == y_test).float().mean()

✅ 2. Confusion Matrix

Classification output को True Positives, False Positives, True Negatives, और False Negatives में बांटता है।

from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_true, y_pred))

✅ 3. Precision, Recall, F1 Score

MetricMeaning
PrecisionPositive prediction में से कितने सही थे
Recallकितने actual positive सही पकड़े गए
F1 ScorePrecision और Recall का balance
from sklearn.metrics import classification_report
print(classification_report(y_true, y_pred))

✅ 4. Loss Curve / Accuracy Curve (Visualization)

import matplotlib.pyplot as plt

plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label='val_loss')
plt.legend()
plt.show()

🔷 Part 2: 🚀 Model Deployment

Model को दुनिया तक पहुँचाने के लिए हमें उसे deploy करना पड़ता है — यानी किसी app, API, या web server पर चलाना।


✅ 1. Deployment Methods:

MethodUse Case
Flask APISimple Web/API deployment
TensorFlow ServingProduction-ready serving
TorchScriptPyTorch model serialization
ONNXCross-platform compatibility
TF LiteMobile apps (Android/iOS)
TF.jsBrowser-based models
Gradio / StreamlitQuick UI + demo

✅ 2. PyTorch Model Export (TorchScript)

traced_model = torch.jit.trace(model, torch.rand(1, 2))
traced_model.save("model.pt")

Use in any PyTorch-enabled environment.


✅ 3. TensorFlow/Keras Model Export

pythonCopyEditmodel.save("model.h5")  # Full model (Keras)

Convert to TF Lite for mobile:

converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)

✅ 4. Simple Flask API for Inference

from flask import Flask, request, jsonify
import torch

app = Flask(__name__)
model = torch.load("model.pt")
model.eval()

@app.route('/predict', methods=['POST'])
def predict():
data = request.json
input_tensor = torch.tensor(data['input'])
with torch.no_grad():
prediction = model(input_tensor).item()
return jsonify({'prediction': prediction})

app.run(debug=True)

✅ 5. Deployment Tools

ToolPurpose
DockerContainerize model + environment
KubernetesDeploy at scale
HerokuSimple web hosting
AWS/GCP/AzureCloud deployment
Hugging Face SpacesDeploy public demos

📝 Practice Questions:

  1. Accuracy और F1-score में क्या अंतर है?
  2. PyTorch में confusion matrix कैसे calculate करते हैं?
  3. Model को Flask API में कैसे deploy किया जाता है?
  4. torch.jit.trace() और model.save() में क्या अंतर है?
  5. TensorFlow Lite का उपयोग कब और क्यों करना चाहिए?

🧠 Summary Table

TaskPyTorchTensorFlow/Keras
Accuracy Eval(preds == y).float().mean()model.evaluate()
Save for Deploymenttorch.jit.save()model.save()
MobileONNX or TorchScriptTF Lite
APIFlask/FastAPIFlask/FastAPI
Web UIGradio / StreamlitGradio / Streamlit

Using GPUs and TPUs in Deep Learning

अब जब आप PyTorch और Keras दोनों में model बना और train कर रहे हैं, तो performance boost के लिए GPU/TPU का इस्तेमाल करना ज़रूरी हो जाता है — खासकर बड़े datasets या deep models के लिए।


🔷 1. 🔥 Why Use GPUs?

CPU vs GPUGPU Advantage
SequentialParallel computing
Few coresThousands of cores
Slower matrix opsFaster tensor operations
General-purposeSpecial for ML/DL, CUDA-optimized

🔶 PyTorch में GPU का उपयोग कैसे करें?

✅ Step 1: Check GPU Availability

import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)

✅ Step 2: Model और Data को GPU पर भेजना

model = MyNet().to(device)  # Model को GPU पर भेजें
X = X.to(device)
y = y.to(device)

✅ Training Code में बदलाव:

for epoch in range(1000):
y_pred = model(X)
loss = criterion(y_pred, y)

optimizer.zero_grad()
loss.backward()
optimizer.step()

बस यह ध्यान रखें कि model और data दोनों एक ही device पर होने चाहिए


🔷 2. GPU से Prediction (Inference)

model.eval()
with torch.no_grad():
test = torch.tensor([[1., 0.]]).to(device)
output = model(test)
print("Prediction:", output.item())

🔷 3. Keras (TensorFlow) में GPU का उपयोग

TensorFlow अपने आप GPU को detect करता है और उपयोग करता है (अगर उपलब्ध हो)। बस ensure करें कि:

  • TensorFlow-GPU version install हो
  • NVIDIA Drivers + CUDA Toolkit सही से install हो

✅ Check GPU:

import tensorflow as tf
print("Num GPUs Available:", len(tf.config.list_physical_devices('GPU')))

✅ Tensor और Model GPU पर चलेंगे अपने आप:

model.fit(X, y, epochs=10)  # If GPU available, TensorFlow will use it

✅ Manually GPU select करना:

with tf.device('/GPU:0'):
model = tf.keras.Sequential([...])
model.compile(...)
model.fit(...)

🔷 4. Google Colab में GPU/TPU Use

✅ GPU Enable करें:

Runtime → Change runtime type → Hardware accelerator → GPU or TPU

✅ Check GPU/TPU:

import tensorflow as tf
print(tf.config.list_physical_devices('GPU')) # For GPU
print(tf.config.list_logical_devices('TPU')) # For TPU

🔷 5. TPUs क्या होते हैं?

AspectDetail
TPUTensor Processing Unit (Google द्वारा बनाया गया)
SpeedGPU से भी तेज़ है कुछ tasks में
Best forVery large models, production-level serving
UseMainly in Google Colab, Cloud TPUs, TensorFlow

📝 Practice Questions:

  1. PyTorch में GPU support कैसे check करते हैं?
  2. Model को GPU पर भेजने के लिए कौनसा syntax है?
  3. TensorFlow GPU vs TPU में क्या अंतर है?
  4. Google Colab में GPU enable कैसे करते हैं?
  5. क्या CPU से GPU training में फर्क आता है?

🧠 Summary Table

TaskPyTorchKeras (TF)
GPU Checktorch.cuda.is_available()tf.config.list_physical_devices()
Send to GPUx.to(device)Automatic
Model to GPUmodel.to(device)Automatic
Use Colab GPURuntime > Change > GPUSame
TPU Support❌ (Limited)✅ (Good)

Model Training, Saving, and Loading in Keras

अब हम Keras (जो TensorFlow का high-level API है) में Deep Learning Model को Train, Save, और Load करना सीखेंगे — step-by-step और practical examples के साथ।


🔷 1. ✅ Model Training in Keras (Step-by-Step)

📌 Step 1: Import Libraries

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

📌 Step 2: Define Model

model = Sequential([
Dense(8, activation='relu', input_shape=(2,)),
Dense(1, activation='sigmoid')
])

📌 Step 3: Compile Model

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

📌 Step 4: Prepare Data

import numpy as np

X = np.array([[0,0], [0,1], [1,0], [1,1]])
y = np.array([0, 1, 1, 0])

📌 Step 5: Train Model

model.fit(X, y, epochs=100, batch_size=2, verbose=1)

🔷 2. 💾 Saving a Keras Model

✅ Option 1: Save Full Model (Best Practice)

model.save("my_model.h5")  # Saves architecture + weights + optimizer state

OR in newer format:

model.save("my_model.keras")  # New native format

✅ Option 2: Save Only Weights

model.save_weights("model_weights.h5")

🔷 3. 📂 Loading a Saved Model

✅ Load Full Model:

from tensorflow.keras.models import load_model

model = load_model("my_model.h5")

This will return the model ready to use — no need to recompile or redefine.


✅ Load Only Weights:

First define the model architecture same as before:

model = Sequential([
Dense(8, activation='relu', input_shape=(2,)),
Dense(1, activation='sigmoid')
])

Then load the weights:

model.load_weights("model_weights.h5")

🔷 4. 🔁 Save and Load during Training (Checkpointing)

✅ Use ModelCheckpoint Callback

from tensorflow.keras.callbacks import ModelCheckpoint

checkpoint = ModelCheckpoint("best_model.h5", save_best_only=True, monitor="loss")

model.fit(X, y, epochs=50, callbacks=[checkpoint])

🔷 5. 🧪 Inference (Prediction)

pred = model.predict(np.array([[1, 0]]))
print("Prediction:", pred[0][0])

🧠 Use .predict() method for classification, regression, or output generation.


🔧 Extra: Exporting to TF Lite (Mobile/Edge)

converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

with open('model.tflite', 'wb') as f:
f.write(tflite_model)

📝 Practice Questions:

  1. Keras में model train करने के steps क्या हैं?
  2. .h5 और .keras में क्या अंतर है?
  3. model.save() और model.save_weights() में क्या फर्क है?
  4. Training के दौरान best model कैसे save करते हैं?
  5. Model load करने के बाद inference कैसे करते हैं?

🧠 Summary Table

TaskKeras Method
Train Modelmodel.fit()
Save Full Modelmodel.save("model.h5")
Save Only Weightsmodel.save_weights()
Load Full Modelload_model("model.h5")
Load Weights Onlymodel.load_weights()
Predict / Inferencemodel.predict(x)
Save Best during TrainingModelCheckpoint(callback)