gpt4 book ai didi

r - 在 R 中创建多个偏差方差权衡图

转载 作者:行者123 更新时间:2023-12-01 09:14:12 26 4
gpt4 key购买 nike

我对 R 比较陌生。我想知道如何创建以下图形。我被困了两个多小时。

enter image description here

假设红线——真正的关系——是 y = x^2。假设我想将 100 个线性模型拟合到 100 个随机样本(蓝线)。

我该怎么做?到目前为止,这就是我所拥有的:

# create the true relationship
f <- function(x) x^2 # true model
x <- seq(0, 1, by = 0.01)
y <- f(x)

# plot the true function
plot(x, y, type = "l", col = "red", ylim = c(-0.2, 1.2), lwd = 4)

# fit 100 models
set.seed(1)
for (i in 1:100)
{
errors <- rnorm(n, 0, sigma) # random errors, have standard deviation sigma
obs_y <- f(obs_x) + errors # observed y = true_model + error
model <- lm(obs_y ~ obs_x) # fit a linear model to the observed values
points(obs_x[i], mean(obs_y[i]), col = "green") # mean values
abline(model, col = "purple") # plot the fitted model
}

创建这个:

enter image description here

其中的绿点肯定是关闭的......而且我没有黑点...

谢谢!

最佳答案

这是经过多次调整后的代码:

f <- function(x) x^2
x <- seq(0, 1, by = 0.05)
n <- length(x)
sigma <- 0.05
y <- f(x)

plot(x, y, type = "l", col = "red", ylim = c(-0.2, 1.2), lwd = 2)

fitted <- ys <- matrix(0, ncol = n, nrow = 100)

set.seed(1)
for (i in 1:100)
{
errors <- rnorm(n, 0, sigma)
ys[i, ] <- obs_y <- f(x) + errors
model <- lm(obs_y ~ x)
fitted[i, ] <- fitted(model)
abline(model, col = "purple", lwd = 0.1)
}

points(x = rep(x, each = 100), y = ys, cex = 0.1)
points(x = x, y = colMeans(fitted), col = 'green', cex = 0.3)

enter image description here

关于r - 在 R 中创建多个偏差方差权衡图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888090/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com