我有一个部署到在线端点的二元分类模型。
我可以将数据传递到端点并让它返回预测的类别或预测的概率。
我希望它返回一个 ID 字段,该字段也传递到模型中,以便分数可以匹配回与其关联的记录。
下面是我的代码中调用端点的相关部分:
data = {
"Inputs": {
"data":
data1
},
"GlobalParameters": {
"method": "predict_proba"
}
}
body = str.encode(json.dumps(data))
url = 'http://MyDeployement.MyRegion.azurecontainer.io/score'
headers = {'Content-Type':'application/json'}
req = urllib.request.Request(url, body, headers)
response = urllib.request.urlopen(req)
result = response.read()
encoding = response.info().get_content_charset('utf-8')
JSON_object = json.loads(result.decode(encoding))
print(JSON_object)
谢谢。
我在下面添加了大部分当前评分脚本(作为 AutoML 的输出),因为现在看来是相关的:
import...
data_sample = PandasParameterType(pd.DataFrame({"age": pd.Series([0], dtype="int64"), "job": pd.Series(["example_value"], dtype="object"), "marital": pd.Series(["example_value"], dtype="object"), "education": pd.Series(["example_value"], dtype="object"), ...))
input_sample = StandardPythonParameterType({'data': data_sample})
method_sample = StandardPythonParameterType("predict")
sample_global_params = StandardPythonParameterType({"method": method_sample})
result_sample = NumpyParameterType(np.array(["example_value"]))
output_sample = StandardPythonParameterType({'Results':result_sample})
try:
log_server.enable_telemetry(INSTRUMENTATION_KEY)
log_server.set_verbosity('INFO')
logger = logging.getLogger('azureml.automl.core.scoring_script_v2')
except:
pass
def init():
global model
# This name is model.id of model that we want to deploy deserialize the model file back
# into a sklearn model
model_path = os.path.join(os.getenv('AZUREML_MODEL_DIR'), 'model.pkl')
path = os.path.normpath(model_path)
path_split = path.split(os.sep)
log_server.update_custom_dimensions({'model_name': path_split[-3], 'model_version': path_split[-2]})
try:
logger.info("Loading model from path.")
model = joblib.load(model_path)
logger.info("Loading successful.")
except Exception as e:
logging_utilities.log_traceback(e, logger)
raise
@input_schema('GlobalParameters', sample_global_params, convert_to_provided_type=False)
@input_schema('Inputs', input_sample)
@output_schema(output_sample)
def run(Inputs, GlobalParameters={"method": "predict"}):
data = Inputs['data']
if GlobalParameters.get("method", None) == "predict_proba":
result = model.predict_proba(data)
elif GlobalParameters.get("method", None) == "predict":
result = model.predict(data)
else:
raise Exception(f"Invalid predict method argument received. GlobalParameters: {GlobalParameters}")
if isinstance(result, pd.DataFrame):
result = result.values
return {'Results':result.tolist()}
由于 Azure AutoML 已更新并具有可以取消选择训练数据中的字段以在模型中考虑的功能,因此传递到已部署模型的数据将不再包含 ID 字段。 由于 Python 中保留了顺序,因此用于评分的数据应在评分前删除 ID 字段,然后应将评分数据连接回原始文件以获得 ID。
读取文件以评分到数据框中,删除 ID 列,适当保存或根据需要直接传递到端点。 然后读取原始文件和输出,将之前的ID和后者的分数连接到一个新的数据框中,以达到与ID相关的分数的目标。然后您可以根据情况编写或使用它。