如何在C++中实现Softmax函数

   2024-10-01 2110
核心提示:在C++中实现Softmax函数可以通过以下代码:#include iostream#include vector#include cmathstd::vectordouble softmax(std::vec

在C++中实现Softmax函数可以通过以下代码:

#include <iostream>#include <vector>#include <cmath>std::vector<double> softmax(std::vector<double> &input) {    std::vector<double> result;    double sum = 0.0;    // Compute the sum of the exponentials of the input values    for (int i = 0; i < input.size(); ++i) {        sum += exp(input[i]);    }    // Compute the softmax values    for (int i = 0; i < input.size(); ++i) {        result.push_back(exp(input[i]) / sum);    }    return result;}int main() {    std::vector<double> input = {1.0, 2.0, 3.0};    std::vector<double> output = softmax(input);    // Print the softmax values    for (int i = 0; i < output.size(); ++i) {        std::cout << "Softmax[" << i << "] = " << output[i] << std::endl;    }    return 0;}

在这段代码中,softmax函数接受一个double类型的向量作为输入,并返回一个包含Softmax值的向量。在主函数中,我们定义了一个输入向量{1.0, 2.0, 3.0},并调用softmax函数计算Softmax值。最后,我们打印出Softmax值。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号