Bird
Raised Fist0
TensorFlowml~20 mins

TensorFlow Serving setup - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - TensorFlow Serving setup
Problem:You have trained a TensorFlow model and want to deploy it for real-time predictions using TensorFlow Serving.
Current Metrics:N/A - Deployment setup, no model metrics yet.
Issue:The model is not yet served, so no predictions can be made by external clients.
Your Task
Set up TensorFlow Serving to serve a saved TensorFlow model and verify it returns correct predictions.
Use TensorFlow Serving Docker container for deployment.
Serve a simple pre-trained model saved in SavedModel format.
Test the serving endpoint with a sample input to get predictions.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
TensorFlow
import tensorflow as tf
import numpy as np
import requests
import json
import time

# Step 1: Create and save a simple model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(10, activation='relu', input_shape=(4,)),
    tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Dummy training data
X_train = np.random.random((100, 4))
y_train = np.random.randint(0, 3, 100)
model.fit(X_train, y_train, epochs=3)

# Save the model in SavedModel format
model.save('saved_model/1')  # Version number folder

# Step 2: Run TensorFlow Serving Docker container (run this in terminal, not Python)
# docker run -p 8501:8501 --name=tf_serving_example \
#   -v "$(pwd)/saved_model:/models/my_model" \
#   -e MODEL_NAME=my_model -t tensorflow/serving

# Wait a few seconds for the server to start
print('Waiting for TensorFlow Serving to start...')
time.sleep(10)

# Step 3: Prepare input data for prediction
input_data = {
    "signature_name": "serving_default",
    "instances": [
        [0.1, 0.2, 0.3, 0.4]
    ]
}

# Step 4: Send prediction request
url = 'http://localhost:8501/v1/models/my_model:predict'
headers = {"content-type": "application/json"}
response = requests.post(url, data=json.dumps(input_data), headers=headers)

# Step 5: Print prediction result
print('Prediction response:', response.json())
Created a simple TensorFlow model and saved it in SavedModel format under version folder '1'.
Provided Docker command to run TensorFlow Serving container with the saved model mounted.
Added Python code to send a REST API request to the TensorFlow Serving endpoint for prediction.
Included waiting time to ensure the server is ready before sending requests.
Results Interpretation

Before: No model serving, no external predictions possible.

After: TensorFlow Serving runs the model and returns predictions via REST API.

This experiment shows how to deploy a TensorFlow model for real-time serving using TensorFlow Serving and Docker, enabling external applications to get predictions easily.
Bonus Experiment
Try deploying the model using gRPC protocol instead of REST and test predictions.
💡 Hint
Use TensorFlow Serving gRPC endpoint at port 8500 and a gRPC client library to send prediction requests.

Practice

(1/5)
1. What is the main purpose of TensorFlow Serving in a machine learning workflow?
easy
A. To visualize training data and model metrics
B. To train new machine learning models from scratch
C. To preprocess data before training
D. To deploy trained models for real-time predictions

Solution

  1. Step 1: Understand TensorFlow Serving's role

    TensorFlow Serving is designed to make trained models available for real-time use without retraining.
  2. Step 2: Differentiate from other tasks

    Training, visualization, and preprocessing are separate steps not handled by TensorFlow Serving.
  3. Final Answer:

    To deploy trained models for real-time predictions -> Option D
  4. Quick Check:

    Serving = deploy models [OK]
Hint: Serving means making models ready for prediction [OK]
Common Mistakes:
  • Confusing serving with training
  • Thinking it handles data preprocessing
  • Assuming it visualizes metrics
2. Which command correctly starts TensorFlow Serving to serve a model saved in the directory /models/my_model/1/ with model name my_model?
easy
A. tensorflow_model_server --model_name my_model --model_base_path /models/my_model/1/
B. tensorflow_model_server --model_name=my_model --model_path=/models/my_model/1/
C. tensorflow_model_server --model_name=my_model --model_base_path=/models/my_model/1/
D. tensorflow_serve --model_name=my_model --model_base_path=/models/my_model/1/

Solution

  1. Step 1: Identify correct flags for TensorFlow Serving

    The correct flags are --model_name and --model_base_path with equal signs.
  2. Step 2: Check command correctness

    tensorflow_model_server --model_name=my_model --model_base_path=/models/my_model/1/ uses correct command and flags with equal signs; others have syntax errors or wrong command name.
  3. Final Answer:

    tensorflow_model_server --model_name=my_model --model_base_path=/models/my_model/1/ -> Option C
  4. Quick Check:

    Correct flags and command = tensorflow_model_server --model_name=my_model --model_base_path=/models/my_model/1/ [OK]
Hint: Use equal signs with flags and correct command name [OK]
Common Mistakes:
  • Using spaces instead of equal signs in flags
  • Wrong command name like tensorflow_serve
  • Using incorrect flag names like --model_path
3. Given the following Python code snippet to send data to a TensorFlow Serving REST API, what will be the printed output if the server returns a prediction of 0.85?
import requests
import json

url = 'http://localhost:8501/v1/models/my_model:predict'
data = {"instances": [[1.0, 2.0, 3.0]]}
response = requests.post(url, json=data)
prediction = response.json()['predictions'][0]
print(prediction)
medium
A. 0.85
B. [0.85]
C. {'predictions': [0.85]}
D. Error: KeyError

Solution

  1. Step 1: Understand the response JSON structure

    The server returns a JSON with key 'predictions' holding a list of prediction values, e.g., {'predictions': [0.85]}.
  2. Step 2: Extract the first prediction value

    Accessing response.json()['predictions'][0] extracts the float 0.85.
  3. Final Answer:

    0.85 -> Option A
  4. Quick Check:

    Extract first prediction value = 0.85 [OK]
Hint: Access ['predictions'][0] to get single prediction value [OK]
Common Mistakes:
  • Printing the whole JSON instead of the value
  • Forgetting to index the first prediction
  • Assuming prediction is a list, not a float
4. You tried to start TensorFlow Serving with the command tensorflow_model_server --model_name=my_model --model_base_path=/models/my_model/1/ but got an error saying the model path does not exist. What is the most likely cause?
medium
A. The command should use --model_path instead of --model_base_path
B. The model directory path is incorrect or missing the version subfolder
C. TensorFlow Serving requires the model to be in a .pb file, not a folder
D. The model name must be the full path, not just a name

Solution

  1. Step 1: Check model directory structure requirements

    TensorFlow Serving expects model_base_path to point to a directory containing version subfolders like '1', '2', etc.
  2. Step 2: Identify common path mistakes

    If the path misses the version folder or is incorrect, the server cannot find the model and throws an error.
  3. Final Answer:

    The model directory path is incorrect or missing the version subfolder -> Option B
  4. Quick Check:

    Model path must include version folder [OK]
Hint: Model path must include version folder like /1/ [OK]
Common Mistakes:
  • Using --model_path instead of --model_base_path
  • Pointing to a file instead of a directory
  • Confusing model name with path
5. You want to update your TensorFlow model served by TensorFlow Serving without downtime. Which approach allows you to serve the new model version while keeping the old version available for requests?
hard
A. Add the new model version in a new subfolder and update the model config file
B. Stop TensorFlow Serving, replace the old model folder, then restart the server
C. Serve the new model on a different port and manually switch clients
D. Retrain the model inside TensorFlow Serving using the new data

Solution

  1. Step 1: Understand TensorFlow Serving versioning

    TensorFlow Serving supports multiple model versions by placing each version in its own numbered subfolder.
  2. Step 2: Use model config file to add new version

    Adding the new version folder and updating the config allows serving both versions simultaneously without downtime.
  3. Final Answer:

    Add the new model version in a new subfolder and update the model config file -> Option A
  4. Quick Check:

    Versioned folders + config update = zero downtime [OK]
Hint: Use versioned folders and config to update without downtime [OK]
Common Mistakes:
  • Replacing model folder while server runs
  • Restarting server causes downtime
  • Trying to retrain model inside serving
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