// 梯度下降.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;
}
}
}