天天看点

极智AI | C++ 手写 softmax 激活函数

  ​

​欢迎关注我的公众号 [极智视界],获取我的更多笔记分享​

  大家好,我是极智视界,本文讲解一下 C++ 手写 softmax 激活函数。

  在多分类任务中,最后通常使用 softmax 函数作为网络输出层的激活函数,softmax 函数可以对输出值作归一化,把所有的输出值转换为概率,所有的概率值加起来等于 1。在做分类的时候,概率值高的那个类别即为预测类别。现在很多框架里的接口封得易用性太强了,如 pytorch 中只要一句话就能直接调用 softmax 去计算,这很容易导致我们对于功能函数内部实现缺乏了解。基于此出发,这里讲解一下 C++ 来实现 softmax 函数。

文章目录

  • ​​1 softmax 数学表达​​
  • ​​2 softmax C++ 实现​​

1 softmax 数学表达

  softmax 的数学公式如下:

极智AI | C++ 手写 softmax 激活函数

  如输入值为 x0 = 1.3, x1 = 5.1,x2 = 2.2,x3 = 0.7,x4 = 1.1,根据以上计算方式可以计算出经过 softmax 后的值为 x0’ = 0.02,x1’ = 0.90,x2’ = 0.05,x3’ = 0.01,x4’ = 0.02。如下:

极智AI | C++ 手写 softmax 激活函数

  softmax 的示意图如下:

极智AI | C++ 手写 softmax 激活函数
## 安装依赖
sudo apt-get install autoconf automake libtool curl make g++ unzip libffi-dev -
## clone pro
git clone --recursive https://gitee.com/jeremyjj/protobuf.git

## 编译 C++ 接口
cd protobuf
./autogen.sh 
./configure
sudo make -j32
sudo make install

## 刷新共享库
sudo ldconfig

## 验证一下
protoc --version

## 编译 python 接口
cd python 

python setup.py build 
python setup.py test 
python setup.py install

## 验证一下
$ python
>>> import      

2 softmax C++ 实现

  来看 softmax 的 cpp 实现:

// softmax cpp 实现
vector<float> softmax(vector<float> input)
{
  float total = 0.;
  for(auto x : input)
  {
    total += exp(x);
  }
  vector<float> result;
  for(auto x : input)
  {
    result.push_back(exp(x) / total);
  }
  return result;
}      

  这边的输入、输出都用了 vector 数据结构,操作的数据的类型都默认使用了 float。

  好了,以上分享了 C++ 手写 softmax 激活函数的方法。希望我的分享能对你的学习有一点帮助。

极智AI | C++ 手写 softmax 激活函数

继续阅读