From 5a5f44eed70dbbdbd82584712c2ba50ef28581cc Mon Sep 17 00:00:00 2001 From: Changming Sun Date: Mon, 8 Jun 2020 09:33:50 -0700 Subject: [PATCH] Add softmax to the mnist example (#4149) --- samples/c_cxx/MNIST/MNIST.cpp | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/samples/c_cxx/MNIST/MNIST.cpp b/samples/c_cxx/MNIST/MNIST.cpp index a564a31396..08e69ce51e 100644 --- a/samples/c_cxx/MNIST/MNIST.cpp +++ b/samples/c_cxx/MNIST/MNIST.cpp @@ -5,11 +5,25 @@ #include #include #include +#include #pragma comment(lib, "user32.lib") #pragma comment(lib, "gdi32.lib") #pragma comment(lib, "onnxruntime.lib") +template +static void softmax(T& input) { + float rowmax = *std::max_element(input.begin(), input.end()); + std::vector y(input.size()); + float sum = 0.0f; + for (size_t i = 0; i != input.size(); ++i) { + sum += y[i] = std::exp(input[i] - rowmax); + } + for (size_t i = 0; i != input.size(); ++i) { + input[i] = y[i] / sum; + } +} + // This is the structure to interface with the MNIST model // After instantiation, set the input_image_ data to be the 28x28 pixel image of the number to recognize // Then call Run() to fill in the results_ data with the probabilities of each @@ -26,7 +40,7 @@ struct MNIST { const char* output_names[] = {"Plus214_Output_0"}; session_.Run(Ort::RunOptions{nullptr}, input_names, &input_tensor_, 1, output_names, &output_tensor_, 1); - + softmax(results_); result_ = std::distance(results_.begin(), std::max_element(results_.begin(), results_.end())); return result_; }