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)