python-3.x - 如何通过 AWS Lambda 函数推断托管在 AWS SageMaker 上的 keras 模型?
问题描述
我有一个预先训练的keras
模型,我AWS
使用AWS SageMaker
. 我有一个endpoint
,我可以成功predictions
使用Amazon SageMaker Notebook instance
.
我在那里所做的是我提供.PNG image
以下服务,并且模型给了我正确的预测。
file= s3.Bucket(bucketname).download_file(filename_1, 'normal.png')
file_name_1='normal.png'
import sagemaker
from sagemaker.tensorflow.model import TensorFlowModel
endpoint = 'tensorflow-inference-0000-11-22-33-44-55-666' #endpoint
predictor=sagemaker.tensorflow.model.TensorFlowPredictor(endpoint, sagemaker_session)
data = np.array([resize(imread(file_name), (137, 310, 3))])
predictor.predict(data)
现在我想使用mobile application
. 为此,我必须Lambda function
在 python 中编写一个并附加一个API gateway
。我Lambda function
的是以下。
import os
import sys
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CWD, "lib"))
import json
import base64
import boto3
import numpy as np
from scipy import signal
from scipy.signal import butter, lfilter
from scipy.io import wavfile
import scipy.signal as sps
import io
from io import BytesIO
import matplotlib.pylab as plt
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from datetime import datetime
from skimage.io import imread
from skimage.transform import resize
from PIL import Image
ENDPOINT_NAME = 'tensorflow-inference-0000-11-22-33-44-55-666'
runtime= boto3.client('runtime.sagemaker')
def lambda_handler(event, context):
s3 = boto3.client("s3")
# retrieving data from event.
get_file_content_from_postman = event["content"]
# decoding data.
decoded_file_name = base64.b64decode(get_file_content_from_postman)
image = Image.open(io.BytesIO(decoded_file_name))
data = np.array([resize(imread(image), (137, 310, 3))])
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME, ContentType='text/csv', Body=data)
result = json.loads(response['Body'].read().decode())
return result
最后第三行是给我错误'PngImageFile' object has no attribute 'read'
。知道我在这里缺少什么吗?
解决方案
如果io.BytesIO(decoded_file_name)
正确表示您的图像数据(尽管名称decoded_file_name
表明它只是文件名,而不是实际图像数据),那么您不需要使用 PIL。直接使用即可:
data = np.array([resize(imread(io.BytesIO(decoded_file_name)), (137, 310, 3))])
推荐阅读
- html - 图像CSS上的重叠文本
- reactjs - react-360 没有创建项目
- php - htaccess 总是将 POST 请求重定向到 GET 请求。
- python - 我如何执行枚举?
- ubuntu - 在 ubuntu pycharm 中我找不到 anaconda 包
- sql - PostgreSQL - Distinct on 的随机顺序
- python - Pip install PyAudio 失败,错误代码为 1
- java - 将插入排序应用于对象数组
- android-studio - 如何在 Android Studio 中打开现有的 Flutter 项目
- reactjs - react-google-maps“'google'未定义”错误