最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實現(xiàn)softmax函數(shù)的面試經(jīng)驗

 更新時間:2022年05月18日 12:57:17   作者:concyclics  
這篇文章主要為大家介紹了C++實現(xiàn)softmax函數(shù)的面試經(jīng)驗,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

背景

今天面試字節(jié)算法崗時被問到的問題,讓我用C++實現(xiàn)一個softmax函數(shù)。softmax是邏輯回歸在多分類問題上的推廣。大概的公式如下:

即判斷該變量在總體變量中的占比。

第一次實現(xiàn)

實現(xiàn)

我們用vector來封裝輸入和輸出,簡單的按公式復(fù)現(xiàn)。

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}

經(jīng)過簡單測試是正常的。

test 2

但是這時面試官提出了一個問題,即如果有較大輸入變量時會怎么樣?

  • 測試用例2: {1, 2, 3, 4, 5, 1000}
  • 測試輸出2: {0, 0, 0, 0, 0, nan}

由于 e^1000已經(jīng)溢出了雙精度浮點(double)所能表示的范圍,所以變成了NaN(not a number)。

第二次實現(xiàn)(改進)

改進原理

我們注意觀察softmax的公式:

如果我們給上下同時乘以一個很小的數(shù),最后答案的值是不變的。

那我們可以給每一個輸入 x i 都減去一個值 a ,防止爆精度。

大致表示如下:

實現(xiàn)

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}

我們發(fā)現(xiàn)結(jié)果正常了。

完整代碼

#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<<' ';
	}
}

以上就是C++實現(xiàn)softmax函數(shù)的面試經(jīng)驗的詳細內(nèi)容,更多關(guān)于C++ softmax函數(shù)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

阿鲁科尔沁旗| 迭部县| 东乡县| 从化市| 怀安县| 宜兰县| 石景山区| 翁牛特旗| 金平| 南阳市| 天镇县| 云南省| 惠东县| 霞浦县| 阿巴嘎旗| 财经| 海淀区| 县级市| 长乐市| 太白县| 湟源县| 托克托县| 南丹县| 阿巴嘎旗| 江陵县| 洛川县| 双城市| 蓝山县| 临湘市| 洪江市| 德州市| 石屏县| 临泽县| 海兴县| 永安市| 达拉特旗| 通道| 六盘水市| 定安县| 满洲里市| 堆龙德庆县|