调用SageMaker Endpoint报错:无法将字符串转换为浮点数
SageMaker Autopilot XGBoost模型推理错误修复及字段顺序查询
一、解决"could not convert string to float"错误
Autopilot训练阶段会自动对布尔、分类类特征做编码转换:
- 布尔值
False/True会被转为0/1 - 字符串分类特征会被映射为专属数值编码
推理时必须使用编码后的数值,不能直接传递原始字符串:
- 将
testCSV中的False替换为0 - 对于
fff77916386145、web这类字符串特征,需要替换为训练时Autopilot生成的对应数值编码。若不确定编码规则,可查看Autopilot训练输出的预处理脚本,或从训练数据中统计该特征的编码映射关系。
修改后的代码示例:
import { SageMakerRuntimeClient, InvokeEndpointCommand } from "@aws-sdk/client-sagemaker-runtime"; const sagemakerRuntime = new SageMakerRuntimeClient({ region: "us-east-2" }); export const handler = async (event) => { // 替换布尔值为编码后的数值,分类特征使用训练时对应的编码 const testCSV = "0,105,0,-1,0,2"; // 示例编码,需替换为项目实际对应值 const params = { EndpointName: process.env.ENDPOINT_NAME, Body: testCSV, ContentType: 'text/csv', }; try { const command = new InvokeEndpointCommand(params); const response = await sagemakerRuntime.send(command); const result = new TextDecoder("utf-8").decode(response.Body); return { statusCode: 200, headers: { 'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*' }, body: result }; } catch (error) { console.error(error); throw new Error('Failed to call SageMaker endpoint'); } };
二、获取推理CSV的正确字段顺序
有三种可靠途径:
- 匹配训练数据列顺序:推理字段顺序和训练数据的列顺序完全一致(注意:若训练数据包含标签列,推理时需要排除该列)
- SageMaker Studio查看:进入对应AutoML实验的
Data exploration页面,查看原始数据的列顺序;或在Model tuning页面的最优模型详情中,查看预处理阶段的特征列表 - S3训练输出文件:在训练作业对应的S3存储路径下,找到
preprocessing目录中的特征元数据文件,里面记录了特征的顺序和编码规则
内容的提问来源于stack exchange,提问作者white_and_red
相关产品推荐
相关产品推荐

