GCP为已有模型添加评估遇InvalidArgument:400指标格式错误求助
解决GCP AI Platform模型评估导入的"Invalid Metrics format"错误
问题根源
你遇到的InvalidArgument: 400 Invalid Metrics format错误,核心原因是直接将Python字典传入gapic.ModelEvaluation的metrics字段,而GCP API要求该字段必须是**google.protobuf.Struct类型**,而非普通字典。此外,指标Schema对字段结构有严格匹配要求,需按规范构造。
修复步骤
1. 导入Protobuf Struct模块
首先引入google.protobuf.struct_pb2模块,用于构造符合API要求的Struct对象:
from google.protobuf import struct_pb2
2. 将指标字典转换为Struct类型
把原始的指标字典转换为Protobuf Struct格式,替代直接传入普通字典:
# 定义指标字典 metrics_dict = { "classificationMetrics": { "auPrc": 0.88, "logLoss": 0.66 } } # 转换为Protobuf Struct对象 metrics_struct = struct_pb2.Struct() metrics_struct.update(metrics_dict)
3. 正确初始化ModelEvaluation对象
使用转换后的Struct对象作为metrics参数的值:
model_eval = gapic.ModelEvaluation( display_name="eval", metrics_schema_uri="gs://google-cloud-aiplatform/schema/modelevaluation/classification_metrics_1.0.0.yaml", metrics=metrics_struct )
4. 完整修复后的代码
from google.cloud.aiplatform import gapic from google.cloud import aiplatform from google.protobuf import struct_pb2 # 构造指标并转换为Protobuf Struct metrics_dict = { "classificationMetrics": { "auPrc": 0.88, "logLoss": 0.66 } } metrics_struct = struct_pb2.Struct() metrics_struct.update(metrics_dict) # 初始化模型评估对象 model_eval = gapic.ModelEvaluation( display_name="eval", metrics_schema_uri="gs://google-cloud-aiplatform/schema/modelevaluation/classification_metrics_1.0.0.yaml", metrics=metrics_struct ) # 设置API客户端 API_ENDPOINT = "us-central1-aiplatform.googleapis.com" client = gapic.ModelServiceClient(client_options={"api_endpoint": API_ENDPOINT}) # 导入模型评估 client.import_model_evaluation(parent=model.resource_name, model_evaluation=model_eval)
额外检查点
- 确认
model.resource_name是有效的模型资源路径(格式示例:projects/{PROJECT_ID}/locations/{LOCATION}/models/{MODEL_ID}) - 若仍报错,可核对分类指标Schema的完整要求,确保未遗漏必填字段(例如部分场景下可能需要
confusionMatrix或precisionRecallCurve等字段)
内容的提问来源于stack exchange,提问作者Sai Shashank
相关产品推荐
相关产品推荐

