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