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

我运行了以下代码,返回了正确的系数。然而,无论我在哪里调用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))    }  }}

回答:

不清楚你之前尝试了什么方法但没有效果。基础图形函数plotabline即使在函数内部使用也应该能生成输出。Lattice和ggplot2图形基于grid图形,因此需要在函数调用外包一层print()才能生成输出(如R-FAQ中所述)。所以试试这样做:

gradientDescent <- function(x, y, learn_rate, conv_threshold, n, max_iter)     { ## plot.new() 或许不需要      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)  #计算的           dev.off()          converged = T        return(paste("Optimal intercept:", c, "Optimal slope:", m))        }      }    } 

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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