Bird
Raised Fist0
TensorFlowml~8 mins

Loading and inference in TensorFlow - Model Metrics & Evaluation

Choose your learning style10 modes available
Metrics & Evaluation - Loading and inference
Which metric matters for Loading and inference and WHY

When we load a saved model and use it to make predictions (inference), the key metric is accuracy or the metric used during training. This tells us if the model still works well after loading.

We also care about inference speed because in real life, predictions should be fast enough to be useful.

So, the main metrics are prediction correctness (like accuracy, precision, recall) and inference time.

Confusion matrix example after loading a model
    Confusion Matrix:

          Predicted
          Pos   Neg
    Actual
    Pos   90    10
    Neg   15    85

    Total samples = 90 + 10 + 15 + 85 = 200

    Precision = TP / (TP + FP) = 90 / (90 + 15) = 0.857
    Recall = TP / (TP + FN) = 90 / (90 + 10) = 0.9
    F1 Score = 2 * (0.857 * 0.9) / (0.857 + 0.9) ≈ 0.878
    Accuracy = (TP + TN) / Total = (90 + 85) / 200 = 0.875
    

This shows the model loaded correctly and performs well on test data.

Precision vs Recall tradeoff in inference

When using a loaded model, sometimes you want to adjust the decision threshold to balance precision and recall.

For example, in a spam filter:

  • High precision means fewer good emails marked as spam (false alarms).
  • High recall means catching most spam emails.

Depending on your goal, you might accept slower inference to get better precision or recall.

Good vs Bad metric values after loading a model

Good: Accuracy close to training accuracy, e.g., 85%+ accuracy, balanced precision and recall.

Bad: Accuracy drops significantly after loading, e.g., below 60%, or very low recall or precision.

Also, inference time should be reasonable (e.g., milliseconds per prediction). Very slow inference is bad for real-time use.

Common pitfalls in loading and inference metrics
  • Data mismatch: Using different data preprocessing during inference than training causes bad metrics.
  • Model version mismatch: Loading wrong or corrupted model files leads to poor performance.
  • Ignoring inference speed: A model might be accurate but too slow for practical use.
  • Overfitting signs: Very high training accuracy but low inference accuracy means overfitting.
Self-check question

Your loaded model has 98% accuracy but only 12% recall on fraud detection. Is it good for production? Why or why not?

Answer: No, it is not good. Although accuracy is high, recall is very low, meaning the model misses most fraud cases. In fraud detection, missing fraud (low recall) is very bad, so this model is not reliable.

Key Result
After loading, check if accuracy and recall remain high and inference speed is fast enough for your use case.

Practice

(1/5)
1. What is the main purpose of tf.keras.models.load_model() in TensorFlow?
easy
A. To visualize the model architecture
B. To load a previously saved model for inference or further training
C. To compile a model with loss and optimizer
D. To create a new model architecture from scratch

Solution

  1. Step 1: Understand the function purpose

    tf.keras.models.load_model() is used to load a model that was saved earlier, including its architecture, weights, and optimizer state.
  2. Step 2: Differentiate from other functions

    Creating a new model or compiling it are separate steps. Loading is specifically for retrieving a saved model.
  3. Final Answer:

    To load a previously saved model for inference or further training -> Option B
  4. Quick Check:

    Load saved model = load_model() [OK]
Hint: Load saved models with load_model() function [OK]
Common Mistakes:
  • Confusing load_model() with model creation
  • Thinking load_model() compiles the model
  • Assuming load_model() only loads weights
2. Which of the following is the correct way to get predictions from a loaded TensorFlow model named model on input data new_data?
easy
A. predictions = model.predict(new_data)
B. predictions = model.fit(new_data)
C. predictions = model.evaluate(new_data)
D. predictions = model.compile(new_data)

Solution

  1. Step 1: Identify the correct method for inference

    To get predictions from a model, the method predict() is used.
  2. Step 2: Understand other methods

    fit() trains the model, evaluate() tests performance, and compile() sets up the model.
  3. Final Answer:

    predictions = model.predict(new_data) -> Option A
  4. Quick Check:

    Predict new data = model.predict() [OK]
Hint: Use model.predict() to get predictions [OK]
Common Mistakes:
  • Using fit() instead of predict() for inference
  • Calling evaluate() expecting predictions
  • Trying to compile() during prediction
3. Given the following code, what will be the shape of predictions?
import tensorflow as tf
import numpy as np
model = tf.keras.Sequential([
  tf.keras.layers.Dense(3, input_shape=(4,))
])
model.compile(optimizer='adam', loss='mse')
input_data = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
predictions = model.predict(input_data)
medium
A. (3, 4)
B. (4, 3)
C. (2, 3)
D. (2, 4)

Solution

  1. Step 1: Analyze input shape and batch size

    The input data has shape (2, 4) meaning 2 samples, each with 4 features.
  2. Step 2: Determine output shape from model layer

    The Dense layer outputs 3 units per sample, so output shape is (2, 3).
  3. Final Answer:

    (2, 3) -> Option C
  4. Quick Check:

    Input batch 2, output units 3 = (2, 3) [OK]
Hint: Output shape = (batch_size, units in last layer) [OK]
Common Mistakes:
  • Confusing input shape with output shape
  • Mixing batch size and feature dimensions
  • Assuming output shape matches input shape
4. You loaded a model with model = tf.keras.models.load_model('my_model') but get this error when calling model.predict(new_data): ValueError: Error when checking input: expected dense_input to have shape (4,) but got array with shape (3,). What is the likely cause?
medium
A. The input data shape does not match the model's expected input shape
B. The model was not compiled before prediction
C. The model file is corrupted
D. The predict() method was called without training the model

Solution

  1. Step 1: Understand the error message

    The error says the model expects input shape (4,), but received (3,), meaning input data shape is wrong.
  2. Step 2: Rule out other causes

    Model compilation is not required for prediction, corrupted files cause different errors, and training is not needed for predict().
  3. Final Answer:

    The input data shape does not match the model's expected input shape -> Option A
  4. Quick Check:

    Input shape mismatch = ValueError [OK]
Hint: Match input data shape to model input shape exactly [OK]
Common Mistakes:
  • Ignoring input shape mismatch
  • Thinking model must be compiled before predict
  • Assuming predict requires training first
5. You have a saved TensorFlow model that expects input shape (None, 5). You want to predict on a single sample with 5 features stored in a list sample = [1, 2, 3, 4, 5]. Which code snippet correctly prepares the input and gets the prediction?
hard
A. input_data = np.array(sample) prediction = model.predict(input_data)
B. input_data = np.array(sample).reshape(1, 1, 5) prediction = model.predict(input_data)
C. input_data = np.array(sample).reshape(5, 1) prediction = model.predict(input_data)
D. import numpy as np input_data = np.array([sample]) prediction = model.predict(input_data)

Solution

  1. Step 1: Understand model input shape

    The model expects input shape (None, 5), where None is batch size, so input must be 2D with shape (batch_size, 5).
  2. Step 2: Prepare input data correctly

    Wrapping the sample list in another list creates shape (1, 5), which matches expected input.
  3. Step 3: Check other options

    input_data = np.array(sample) prediction = model.predict(input_data) gives shape (5,), not 2D; input_data = np.array(sample).reshape(5, 1) prediction = model.predict(input_data) reshapes to (5,1) which is wrong; input_data = np.array(sample).reshape(1, 1, 5) prediction = model.predict(input_data) reshapes to (1,1,5) which is 3D and incorrect.
  4. Final Answer:

    import numpy as np input_data = np.array([sample]) prediction = model.predict(input_data) -> Option D
  5. Quick Check:

    Input shape (1,5) matches model input [OK]
Hint: Wrap single sample in list to add batch dimension [OK]
Common Mistakes:
  • Passing 1D array instead of 2D batch input
  • Incorrect reshaping causing wrong input dimensions
  • Adding extra unnecessary dimensions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard