private static void PrintDigit(DigitInputData digit) { Console.WriteLine(); for (var i = 0; i < 28; i++) { for (var j = 0; j < 28; j++) { Console.Write(digit.PixelValues[i * 28 + j].ToString().PadLeft(4, ' ')); } Console.WriteLine(); } }
public static int PredictDigit2(DigitInputData digit) { PrintDigit(digit); var mlContext = new MLContext(); var trainedModel = mlContext.Model.Load(ModelPath, out var modelInputSchema); // Create prediction engine related to the loaded trained model var predEngine = mlContext.Model.CreatePredictionEngine <DigitInputData2, DigitOutputData>(trainedModel); var mapped = MapToAlternateInput(GetZero()); var prediction = predEngine.Predict(mapped); var predictedDigit = 0; var maxProbability = (float)0; for (var i = 0; i < prediction.Score.Length; i++) { if (!(prediction.Score[i] > maxProbability)) { continue; } maxProbability = prediction.Score[i]; predictedDigit = i; } Console.WriteLine($"Actual: {digit.Number} Predicted probability:"); Console.WriteLine($" zero: {prediction.Score[0]:0.####}"); Console.WriteLine($" one : {prediction.Score[1]:0.####}"); Console.WriteLine($" two: {prediction.Score[2]:0.####}"); Console.WriteLine($" three: {prediction.Score[3]:0.####}"); Console.WriteLine($" four: {prediction.Score[4]:0.####}"); Console.WriteLine($" five: {prediction.Score[5]:0.####}"); Console.WriteLine($" six: {prediction.Score[6]:0.####}"); Console.WriteLine($" seven: {prediction.Score[7]:0.####}"); Console.WriteLine($" eight: {prediction.Score[8]:0.####}"); Console.WriteLine($" nine: {prediction.Score[9]:0.####}"); Console.WriteLine($"Prediction: {predictedDigit}"); Console.WriteLine(); return(predictedDigit); }
public static DigitInputData2 MapToAlternateInput(DigitInputData data) { var array = new float[49]; for (var i = 0; i < 28; i++) { for (var j = 0; j < 28; j++) { if (data.PixelValues[i * 28 + j] > 0) { var iCoord = i / 4; var jCoord = j / 4; array[iCoord * 7 + jCoord]++; } } } return(new DigitInputData2 { PixelValues = array, Number = data.Number }); }