首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用“D”求出我的回归多项式的导数时的误差

使用“D”求出我的回归多项式的导数时的误差
EN

Stack Overflow用户
提问于 2016-01-14 21:02:24
回答 1查看 1K关注 0票数 4

我在二维图上有点。我想找到最适合这个模型的第三次多项式,并得到它的一阶导数。但是我不能让D函数工作。下面是一个简单的例子:

代码语言:javascript
运行
复制
a <- 0:10
b <- c(2, 4, 5, 8, 9, 12, 15, 16, 18, 19, 20)
plot(a, b)
m1 <- lm(b ~ a + I(a ^ 2) + I(a ^ 3))
s <- coef(m1)

## try to get 1st derivative of the regression polynomial
D(expression(s[1] + s[2] * a + (a ^ 2) * s[3] + (a ^ 3) * s[4]), "a")

D中的错误(表达式(s1+ s2 *a+ (a^2) * s3 + (a^3) * s4),: 函数'[‘不在导数表中

我想避免通过差分来计算数值导数。谢谢你帮忙!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-05 23:07:37

您看到的“'**[**‘函数不在派生表”中的错误消息是因为D只能识别用于符号操作的特定函数集。你可以在?D中找到它们

代码语言:javascript
运行
复制
The internal code knows about the arithmetic operators ‘+’, ‘-’,
‘*’, ‘/’ and ‘^’, and the single-variable functions ‘exp’, ‘log’,
‘sin’, ‘cos’, ‘tan’, ‘sinh’, ‘cosh’, ‘sqrt’, ‘pnorm’, ‘dnorm’,
‘asin’, ‘acos’, ‘atan’, ‘gamma’, ‘lgamma’, ‘digamma’ and
‘trigamma’, as well as ‘psigamma’ for one or two arguments (but
derivative only with respect to the first).  (Note that only the
standard normal distribution is considered.)

"["实际上是R中的一个函数(read ?Extract?"[")。

为了表明类似的行为,考虑:

代码语言:javascript
运行
复制
s <- function (x) x

D(expression(s(x) + x ^ 2), name = "x")
# Error in D(expression(s(x) + x^2), name = "x") : 
#  Function 's' is not in the derivatives table

在这里,尽管s被定义为一个简单的函数,但D对它无能为力。

你的问题已经被我最近对Function for derivatives of polynomials of arbitrary order (symbolic method preferred)的回答解决了。在我的三个答案中提供了三种方法,没有一种是基于数值导数的。我个人更喜欢outer ( LaTeX数学公式的唯一答案),对于多项式,一切都是精确的。

要使用该解决方案,在那里使用函数g,并通过要计算导数(例如0:10)的值指定参数x,并通过多项式回归系数s指定pc。默认情况下,nderiv = 0L将返回多项式本身,就像调用predict.lm(m1, newdata = list(a = 0:10))一样。但是一旦指定了nderiv,你就得到了回归曲线的精确导数。

代码语言:javascript
运行
复制
a <- 0:10
b <- c(2, 4, 5, 8, 9, 12, 15, 16, 18, 19, 20)
plot(a, b)
m1 <- lm(b ~ a + I(a ^ 2) + I(a ^ 3))
s <- coef(m1)
#(Intercept)           a      I(a^2)      I(a^3) 
# 2.16083916  1.17055167  0.26223776 -0.02020202 

## first derivative at your data points
g(0:10, s, nderiv = 1)
# [1] 1.1705517 1.6344211 1.9770785 2.1985237 2.2987568 2.2777778 2.1355866
# [8] 1.8721834 1.4875680 0.9817405 0.3547009

其他备注:建议您使用poly(a, degree = 3, raw = TRUE)而不是I()。它们在这里也是如此,但是poly更简洁,如果您想要交互,可以更容易地进行,就像在How to write interactions in regressions in R?中一样

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34799673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档