Python实现softmax函数
Python实现softmax函数:PS:为了避免求exp(x)出现溢出的情况,一般需要减去最大值。# -*-coding: utf-8 -*-import tensorflow as tfimport numpy as npdef softmax(x, axis=1):# 计算每行的最大值row_max = x.max(axis=axis)...
·
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());
更多推荐
已为社区贡献2条内容
所有评论(0)