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
    评论
基于梯度下降法多元线性回归是一种用于求多个特征变量的线性回归问题的算法。在多元线性回归中,我们构建一个代价函数,目标是找到使得代价函数最小的一系列参数。梯度下降算法通过迭代的方式,不断调整参数的值,使得代价函数逐渐减小,最终找到最优的参数值。 具体而言,梯度下降算法通过计算代价函数对参数的偏导数来确定参数的更新方向。在每一次迭代中,根据当前参数的值和偏导数的值,更新参数的值,使得代价函数逐渐减小。这个过程会一直进行,直到达到预定的停止条件。 在多元线性回归中,我们可以使用批量梯度下降算法来求代价函数的最小值。批量梯度下降算法通过计算所有样本的梯度来更新参数的值,因此每一次迭代都需要遍历整个训练集。这种算法的优点是可以找到全局最优,但计算量较大。 总结来说,基于梯度下降法多元线性回归是一种通过迭代调整参数值的算法,用于求多个特征变量的线性回归问题。它可以通过计算代价函数的偏导数来确定参数的更新方向,并通过不断迭代来逐渐减小代价函数的值,最终找到最优的参数值。 #### 引用[.reference_title] - *1* *2* *3* [机器学习-线性回归-多元梯度下降法](https://blog.csdn.net/kingsure001/article/details/107465231)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值