设计模型后,就可以使用 Infer.NET 建模 API 将其表示为概率性程序。 在常用的文本编辑器中,打开 Program.cs,并将其所有内容替换为以下代码:
C#
namespacemyApp
{
using System;
using System.Linq;
using Microsoft.ML.Probabilistic;
using Microsoft.ML.Probabilistic.Distributions;
using Microsoft.ML.Probabilistic.Models;
classProgram
{
staticvoidMain(string[] args)
{
// The winner and loser in each of 6 samples gamesvar winnerData = new[] { 0, 0, 0, 1, 3, 4 };
var loserData = new[] { 1, 3, 4, 2, 1, 2 };
// Define the statistical model as a probabilistic programvar game = new Range(winnerData.Length);
var player = new Range(winnerData.Concat(loserData).Max() + 1);
var playerSkills = Variable.Array<double>(player);
playerSkills[player] = Variable.GaussianFromMeanAndVariance(6, 9).ForEach(player);
var winners = Variable.Array<int>(game);
var losers = Variable.Array<int>(game);
using (Variable.ForEach(game))
{
// The player performance is a noisy version of their skillvar winnerPerformance = Variable.GaussianFromMeanAndVariance(playerSkills[winners[game]], 1.0);
var loserPerformance = Variable.GaussianFromMeanAndVariance(playerSkills[losers[game]], 1.0);
// The winner performed better in this game
Variable.ConstrainTrue(winnerPerformance > loserPerformance);
}
// Attach the data to the model
winners.ObservedValue = winnerData;
losers.ObservedValue = loserData;
// Run inferencevar inferenceEngine = new InferenceEngine();
var inferredSkills = inferenceEngine.Infer<Gaussian[]>(playerSkills);
// The inferred skills are uncertain, which is captured in their variancevar orderedPlayerSkills = inferredSkills
.Select((s, i) => new { Player = i, Skill = s })
.OrderByDescending(ps => ps.Skill.GetMean());
foreach (var playerSkill in orderedPlayerSkills)
{
Console.WriteLine($"Player {playerSkill.Player} skill: {playerSkill.Skill}");
}
}
}
}
运行应用
在命令提示符中运行下面的命令:
.NET CLI
dotnetrun
结果
结果应如下所示:
控制台
Compiling model...done.
Iterating:
.........|.........|.........|.........|.........| 50
Player 0 skill: Gaussian(9.517, 3.926)
Player 3 skill: Gaussian(6.834, 3.892)
Player 4 skill: Gaussian(6.054, 4.731)
Player 1 skill: Gaussian(4.955, 3.503)
Player 2 skill: Gaussian(2.639, 4.288)