Skip to content

Instantly share code, notes, and snippets.

@jamesandersen
Created August 28, 2017 22:17
Show Gist options
  • Save jamesandersen/787469608e404accbac3e82d7a8cac37 to your computer and use it in GitHub Desktop.
Save jamesandersen/787469608e404accbac3e82d7a8cac37 to your computer and use it in GitHub Desktop.
"""AWS Lambda Handler for making loan grade predictions"""
import os
import boto3
import botocore
import json
import numpy as np
from keras.models import load_model
from keras import backend as K
# Read environment variables indicating where our model lives
BUCKET_NAME = os.environ["bucket"]
MODEL_KEY = os.environ["modelkey"]
s3 = boto3.resource('s3')
loan_grade_model = None
# One-time per lambda instance, load the model from S3
try:
s3.Bucket(BUCKET_NAME).download_file(MODEL_KEY, '/tmp/model.h5')
print("Model downloaded from s3://{}/{}".format(BUCKET_NAME, MODEL_KEY))
loan_grade_model = load_model('/tmp/model.h5')
print("Model loaded from s3://{}/{}".format(BUCKET_NAME, MODEL_KEY))
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
print("The {}/{} does not exist.".format(BUCKET_NAME, MODEL_KEY))
else:
raise
def sample_predict(event, context):
# Read incoming data used to make prediction
body = json.loads(event['body'])
x = np.matrix([list(each.values()) for each in body])
# Make predictions
pred = loan_grade_model.predict(x)
max_indices = np.argmax(pred, axis=1)
# Generate response
grades = ["ABCDEFG"[x] for x in max_indices]
response = {}
response['statusCode'] = 200
response['headers'] = { "X-tensorflow-prediction": "True" }
response['body'] = json.dumps(grades)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment