我不是 R 专家。我正在尝试计算多项式模型生成的偏差:
f <- function(x) sin(x-5)/(x-5)
# From which we can sample datasets:
N <- 20
x <- runif(N,0,15)
t <- f(x) + rnorm(N, sd=0.1)
t是生成数据的函数,我使用标准差为0.2的高斯误差的同步函数。 为了创建点 x,我使用均匀分布形式 0 到 15。
plot.bias <- function (f, polydeg) {
plot(data.frame(x, t))
curve(f, type="l", col="green", add=TRUE)
polyfit <- lm(t ~ poly(x, polydeg, raw=TRUE))
p <- polynom(coef(polyfit))
curve(p, col="red", add=TRUE)
points(x, calc.bias(f, polydeg, x), col="blue")
abline(h=0, col='blue')
}
该函数首先绘制数据,然后绘制原始生成曲线,接下来计算给定次数的回归多项式,绘制它,最后绘制偏差。偏差由以下函数计算得出,该函数给出了误差:
calc.bias <- function (f, polyfit, point) {
predictions <- numeric(0)
print(class(point))
for (i in 1:100)
{
x <- runif(N, 0, 15)
t <- f(x) + rnorm(N, sd=0.2)
d <- data.frame(point)
add <- predict(polyfit, newdata = data.frame(point))
predictions <- c(predictions, add)
}
return((f(point)-mean(predictions))^2)
}
我所做的是使用我们的多项式模型计算最佳预测(f 函数)减去 100 个不同数据集中给定点的预测的差值。我将这些结果存储在预测向量中,最后函数返回差异均值的平方,即平方偏差。
奇怪的是,当我执行纯代码而不是函数时,它可以工作,并且不会生成任何错误。但是当我运行时:
plot.bias(f, 1)
出现错误。怎么了?许多交易
最佳答案
我想我找到了。这似乎有效,但不确定是否是您所期望的。在 plot.bias
中,我更改了对 calc.bias
的使用(即 calc.bias(f, polyfit, x)
而不是 >calc.bias(f, polydeg, x)
)。我使用的整个代码:
library(PolynomF)
f <- function(x) sin(x-5)/(x-5)
# From which we can sample datasets:
N <- 20
x <- runif(N,0,15)
t <- f(x) + rnorm(N, sd=0.1)
calc.bias <- function (f, polyfit, point) {
predictions <- numeric(0)
print(class(point))
for (i in 1:100)
{
x <- runif(N, 0, 15)
t <- f(x) + rnorm(N, sd=0.2)
d <- data.frame(point)
add <- predict(polyfit, newdata = data.frame(point))
predictions <- c(predictions, add)
}
return((f(point)-mean(predictions))^2)
}
plot.bias <- function (f, polydeg) {
plot(data.frame(x, t))
curve(f, type="l", col="green", add=TRUE)
polyfit <- lm(t ~ poly(x, polydeg, raw=TRUE))
p <- polynom(coef(polyfit))
curve(p, col="red", add=TRUE)
points(x, calc.bias(f, polyfit, x), col="blue")
abline(h=0, col='blue')
}
plot.bias(f, 1)
关于r - 使用方法错误 ("predict"): no applicable method for 'predict' applied to an object of class "c(' double', 'numeric'),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54926897/