在R中,我生成了一些人工数据,用梯度下降法进行线性回归Y = c0 + c1 * x1 + c2 * x2 + 噪声。
我也用分析法计算参数θ=[c0,c1,c2]。下面是R代码与变量的注释。
我使用梯度下降法来计算theta。公式取自下面的链接。
斯坦福大学的幻灯片------------------------------------------------吴志强
但是,该方法无法收敛。我的R代码如下.theta与R代码中的分析解k有很大的不同。
rm(list = ls())
n=500
x1=rnorm(n,mean=4,sd=1.6)
x2=rnorm(n,mean=4,sd=2.5)
X=cbind(x1,x2)
A=as.matrix(cbind(rep(1,n),x1,x2))
Y=-3.9+3.8*x1-2.4*x2+rnorm(n,mean=0,sd=1.5);
k=solve(t(A)%*%A,t(A)%*%Y) # k is the parameters determined by analytical method
MSE=sum((A%*%k-Y)^2)/(n);
iterations=3000 # total number of step
epsilon = 0.0001 # set precision
eta=0.0001 # step size
t1=integer(iterations)
e1=integer(iterations)
X=as.matrix(X)# convert data table X into a matrix
N=dim(X)[1] # total number of observations
X=as.matrix(cbind(rep(1,length(N)),X))# add a column of ones to represent intercept
np=dim(X)[2] # number of parameters to be determined
theta=matrix(rnorm(n=np,mean=0,sd=1),1,np) # Initialize theta:1 x np matrix
for(i in 1:iterations){
error =theta%*%t(X)-t(Y) # error = (theta * x' -Y'). Error is a 1xN row vector;
grad=(1/N)*error%*%X # Gradient grad is 1 x np vector
theta=theta-eta*grad # updating theta
L=sqrt(sum((eta*grad)^2)) # calculating the L2 norm
e1[i]=sum((error)^2)/(2*N) # record the cost function in each step (value=2*MSE)
t1[i]=L # record the L2 norm in each step
if(L<=epsilon){ # checking whether convergence is obtained or not
break
}
}
plot(e1*2,type="l",ylab="MSE",lwd=2,col=rgb(0,0,1))
abline(h=MSE)
text(x=1000,y=MSE+1,labels = "Actual MSE",adj=1)
text(x=500,y=15,labels = "Gradient Descent",adj=0.4)
theta
k
我试过这段代码,问题是经过3000次迭代后,L2规范L仍然大于teh精度epsilon。我可以通过运行以下程序来获得可重复的样本数据 set.seed(5556)
首先。经过7419次迭代后,L=9.99938 e-5 < epsilon。然而θ仍与预期结果不同,当然对于L2常态和正常数据可以计算运行 lm(Y ~ X1+X2)
.