多元线性回归 – R语言中的梯度下降

我正在学习机器学习。因此,我使用在线找到的数据进行了一些简单的练习。现在,我尝试在R语言中通过梯度下降实现线性回归。当我运行它时,我发现它没有收敛,我的成本函数值无限增加。虽然我怀疑问题出在计算梯度的那部分,但我无法找到具体问题所在。所以,让我们开始展示我的数据吧。

我的数据集包含4列:ROLL ~ UNEM, HGRAD, INC,所以,目标是找出ROLL与其他变量之间的关系。

  • 让我展示我的代码

    datavar <- read.csv("dataset.csv")attach(datavar)X <- cbind(rep(1, 29), UNEM,HGRAD,INC)y <- ROLL# function where I calculate my predictionh <- function(X, theta){  return(t(theta) %*% X)}# function where I calculate the cost with current valuescost <- function(X, y, theta){  result <- sum((X %*% theta - y)^2 ) / (2*length(y))  return(result)}# here I calculate the gradient, #mathematically speaking I calculate derivetive of cost function at given pointsgradient <- function(X, y, theta){  m <- nrow(X)  sum <- c(0,0,0,0)  for (i in 1 : m) {    sum <- sum + (h(X[i,], theta) - y[i]) * X[i,]  }  return(sum)}# The main algorithm gradientDescent <- function(X, y, maxit){  alpha <- 0.005  m <- nrow(X)  theta <- c(0,0,0,0)  cost_history <- rep(0,maxit)  for (i in 1 : maxit) {    theta <- theta - alpha*(1/m)*gradient(X, y, theta)    cost_history[i] <- cost(X, y, theta)  }  plot(1:maxit, cost_history, type = 'l')  return(theta)}

我这样运行代码

 gradientDescent(X, y, 20)

这是我得到的输出:

-7.001406e+118  -5.427330e+119  -1.192040e+123  -1.956518e+122

那么,你能找出我哪里做错了?我已经尝试了不同的alpha值,但没有效果。顺便说一下,我很感激你能提供任何建议或好的实践,

谢谢


回答:

嗯,我想我终于找到了答案。问题是我没有应用任何特征缩放。因为我认为这是运行算法顺利进行的可选步骤。现在它按预期工作了。你可以尝试使用R语言的scale()函数对数据集进行缩放后运行代码。

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注