根据老师的要求,基于[-1,1]上的均匀分布随机生成20个样本,相应的输出有20%的错误率;20个样本将数轴分为21段,中间有19段,θ取这19段的中点当中的一个,s取1或-1。遍历所有的θ和s,找到E-in最小的(θ,s)组合就得到了那个g函数。
#include#include #include #include #include using namespace std;#define SAMPLE_SIZE 20 //样本量struct Hypothesis{ int coef; double threshold; };//求数字的符号int sign(double x){ if(x<0) return -1; else if(x>0) return 1; else return -1;}//反转数字的符号int flipSign(int num){ return num * (-1); }//计算样本错误率double calErrInSample(vector & inputVec, vector & outputVec, Hypothesis & hypo){ int errCount = 0; for(int i=0;i & inputVec){ for(int i=0;i & inputVec, vector & outputVec){ int output; double randNum; for(int i=0;i & inputVec, vector & outputVec, Hypothesis & hypo, double & bestThres ){ double minErrIn = 1.0; double curErrIn; for(int i=0;i & inputVec, vector & outputVec, Hypothesis & hypo ){ double minErrInPositive = 1.0; double minErrInNegtive = 1.0; double minErrIn; double bestThresPositive; double bestThresNegtive; hypo.coef = 1; minErrInPositive = getMinErrIn(inputVec,outputVec,hypo,bestThresPositive); hypo.coef = -1; minErrInNegtive = getMinErrIn(inputVec,outputVec,hypo,bestThresNegtive); if(minErrInPositive inputVec; vector outputVec; Hypothesis hypo; getTrainingData(inputVec); calOutput(inputVec,outputVec); errInTotal += decisionStump(inputVec,outputVec,hypo); errOutTotal += calErrOutSample(hypo); cout<<"-----------------第"< <<"次计算结束-------------------\n"; cout<<"s = "< <
计算结果: