标签:
梯度下降法:
应用:求线性回归方程的系数
目标:最小化损失函数 (损失函数定义为残差的平方和)
搜索方向:负梯度方向,负梯度方向是下降最快的方向
#Gradient Descent 梯度下降法
# 在直接设置固定的step时,不宜设置的过大,当步长过大时会报错:
# Error in while ((newerror > error) | (iter < maxiter)) { : missing value where TRUE/FALSE needed
#原因是step过大,会导致在迭代过程中梯度会特别的大,当超过1e+309时就会直接变成无穷Inf
#梯度下降法 求线性回归方程系数theta
#x为数据矩阵(mxn m:样本数 n:特征数 );y观测值(mx1);error相邻两次迭代的最大误差;
#step为设定的固定步长;maxiter最大迭代次数,alpha,beta为回溯下降法的参数
GradientDescent<-function(x,y,error,maxiter,stepmethod=T,step=0.001,alpha=0.25,beta=0.8)
{
m<-nrow(x)
n<-ncol(x)+1
x<-cbind(matrix(1,m,1),x)
theta<-matrix(rep(1,n),n,1) #theta初始值都设置为1
iter<-1
newerror<-1
while((newerror>error)|(iter<maxiter)){
iter<-iter+1
h<-x%*%theta
des<-t(t(h-y)%*%x) #梯度
#回溯下降法求步长t
if(stepmethod==T){
sstep=1
new_theta<-theta-sstep*des
new_h<-x%*%new_theta
costfunction<-t(h-y)%*%(h-y) #最小二乘损失函数
new_costfunction<-t(new_h-y)%*%(new_h-y)
#回溯下降法求步长sstep
while(new_costfunction>costfunction-alpha*sstep*sum(des*des)){
sstep<-sstep*beta
new_theta<-theta-sstep*des
new_h<-x%*%new_theta
new_costfunction<-t(new_h-y)%*%(new_h-y)
}
newerror<-sum(abs(theta-new_theta),na.rm=T)
theta<-new_theta
}
#直接设置固定步长
if(stepmethod==F){
new_theta<-theta-step*des
new_h<-x%*%new_theta
# new_costfunction<-t(new_h-y)%*%(new_h-y)
newerror<-sum(abs(theta-new_theta))
theta<-new_theta
}
}
result<-list(theta,iter,newerror)
names(result)<-c(‘系数‘,‘迭代次数‘,‘误差‘)
result
}
标签:
原文地址:http://www.cnblogs.com/runner-ljt/p/4552900.html