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