批量梯度下降(简单版.第一代)

// 梯度下降.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//批量梯度下降  

初学机器学习,如果有错误希望大家站出来,本案例为最简单版/第一代

#include <iostream>
#include<vector>
#include<math.h>
using namespace std;
vector<double>X = { 2,3,4,5,6,7,8,9,10,11,12};//定义X
vector<double>Y = { 1,5 ,2,7,8,1,3,9,10,21,22};//定义Y
double errorQ = 0.267;//学习误差阙值
double alph = 0.00001;//定义学习步长   收敛???
double theta = 2,theta1 = 3;//参数初始化
double costFunction(double x,double y){
    //return pow((theta *x+theta1)-y,2);
    return (y - (theta * x + theta1));
}
int main()
{
    int iteator=0;
    int error = 1;
    while (iteator<10000)//设置迭代500次
    {
        iteator++;
        cout << iteator << endl;
        double tem1 = 0;//用来记录求批量梯度下降的中间和
        double tem2 = 0;
        double judge=0;

        for (int i = 0; i <X.size(); i++)//批量梯度下降迭代求解
        {
            judge = costFunction(X[i], Y[i]);
            tem1 = tem1 +(costFunction(X[i], Y[i])*X[i]);//theta方向上偏导
            tem2 = tem2 + costFunction(X[i], Y[i]);
        }
        int ave = tem1/X.size();
        int ave2 = tem2/X.size();
        theta = theta- alph*abs(ave);
        theta1 = theta1- alph*abs(ave2);
        cout << theta << "    " << theta1 << endl;
        cout << judge << endl;
        if (abs(judge)<=errorQ) {
            cout << "完成:" << judge<<endl;
            break;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值