具有输出图和回归线的梯度下降函数

时间:2017-02-07 21:41:11

标签: r machine-learning

我一直在运行以下代码,它返回正确的系数。但是,无论我在哪里拨打plot电话,我都无法获得任何情节输出。

我不确定这里是否需要可重复的示例,因为我认为可以通过查看下面的gradientDescent函数来解决这个问题?这是我第一次尝试在R中运行此算法:

gradientDescent <- function(x, y, learn_rate, conv_threshold, n, max_iter) {
  m <- runif(1, 0, 1)
  c <- runif(1, 0, 1)
  yhat <- m * x + c
  cost_error <- (1 / (n + 2)) * sum((y - yhat) ^ 2)
  converged = F
  iterations = 0
  while(converged == F) {
    m_new <- m - learn_rate * ((1 / n) * (sum((yhat - y) * x)))
    c_new <- c - learn_rate * ((1 / n) * (sum(yhat - y)))
    m <- m_new
    c <- c_new
    yhat <- m * x + c
    cost_error_new <- (1 / (n + 2)) * sum((y - yhat) ^ 2)
    if(cost_error - cost_error_new <= conv_threshold) {
      converged = T
    }
    iterations = iterations + 1
    if(iterations > max_iter) {
      converged = T
    return(paste("Optimal intercept:", c, "Optimal slope:", m))
    }
  }
}

1 个答案:

答案 0 :(得分:1)

目前还不清楚你一直在做什么是无效的。即使在函数内部使用,基本图形函数plotabline也应该能够生成输出。 Lattice和ggplot2图形基于grid - grpahics,因此需要在函数调用周围创建一个print()来创建输出(如R-FAQ中所述)。所以试试这个:

gradientDescent <- function(x, y, learn_rate, conv_threshold, n, max_iter) 
    { ## plot.new() perhaps not needed
      plot(x,y)
      m <- runif(1, 0, 1)
      c <- runif(1, 0, 1)
      yhat <- m * x + c
      cost_error <- (1 / (n + 2)) * sum((y - yhat) ^ 2)
      converged = F
      iterations = 0
      while(converged == F) {
        m_new <- m - learn_rate * ((1 / n) * (sum((yhat - y) * x)))
        c_new <- c - learn_rate * ((1 / n) * (sum(yhat - y)))
        m <- m_new
        c <- c_new
        yhat <- m * x + c
        cost_error_new <- (1 / (n + 2)) * sum((y - yhat) ^ 2)
        if(cost_error - cost_error_new <= conv_threshold) {
          converged = T
        }
        iterations = iterations + 1
        if(iterations > max_iter) { abline( c, m)  #calculated 
          dev.off()
          converged = T
        return(paste("Optimal intercept:", c, "Optimal slope:", m))
        }
      }
    }