码迷,mamicode.com
首页 > 编程语言 > 详细

梯度下降算法 c++实现

时间:2019-09-04 19:22:53      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:return   标准化   ++i   梯度   max   cout   efi   class   iostream   

没有数据标准化的版本,效率非常高,而且训练结果并不好。

#include <iostream>
#define maxn 105
#include <cstdio>
using namespace std;
int n,m;  //n个特征,m个数据
double theta[maxn];//参数集
double temp[maxn];
double data[maxn][maxn];//数据集
double Y[maxn];//结果集
double hx[maxn];
const double eps=0.37;
double alpha=0.00001;
double h(int x)//计算假设函数
{
    double res=0;
    for(int i=0;i<=n;++i)
    {
        res+=theta[i]*data[x][i];
    }
    return res;
}
double J_theta()//计算cost function
{
    double res=0;
    for(int i=1;i<=m;++i)
    {
        res+=(h(i)-Y[i])*(h(i)-Y[i]);
    }
    res=res/(2*m);
    return res;
}
double f(int x)//求偏导数
{
    double res=0;
    for(int i=1;i<=m;++i)
    {
        res+=hx[i]*data[i][x];
    }
    res/=m;
    return res;
}
void Gradient_Descent()//梯度下降
{
    for(int i=1;i<=m;++i)
    {
        data[i][0]=1;
    }
    for(int i=0;i<=n;++i)
    {
        theta[i]=1;//初始化
    }
    double now,nex;
    do
    {
        now=J_theta();
        for(int i=1;i<=m;++i)
        {
            hx[i]=h(i)-Y[i];
        }
        for(int i=0;i<=n;++i)
        {
            temp[i]=theta[i]-alpha*f(i);
        }
        for(int i=0;i<=n;++i)
        {
            theta[i]=temp[i];
        }
        nex=J_theta();
        //cout<<J_theta()<<endl;
    }while (J_theta()>eps);
}
int main()
{
    freopen("in.txt","r",stdin);
    cin>>n>>m;
    for(int i=1;i<=m;++i)
    {
        for(int j=1;j<=n;++j)
        {
            cin>>data[i][j];
        }
    }
    for(int i=1;i<=m;++i)
    {
        cin>>Y[i];
    }
    Gradient_Descent();
    for(int i=0;i<=n;++i)
    {
        printf("%.2lf\n",theta[i]);
    }
    return 0;
}

 

梯度下降算法 c++实现

标签:return   标准化   ++i   梯度   max   cout   efi   class   iostream   

原文地址:https://www.cnblogs.com/zyf3855923/p/11460864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!