溫馨提示×

如何在C++中實現Softmax函數

c++
小樊
117
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女