2017-08-15 45 views
1

我有一个函数如下:通过sapply构建逆回归和uniroot

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 

这是为什么?很显然,曲线在两个端点都有相反的标志。我猜测端点意味着根部的左右点?

+0

好的,我解决了它。不知道它到底是什么,但是当我将矩阵向量产品转换成常规函数时,它的工作原理是:) – Ben

回答

0

由于“certain_function”的定义,反向回归可能不起作用。这是一个矩阵向量乘积,结果又是一个向量。因此,我将其转换为常规函数function(x) exp(exp(sum(x^0*VK[1],x^1*VK[2],x^2*VK[3],x^3*VK[4])),现在它正在工作。因此,每个人都应该知道一般的界限。