标签: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; }
标签:return 标准化 ++i 梯度 max cout efi class iostream
原文地址:https://www.cnblogs.com/zyf3855923/p/11460864.html