温馨提示×

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

c++
小樊
85
2024-08-18 06:57:37
栏目: 编程语言

在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值。

0