用C++实现softmax函数(面试经验)

背景

今天面试字节算法岗时被问到的问题,让我用C++实现一个softmax函数。softmax是逻辑回归在多分类问题上的推广。大概的公式如下:
i n p u t : { x 1 , x 2 , ⋯   , x n } s o f t m a x ( x t ) = e x t ∑ i = 1 n e x i input: \{x_1, x_2,\cdots, x_n\}\\ softmax(x_t)=\frac{e^{x_t}}{\sum_{i=1}^{n}e^{x_i}} input:{x1,x2,,xn}softmax(xt)=i=1nexiext
即判断该变量在总体变量中的占比。

第一次实现

实现

我们用vector来封装输入和输出,简单的按公式复现。

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

测试

test 1

  • 测试用例1: {1, 2, 3, 4, 5}
  • 测试输出1: {0.0116562, 0.0316849, 0.0861285, 0.234122, 0.636409}

经过简单测试是正常的。
在这里插入图片描述

test 2

但是这时面试官提出了一个问题,即如果有较大输入变量时会怎么样?

  • 测试用例2: {1, 2, 3, 4, 5, 1000}
  • 测试输出2: {0, 0, 0, 0, 0, nan}

由于 e 1000 e^{1000} e1000已经溢出了双精度浮点(double)所能表示的范围,所以变成了NaN(not a number)。
在这里插入图片描述

第二次实现(改进)

改进原理

我们注意观察softmax的公式:
i n p u t : { x 1 , x 2 , ⋯   , x n } s o f t m a x ( x t ) = e x t ∑ i = 1 n e x i input: \{x_1, x_2,\cdots, x_n\}\\ softmax(x_t)=\frac{e^{x_t}}{\sum_{i=1}^{n}e^{x_i}} input:{x1,x2,,xn}softmax(xt)=i=1nexiext
如果我们给上下同时乘以一个很小的数,最后答案的值是不变的。
那我们可以给每一个输入 x i x_i xi都减去一个值 a a a,防止爆精度。
大致表示如下:
e x t ∑ i = 1 n e x i = e x t ⋅ e − a e − a ⋅ ∑ i = 1 n e x i = e x t ⋅ e − a ∑ i = 1 n e x i ⋅ e − a = e x t − a ∑ i = 1 n e x i − a \frac{e^{x_t}}{\sum_{i=1}^{n}e^{x_i}}= \frac{e^{x_t}\cdot e^{-a}}{e^{-a}\cdot \sum_{i=1}^{n}e^{x_i}}= \frac{e^{x_t}\cdot e^{-a}}{ \sum_{i=1}^{n}e^{x_i}\cdot e^{-a}}= \frac{e^{x_t-a}}{ \sum_{i=1}^{n}e^{x_i-a}} i=1nexiext=eai=1nexiextea=i=1nexieaextea=i=1nexiaexta
那我们如何取这个 a a a的值呢?直接取输入中最大的那个即 m a x ( x i ) max(x_i) max(xi)就好啦,这样所有的 e x i − a e^{x_i-a} exia的值都不会超过 e 0 = 1 e^0=1 e0=1,更不可能爆精度了。

实现

vector<double> softmax(vector<double> input)
{
	double total=0;
	double MAX=input[0];
	for(auto x:input)
	{
		MAX=max(x,MAX);
	}
	for(auto x:input)
	{
		total+=exp(x-MAX);
	}
	vector<double> result;
	for(auto x:input)
	{
		result.push_back(exp(x-MAX)/total);
	}
	return result;
}

测试

test 1

  • 测试用例1: {1, 2, 3, 4, 5, 1000}
  • 测试输出1: {0, 0, 0, 0, 0, 1}
    在这里插入图片描述

test 2

  • 测试用例1: {0, 19260817, 19260817}
  • 测试输出1: {0, 0.5, 0.5}

在这里插入图片描述

我们发现结果正常了。

完整代码

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

vector<double> softmax(vector<double> input)
{
	double total=0;
	double MAX=input[0];
	for(auto x:input)
	{
		MAX=max(x,MAX);
	}
	for(auto x:input)
	{
		total+=exp(x-MAX);
	}
	vector<double> result;
	for(auto x:input)
	{
		result.push_back(exp(x-MAX)/total);
	}
	return result;
}

int main(int argc, char *argv[])
{
	int n;
	cin>>n;
	vector<double> input;
	while(n--)
	{
		double x;
		cin>>x;
		input.push_back(x);
	}
	for(auto y:softmax(input))
	{
		cout<<y<<' ';
	}
}
  • 13
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
C语言中的softmax函数用于多分类问题中的逻辑回归。它将一组输入值通过一个指数函数和归一化操作转换为一个概率分布。在给定的输入向量中,softmax函数计算每个元素的指数值,然后对所有指数值求和,最后将每个指数值除以总和,得到每个元素的概率值。以下是C语言中的softmax函数的示例实现: ```c #include <stdio.h> #include <math.h> void softmax(double input[], int n) { double max = input > max) { max = input[i]; } } // 计算指数值和 for(int i = 0; i < n; i++) { input[i = exp(input[i - max); sum += input[i]; } // 归一化处理 for(int i = 0; i < n; i++) { input[i /= sum; } } int main() { int n; printf("请输入输入向量的维度:"); scanf("%d", &n); double input[n]; printf("请输入输入向量的元素值:"); for(int i = 0; i < n; i++) { scanf("%lf", &input[i]); } softmax(input, n); printf("经过softmax函数处理后的概率分布:"); for(int i = 0; i < n; i++) { printf("%lf ", input[i]); } return 0; } ``` 这段代码中,首先找到输入向量中的最大值,然后计算每个元素的指数值,并累加求和。最后,将每个元素除以总和,得到归一化的概率值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [用C++实现softmax函数(面试经验)](https://blog.csdn.net/qq_21008741/article/details/124496100)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [softmax 理解和c++ 实现](https://blog.csdn.net/rongbaohan/article/details/119913830)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

concyclics

可怜可怜孩子吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值