通过sapply和uniroot构造逆回归

时间:2017-08-15 15:23:58

标签: r inverse

我的功能如下:

V <- seq(50, 350, by = 1)
> VK
    Voltage^0     Voltage^1     Voltage^2     Voltage^3 
-1.014021e+01  9.319875e-02 -2.738749e-04  2.923875e-07 
> plot(x = V, exp(exp(sapply(0:3, function(x) V^x) %*% VK)), type = "l"); grid()

现在我想对这个特定函数进行逆回归。我看过Solving for the inverse of a function in R

  

inverse = function(f,lower = -100,upper = 100){      function(y)uniroot((function(x)f(x) - y),lower = lower,upper = upper)1   }

     

square_inverse = inverse(function(x)x ^ 2,0.1,100)

     

square_inverse(4)

我试图根据我的目的调整它,如下所示:

certain_function <- function(x=V) { exp(exp(sapply(0:3, function(x) V^x) %*% VK)) }

inverse = function (f, lower = 50, upper = 350) {
  function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1]
}

inverse_regression = inverse(certain_function, 50, 350)

inverse_regression(2)

不幸的是,这会产生:

 Error in uniroot((function(x) f(x) - y), lower = lower, upper = upper) : 
  f() values at end points not of opposite sign In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
  the condition has length > 1 and only the first element will be used

据我所知:错误意味着有更多的根而不是只有一个(uniroot只能处理一个根)但是不应该有多个根,因为它是严格单调递增的函数。 警告我不明白..

编辑:我试图躲过它..我删除了两个指数,产生了以下情节:

enter image description here

,这仍会产生以下错误:

> inverse_regression(0.1)

 Error in uniroot((function(x) f(x) - y), lower = lower, upper = upper) : 
  f() values at end points not of opposite sign In addition: Warning messages:
1: In if (is.na(f.lower)) stop("f.lower = f(lower) is NA") :
  the condition has length > 1 and only the first element will be used
2: In if (is.na(f.upper)) stop("f.upper = f(upper) is NA") :
  the condition has length > 1 and only the first element will be used

这是为什么?显然曲线在两个端点都有相反的符号。我猜终点意味着从根向左和向右的点?

1 个答案:

答案 0 :(得分:0)

由于“Certain_function”的定义,逆向回归可能不起作用。这是一个矩阵向量乘积,结果又是一个向量。因此,我将其转换为常规函数BEGIN TRAN CREATE TABLE #TMP (Department NVARCHAR(50),Name NVARCHAR(50)) INSERT INTO #TMP SELECT 'Insights', 'Mike' UNION ALL SELECT 'Insights','Mike' UNION ALL SELECT 'Insights','Chris'UNION ALL SELECT 'Market' ,'Julie' UNION ALL SELECT 'Research', 'Will'UNION ALL SELECT 'Research', 'Sabrina'UNION ALL SELECT 'Research','Bryan' SELECT * FROM #TMP SELECT department, COUNT(DISTINCT NAME) FROM #TMP GROUP BY department ROLLBACK TRAN ,现在它正在运行。 因此,每次都应该意识到界限。