Self-Supervised Learning (SSL)

अब हम Deep Learning के एक cutting-edge topic की ओर बढ़ते हैं:

🔍 “Learn from data itself – without explicit labels.”


🔷 1. What is Self-Supervised Learning?

Self-Supervised Learning (SSL) एक ऐसी approach है जिसमें model को बिना manually labeled data के train किया जाता है।
👉 ये unlabeled data से ही pseudo labels generate करता है।

Goal: Supervised learning जैसी performance, लेकिन बिना manually labeled dataset के।


🔶 2. SSL क्यों ज़रूरी है?

समस्यासमाधान
Labeling data महंगा हैSSL human labeling को minimize करता है
कई domains में unlabeled data abundant हैSSL उससे फायदा उठाता है
Pretraining + Fine-tuning = बेहतर generalizationSSL मॉडल transferable बनाता है

🔷 3. SSL कैसे काम करता है?

✅ Key Idea:

Model खुद ही input के कुछ हिस्सों से दूसरा हिस्सा predict करने का task सीखता है।

SSL Task Typeउदाहरण
ContrastiveTwo similar images → close representations
Masked modelingSentence का हिस्सा छिपा दो → predict करो
Pretext tasksRotation predict करना, Colorization, etc.

🔶 4. Popular Self-Supervised Tasks

✅ A. Contrastive Learning (Image)

एक ही object के दो augmentations → similar representation
अलग-अलग object → दूर representation

  • Frameworks: SimCLR, MoCo, BYOL
Loss = NT-Xent (Normalized Temperature-scaled Cross Entropy)

✅ B. Masked Language Modeling (NLP)

Input में कुछ tokens को mask करो, फिर उन्हें predict करो
जैसे BERT करता है

Input: "I like [MASK] learning."  
Target: "deep"

✅ C. Autoencoding

Input से खुद को reconstruct करना

  • Example: Autoencoders, Variational Autoencoders

✅ D. Predict Context (Next Frame, Next Word, etc.)

  • Next Word Prediction: GPT जैसे models
  • Next Frame Prediction: Video prediction tasks

🔷 5. Examples of SSL in Practice

Model / MethodDomainTechnique
BERTNLPMasked token prediction
SimCLRVisionContrastive loss
BYOL, MoCoVisionMomentum encoder
GPTNLPNext token prediction
MAE (Masked Autoencoders)VisionMask patches, reconstruct

🔶 6. Advantages of Self-Supervised Learning

✅ Manual labels की dependency नहीं
✅ Large-scale data से बेहतर generalization
✅ Transfer learning के लिए बेहतरीन
✅ Few-shot या Zero-shot tasks में useful


🔶 7. Self-Supervised vs Unsupervised vs Supervised

MethodLabels RequiredExample
Supervised✅ YesClassification, Regression
Unsupervised❌ NoClustering, PCA
Self-Supervised❌ PseudoBERT, SimCLR, GPT

🧪 Use Case: SimCLR in Vision (PyTorch)

import torchvision.transforms as T
from PIL import Image

transform = T.Compose([
T.RandomResizedCrop(224),
T.RandomHorizontalFlip(),
T.ColorJitter(),
T.ToTensor()
])

img = Image.open("cat.jpg")
x1 = transform(img) # View 1
x2 = transform(img) # View 2

# Pass x1, x2 to encoder → project → NT-Xent loss

📝 Practice Questions

  1. Self-Supervised learning में labels कैसे generate होते हैं?
  2. Contrastive Learning और Masked Modeling में क्या अंतर है?
  3. SimCLR किस domain में काम करता है और कैसे?
  4. GPT और BERT में SSL का role क्या है?
  5. SSL के फायदे क्या हैं supervised learning के comparison में?

🔚 Summary

ConceptDetail
SSL DefinitionData से खुद labels generate करके learning
Famous TasksMasking, Contrastive, Autoencoding
Popular ModelsBERT, GPT, SimCLR, BYOL, MAE
AdvantageLabel-free pretraining, Generalization
Real UseNLP, Vision, Robotics, Video

Serving Deep Learning Models via API / Web App

model को train और save कर लिया है — अब बारी है उसे दुनिया के सामने पेश करने की 🎯
यानि model को API या Web App के ज़रिए serve करना।


🧩 दो मुख्य तरीकें:

तरीकाविवरणउदाहरण
✅ API-BasedModel को backend में serve करेंFlask / FastAPI
✅ Web AppModel के ऊपर UI बनाएंStreamlit / Gradio

🔶 1. ✅ Flask API से Model Serve करना (PyTorch Example)

🛠️ Step-by-step Code

📌 app.py:

from flask import Flask, request, jsonify
import torch
import torch.nn as nn

# Your trained model class
class MyNet(nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)

def forward(self, x):
x = torch.relu(self.fc1(x))
return torch.sigmoid(self.fc2(x))

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

# Create Flask app
app = Flask(__name__)

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

if __name__ == "__main__":
app.run(debug=True)

📲 Test via curl or Postman:

curl -X POST http://127.0.0.1:5000/predict \
-H "Content-Type: application/json" \
-d '{"input": [1.0, 0.0]}'

🔶 2. ✅ Streamlit Web App (Quick & Visual)

📌 app.py

import streamlit as st
import torch
import torch.nn as nn

# Load model
class MyNet(nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)

def forward(self, x):
x = torch.relu(self.fc1(x))
return torch.sigmoid(self.fc2(x))

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

# UI
st.title("XOR Prediction Model")
x1 = st.slider("x1", 0.0, 1.0, 0.0)
x2 = st.slider("x2", 0.0, 1.0, 0.0)

if st.button("Predict"):
input_tensor = torch.tensor([[x1, x2]])
with torch.no_grad():
output = model(input_tensor).item()
st.write("Prediction:", round(output))

🔼 Run the App:

streamlit run app.py

🔶 3. ✅ Gradio Web Interface

import gradio as gr
import torch
import torch.nn as nn

class MyNet(nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.fc1 = nn.Linear(2, 4)
self.fc2 = nn.Linear(4, 1)

def forward(self, x):
x = torch.relu(self.fc1(x))
return torch.sigmoid(self.fc2(x))

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

def predict(x1, x2):
input_tensor = torch.tensor([[x1, x2]])
with torch.no_grad():
output = model(input_tensor).item()
return round(output)

gr.Interface(fn=predict, inputs=["slider", "slider"], outputs="text").launch()

✅ Deployment Options:

PlatformToolSuitable For
Local MachineFlask / StreamlitTesting, demos
Heroku / RenderFlask + GunicornCloud API
Hugging FaceGradio SpacePublic demo
AWS/GCPDocker / APIProduction

📝 Practice Questions:

  1. Flask API बनाने के लिए कौन से steps follow होते हैं?
  2. Streamlit और Gradio में क्या अंतर है?
  3. Model को Web पर serve करने के 3 तरीके क्या हैं?
  4. TorchScript model को Flask में कैसे load करेंगे?
  5. curl से API call कैसे की जाती है?

🧠 Summary Table

MethodInterfaceSetup TimeUI
FlaskJSON APIMedium
StreamlitWeb UIVery Low
GradioWeb UIVery Low
FastAPIFast JSONMedium-High

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