我有这段代码
N <- 1000
beta1 = runif(N, -1,1);
beta2 = runif(N, -1,1);
x1 = seq(-500, 500, 0.01);
并且对于从1到N评估的每个i,我想绘制此函数
z = beta1[i] + beta2[i]*x1;
pr = 1/(1+exp(-z));
plot (x1,pr);
最后我会期待pr与x1的1000曲线。
为此我尝试了这个
for (i in 1:N){
z[i]= res[i,1] + res[i,2]*x1
pr[i] = 1/(1+exp(-z[i]));
plot(x1,pr[i])
}
但它列出了50个警告并且没有成功。
有帮助吗?
答案 0 :(得分:0)
这是一些矩阵乘法的好时机,可以简化和加快计算速度。你最大的问题是plot
每次调用都会打开一个新的情节。我假设您希望在同一图表上绘制所有线条。
N <- 1000
beta1 = runif(N, -1, 1)
beta2 = runif(N, -1, 1)
# I changed this to by = 1
# for plotting purposes you really done need 100k points per line
x1 = seq(-500, 500, 1)
z = cbind(1, x1) %*% rbind(beta1, beta2)
pr = 1 / (1 + exp(-z))
# this is the bug step you were missing
# initialize an empty plot with sufficient range
plot(range(x1), range(pr), type = "n")
# then just add to it in the for loop
for (i in 1:N) {
lines(x1, pr[, i])
}