MetaTrader5
Recognizing Handwritten Digits with ONNX in MetaTrader 5: A Step-by-Step Guide
An Expert Advisor for Handwritten Digit Recognition If you're diving into the world of algorithmic trading, you might want to explore how to utilize models for tasks like recognizing handwritten digits. One popular dataset for this is the MNIST database, which includes 60,000 training images and 10,000 testing images. These images have been generated by remixing the original NIST set of 20x20 pixel black-and-white samples, sourced from the US Census Bureau and enriched with samples from American high school students. Each image has been normalized to a size of 28x28 pixels and anti-aliased to introduce various grayscale levels. For trading enthusiasts looking to implement this, the trained model mnist.onnx is available for download on GitHub from the Model Zoo (opset 8). You can easily download and test other models, but be cautious to avoid those using opset 1, as they aren't supported by the latest ONNX runtime. Interestingly, the output vector isn't processed with the Softmax activation function, which is typically standard in classification models. But don’t worry, we can implement that ourselves! int PredictNumber(void) { static matrixf image(28, 28); static vectorf result(10); PrepareMatrix(image); if(!OnnxRun(ExtModel, ONNX_DEFAULT, image, result)) { Print("OnnxRun error ", GetLastError()); return(-1); } result.Activation(result, AF_SOFTMAX); int predict = int(result.ArgMax()); if(result[predict] < 0.8) Print(result); Print("value ", predict, " predicted with probability ", result[predict]); return(predict);} To recognize a drawn digit, simply draw it within a special grid using your mouse while holding down the left button. Once you’ve drawn your digit, hit the CLASSIFY button to see the result! If the recognized digit's probability is below 0.8, the resulting vector of probabilities for each class will be logged. For instance, if you classify an empty input field, you might see something like this: [0.095331445, 0.10048489, 0.10673151, 0.10274081, 0.087865397, 0.11471312, 0.094342403, 0.094900772, 0.10847695, 0.09441267] value 5 predicted with probability 0.11471312493085861 Interestingly, recognition accuracy tends to dip notably for the number nine (9), and left-slanted digits are recognized more accurately. So, keep that in mind as you experiment with your own digit recognition!
2023.11.23