02.梯度下降解多元线性回归

每次迭代时间复杂度O(m*n)

#include<bits/stdc++.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];
	  }
	}
  	
	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=5;
  x[1][1]=1;x[1][2]=1;x[1][3]=2;x[1][4]=-1;x[1][5]=-3;
  x[2][1]=2;x[2][2]=1;x[2][3]=2;x[2][4]=-1;x[2][5]=-3;
  x[3][1]=3;x[3][2]=4;x[3][3]=1;x[3][4]=-4;x[3][5]=-2;
  x[4][1]=1;x[4][2]=0;x[4][3]=1;x[4][4]=-1;x[4][5]=-3;
  x[5][1]=1;x[5][2]=1;x[5][3]=2;x[5][4]=-2;x[5][5]=-3;
  
  y[1]=2;
  y[2]=3;
  y[3]=4;
  y[4]=0;
  y[5]=1;
  double * theta;
  theta=solve(x,y,m,n);
  for(int i=0;i<=n;i++)
  cout<<theta[i]<<endl;
  return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值