将值绑定到模型的输入和输出后,即可评估模型的输入并获取其预测。
若要运行模型,请在 LearningModelSession 上调用任何 Evaluate* 方法。 可以使用 LearningModelEvaluationResult 查看输出功能。
示例:
在以下示例中,我们对会话进行评估,并传入绑定和唯一相关 ID。 然后,我们将输出分析为概率列表,将其与模型可以识别的不同内容的标签列表匹配,并将结果写入控制台:
// How many times an evaluation has been run
private int runCount = 0;
private void EvaluateModel(
LearningModelSession session,
LearningModelBinding binding,
string outputName,
List<string> labels)
{
// Process the frame with the model
var results =
await session.EvaluateAsync(binding, $"Run {++runCount}");
// Retrieve the results of evaluation
var resultTensor = results.Outputs[outputName] as TensorFloat;
var resultVector = resultTensor.GetAsVectorView();
// Find the top 3 probabilities
List<(int index, float probability)> indexedResults = new List<(int, float)>();
for (int i = 0; i < resultVector.Count; i++)
{
indexedResults.Add((index: i, probability: resultVector.ElementAt(i)));
}
// Sort the results in order of highest probability
indexedResults.Sort((a, b) =>
{
if (a.probability < b.probability)
{
return 1;
}
else if (a.probability > b.probability)
{
return -1;
}
else
{
return 0;
}
});
// Display the results
for (int i = 0; i < 3; i++)
{
Debug.WriteLine(
$"\"{labels[indexedResults[i].index]}\" with confidence of {indexedResults[i].probability}");
}
}
删除设备
如果设备不可用,或者想要使用其他设备,则必须关闭会话并创建新会话。
在某些情况下,可能需要卸载和重新加载图形设备,如 DirectX 文档中所述。
使用 Windows ML 时,需要检测此情况并关闭会话。 若要从设备删除或重新初始化中恢复,你将创建一个新会话,这会触发设备选择逻辑再次运行。
最常见的情况是 LearningModelSession.Evaluate 期间出现此错误。 在设备移除或重置的情况下,LearningModelEvaluationResult.ErrorStatus 将显示 DXGI_ERROR_DEVICE_REMOVED 或 DXGI_ERROR_DEVICE_RESET。
另请参阅
- 上一篇: 绑定模型
注释
使用以下资源获取有关 Windows ML 的帮助:
- 若要询问或回答有关 Windows ML 的技术问题,请使用 Stack Overflow上的 windows-machine-learning 标记。
- 若要报告 bug,请在 gitHub 提交问题。