我不是R语言的专家。我正在尝试计算由多项式模型生成的偏差:
f <- function(x) sin(x-5)/(x-5)# 从中我们可以抽样数据集:N <- 20x <- 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个不同数据集中的给定点的预测之间的差异,这些数据集使用我们的多项式模型。我将这些结果存储在predictions向量中,最后函数返回差异的平均值的平方,即偏差的平方。
奇怪的是,当我执行普通代码,而不是在函数中时,它可以正常工作,不会生成任何错误。但当我运行:
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)# 从中我们可以抽样数据集:N <- 20x <- 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)