ML Zoomcamp 2023 – Serverless – Part 4

Preparing the Code for Lambda

In the last parts we used Jupyter notebooks. Now we need Python scripts for the next steps, so we need to convert our existing code from Jupyter notebook to normal Python scripts. The tool we want to use is called nbconvert. Just use this command:

jupyter nbconvert –to script ‘my-notebook.ipynb’

We need to clean the code a bit. The resulting “lambda_function.py” script should look like:

#!/usr/bin/env python
# coding: utf-8

import tflite_runtime.interpreter as tflite
from keras_image_helper import create_preprocessor

preprocessor = create_preprocessor('xception', target_size=(299, 299))

interpreter = tflite.Interpreter(model_path='clothing-model.tflite')
interpreter.allocate_tensors()

input_index = interpreter.get_input_details()[0]['index']
output_index = interpreter.get_output_details()[0]['index']

url = 'http://bit.ly/mlbookcamp-pants'

classes = [
    'dress',
    'hat',
    'longsleeve',
    'outwear',
    'pants',
    'shirt',
    'shoes',
    'shorts',
    'skirt',
    't-shirt'
]

def predict(url):
    X = preprocessor.from_url(url)

    interpreter.set_tensor(input_index, X)
    interpreter.invoke()
    preds = interpreter.get_tensor(output_index)

    # What happens here is we take an Numpy array and 
    # it will be converted to usual python list with usual python floats.
    float_predictions = preds[0].tolist()

    return dict(zip(classes, float_predictions))

def lambda_handler(event, context):
    url = event['url']
    result = predict(url)
    return result

Testing

For testing we can use iPython – just type ipython and hit return. This will give you access to an iPython console, where you can do some Python commands. To test the code you need the following three commands:

  • import lambda_function
  • event = {'url': 'http://bit.ly/mlbookcamp-pants'}
  • lambda_function.lambda_handler(event, None)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.