评估模型输入

将值绑定到模型的输入和输出后,即可对该模型的输入进行评估并获得其预测结果。

若要运行模型,请在 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_REMOVEDDXGI_ERROR_DEVICE_RESET

另请参阅

注意

使用以下资源可获取有关 Windows ML 的帮助:

  • 若要提出或回答有关 Windows ML 的技术问题,请在 Stack Overflow 上使用 windows-machine-learning 标记。
  • 若要报告 bug,请在 GitHub 上提交问题。