Python實作softmax函數 :
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());