虽然是不同的算法,但是最后结果的形式和多元线性回归几乎一样,只要稍微改改就好了
正规方程法解线性回归只涉及简单的矩阵运算即使要使用也不会有太多改动所以不会写
(样例学习率没有特别调过。。。不要在意这些细节,大概按1,3,10,30这种倍数调就好了)
#include<bits/stdc++.h>
#include<math.h>
#define ll long long
using namespace std;
const double eps=1e-10;
double * solve(double x[][10],double y[],int m,int n)//输入数组x,y训练集大小m,特征数量n
{
static double theta[10];
double alpha=0.01;
double tmp[10];
for(int i=1;i<=m;i++)
x[i][0]=1.0;
for(int i=0;i<=n;i++)
{
theta[i]=0.0;
}
/*for(int i=1;i<=m;i++)
{
for(int j=0;j<=n;j++)
cout<<x[i][j]<<" ";
cout<<endl;
}*/
//int t=100;
while(1)
{
double ans[10];
for(int i=1;i<=m;i++)
{
ans[i]=0.0;
for(int j=0;j<=n;j++)
{
ans[i]=1.0*ans[i]+x[i][j]*theta[j];
}
ans[i]=1.0/(1.0+exp(-ans[i]));
}
for(int i=0;i<=n;i++)
{
tmp[i]=0.0;
for(int j=1;j<=m;j++)
{
tmp[i]=1.0*tmp[i]+1.0*x[j][i]*(ans[j]-y[j]);
if(i==0)
cout<<" "<<ans[j]<<" "<<y[j]<<endl;
}
}
int tm;
for(tm=0;tm<=n;tm++)
{
if(abs(tmp[tm])>eps)
break;
}
if(tm>n)
{
break;
}
for(int i=0;i<=n;i++)
cout<<theta[i]<<" ";
cout<<endl;
for(int i=0;i<=n;i++)
cout<<tmp[i]<<" ";
cout<<endl<<endl;
for(tm=0;tm<=n;tm++)
{
theta[tm]=1.0*theta[tm]-1.0*alpha*tmp[tm]/(1.0*m);
}
}
return theta;
}
int main()
{
double x[15][10],y[15];
int m=5,n=1;
x[1][1]=1;
x[2][1]=2;
x[3][1]=3;
x[4][1]=5;
x[5][1]=8;
y[1]=0;
y[2]=0;
y[3]=0;
y[4]=1;
y[5]=1;
double * theta;
theta=solve(x,y,m,n);
for(int i=0;i<=n;i++)
cout<<theta[i]<<endl;
return 0;
}