gpt4 book ai didi

r - 如何在一张图中绘制 Gamma 分布的拟合图和实际图?

转载 作者:行者123 更新时间:2023-12-01 16:46:32 27 4
gpt4 key购买 nike

步骤 1。加载所需的包。

library(ggplot2)
library(MASS)

步骤 2。生成 10,000 个适合 Gamma 分布的数字。

x <- round(rgamma(100000,shape = 2,rate = 0.2),1)
x <- x[which(x>0)]

步骤 3。假设我们不知道 x 适合哪个分布,请绘制 pdf(概率密度函数)。

t1 <- as.data.frame(table(x))
names(t1) <- c("x","y")
t1 <- transform(t1,x=as.numeric(as.character(x)))
t1$y <- t1$y/sum(t1[,2])
ggplot() + geom_point(data = t1,aes(x = x,y = y)) + theme_classic()

enter image description here

步骤 4。从图中我们可以看出,x的分布很像gamma分布,因此我们使用MASS包中的fitdistr()来得到gamma分布的shaperate参数。

fitdistr(x,"gamma") 
## output
## shape rate
## 2.0108224880 0.2011198260
## (0.0083543575) (0.0009483429)

步骤 5。在同一个图中画出实际点(黑点)和拟合图(红线),这是问题,请先看图。

ggplot() + geom_point(data = t1,aes(x = x,y = y)) +     
geom_line(aes(x=t1[,1],y=dgamma(t1[,1],2,0.2)),color="red") +
theme_classic()

enter image description here

问题1:真实的参数是shape=2rate=0.2,我使用函数fitdistr()来获取参数得到的是 shape=2.01rate=0.20。这两个几乎是一样的,但是为什么拟合图与实际点拟合得不太好,一定是拟合图有问题,或者我绘制拟合图和实际点的方式完全错误,我该怎么办?

问题2:当我得到我建立的模型的参数后,我用什么方式评估模型,比如线性模型的RSS(残差平方和),或者p -valueshapiro.test()ks.test() 和其他测试?我统计知识很差,请帮我解答这两个问题,谢谢!(ps:我在Google和stackoverflow上搜索了很多次,但都不起作用,所以不要投票这个问题没有用,Thx! )

最佳答案

出于某种原因,您的拟合线似乎正好是高的 10 倍:

ggplot() + geom_point(data = t1,aes(x = x,y = y)) +     
geom_line(aes(x=t1[,1],y=(dgamma(t1[,1],2,0.2))/10),color="red") +
theme_classic()

完美契合: enter image description here

正如 jbaums 所说,这是由每 dx 的密度造成的,在本例中为 0.1。

关于r - 如何在一张图中绘制 Gamma 分布的拟合图和实际图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34737909/

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