标签:turn while ++i 随机梯度 number die cos 随机梯度下降 []
#include <iostream>
#include <vector>
#include <cmath>
#include <cfloat>
int main() {
double datax[]={3.4,1.8,4.6,2.3,3.1,5.5,0.7,3.0,2.6,4.3,2.1,1.1,6.1,4.8,3.8};
double datay[]={26.2,17.8,31.3,23.1,27.5,36.0,14.1,22.3,19.6,31.3,24.0,17.3,43.2,36.4,26.1};
double cost=DBL_MAX;
std::vector<double> v_datax,v_datay;
for(size_t i=0;i<sizeof(datax)/sizeof(datax[0]);++i) {
v_datax.push_back(datax[i]);
v_datay.push_back(datay[i]);
}
int number=v_datax.size();
double a=0,b=0,error=0;
while(true) {
for(std::vector<double>::iterator iterx=v_datax.begin(),itery=v_datay.begin();
iterx!=v_datax.end(),itery!=v_datay.end();++iterx,++itery) {
a=a-0.003*(a+b*(*iterx)-*itery);
b=b-0.003*(a+b*(*iterx)-*itery)*(*iterx);
}
error=0;
for(std::vector<double>::iterator iterx=v_datax.begin(),itery=v_datay.begin();
iterx!=v_datax.end(),itery!=v_datay.end();++iterx,++itery) {
error+=(a+b*(*iterx)-*itery)*(a+b*(*iterx)-*itery)*0.5/number;
}
if(std::abs(cost-error)<0.0000000000001)
break;
cost=error;
}
std::cout<<"a = "<<a<<std::endl;
std::cout<<"b = "<<b<<std::endl;
return 0;
}
随机梯度下降(Stochastic gradient descent) C++
标签:turn while ++i 随机梯度 number die cos 随机梯度下降 []
原文地址:http://www.cnblogs.com/donggongdechen/p/7399322.html