SageMaker TensorFlow:如何编写serving_input_fn()函数?
解决SageMaker中serving_input_fn()的实现问题
嘿,作为TensorFlow和SageMaker的新手,写serving_input_fn()确实容易卡壳,我结合你的三个数值特征列,给你一个能直接复用的实现,再一步步给你讲清楚逻辑:
首先先把你的特征列构造函数补全,再搭配对应的serving_input_fn():
import tensorflow as tf def construct_feature_columns(): amount_normalized = tf.feature_column.numeric_column(key='amount_normalized') x_month = tf.feature_column.numeric_column(key='x_month') y_month = tf.feature_column.numeric_column(key='y_month') return set([amount_normalized, x_month, y_month]) def serving_input_fn(): # 定义接收外部请求的占位符,shape=[None]支持单条/批量预测请求 feature_placeholders = { 'amount_normalized': tf.placeholder(tf.float32, shape=[None]), 'x_month': tf.placeholder(tf.float32, shape=[None]), 'y_month': tf.placeholder(tf.float32, shape=[None]) } # 这里直接用占位符作为模型输入的特征字典(如果无需额外预处理的话) # 如果需要在服务阶段做预处理(比如动态归一化),可以在这里添加逻辑 features = feature_placeholders # 返回ServingInputReceiver,告诉SageMaker如何解析请求并喂给模型 return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)
关键部分解释
- 占位符定义:每个特征对应一个
tf.placeholder,shape=[None]是为了兼容单条预测和批量预测两种场景,数据类型用tf.float32匹配你的数值特征列。 - 特征字典处理:因为你的
amount_normalized已经是预处理后的特征,所以直接把占位符作为特征字典返回即可。如果需要在服务时动态做预处理(比如用训练时的均值/方差做归一化),可以参考下面的示例:# 示例:服务阶段动态归一化amount特征(假设训练时的均值和方差已知) mean_amount = 120.5 # 替换成你训练时计算的均值 std_amount = 30.2 # 替换成你训练时计算的方差 normalized_amount = (feature_placeholders['amount_normalized'] - mean_amount) / std_amount features = { 'amount_normalized': normalized_amount, 'x_month': feature_placeholders['x_month'], 'y_month': feature_placeholders['y_month'] } - ServingInputReceiver的作用:这个对象是连接外部请求和模型的桥梁,它包含两个核心部分:
features:模型训练时使用的特征格式,也就是模型期望接收的输入。receiver_tensors:外部请求的原始数据会被映射到这些张量上,也就是我们定义的占位符。
常见避坑提示
- 一定要保证特征列的
key和serving_input_fn里占位符的key完全一致,否则模型会找不到对应特征报错。 - 如果用的是TensorFlow Estimator(比如
DNNClassifier),这个serving_input_fn可以直接传给estimator.export_savedmodel()方法导出模型,供SageMaker部署使用。 - 在SageMaker训练脚本里,导出模型的代码可以这么写:
estimator.export_savedmodel(export_dir_base='export', serving_input_receiver_fn=serving_input_fn)
内容的提问来源于stack exchange,提问作者pbh
相关产品推荐
相关产品推荐

