Python实现softmax函数 :

PS:为了避免求exp(x)出现溢出的情况,一般需要减去最大值。

import numpy as np
def softmax(x):
    # 计算每行的最大值
    row_max = np.max(x)
    # 每行元素都需要减去对应的最大值,否则求exp(x)会溢出,导致inf情况
    x = x - row_max
    # 计算e的指数次幂
    x_exp = np.exp(x)
    x_sum = np.sum(x_exp)
    s = x_exp / x_sum
    return s

C++实现Softmax函数

template<typename _Tp>
int softmax(const _Tp* src, _Tp* dst, int length)
{
//    double max = 0.0;
//    double sum = 0.0;
//
//    for (int i = 0; i<k; i++) if (max < x[i]) max = x[i];
//    for (int i = 0; i<k; i++) {
//        x[i] = exp(x[i] - max);
//        sum += x[i];
//    }
//    for (int i = 0; i<k; i++) x[i] /= sum;
    //为了避免溢出,需要减去最大值
    const _Tp max_value = *std::max_element(src, src + length);
    _Tp denominator{ 0 };

    for (int i = 0; i < length; ++i) {
        dst[i] = std::exp(src[i] - max_value);
        denominator += dst[i];
    }

    for (int i = 0; i < length; ++i) {
        dst[i] /= denominator;
    }
    return 0;
}
std::vector<float> output_vector;
std::vector<float> preds;
softmax(output_vector.data(), preds.data(),output_vector.size());

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐