2012-08-05 251 views
8

我一直在R中进行一些数据分析,并试图找出如何将我的数据拟合成3参数威布尔分布。我发现如何使用2参数Weibull来做到这一点,但是却发现如何用3参数来做到这一点。拟合R中的3参数Weibull分布

这里是我如何配合使用fitdistr从MASS包()函数的数据:

y <- fitdistr(x[[6]], 'weibull') 

x[[6]]是我的数据的一个子集,y是我在哪里存储拟合的结果。

+0

或许,如果你犯了一个[重复的例子(http://stackoverflow.com/questions/5963269/如何使一个伟大的再现的例子),演示你的问题/问题,人们会发现它更容易回答。具体来说,'x [[6]]'看起来像什么。至少,在'str(x [[6]]'或者最好是dput(x [[6]])的结果后面输入' – Andrie 2012-08-05 16:07:15

+2

'你不能使用R中可用的内置'weibull'分布,因为它是一个两参数威布尔分布,你必须计算自定义概率密度函数(3个参数),并用它来代替 – dickoa 2012-08-05 16:17:59

回答

8

首先,你可能想看看FAdist package。然而,事实并非如此用心地去从rweibull3rweibull

> rweibull3 
function (n, shape, scale = 1, thres = 0) 
thres + rweibull(n, shape, scale) 
<environment: namespace:FAdist> 
dweibull3

和类似dweibull

> dweibull3 
function (x, shape, scale = 1, thres = 0, log = FALSE) 
dweibull(x - thres, shape, scale, log) 
<environment: namespace:FAdist> 

,所以我们有这个

> x <- rweibull3(200, shape = 3, scale = 1, thres = 100) 
> fitdistr(x, function(x, shape, scale, thres) 
     dweibull(x-thres, shape, scale), list(shape = 0.1, scale = 1, thres = 0)) 
     shape   scale   thres  
    2.42498383  0.85074556 100.12372297 
( 0.26380861) ( 0.07235804) ( 0.06020083) 

编辑:作为在评论中提到,当试图符合分配时会出现各种警告离子这样

Error in optim(x = c(60.7075705026659, 60.6300379017397, 60.7669410153573, : 
    non-finite finite-difference value [3] 
There were 20 warnings (use warnings() to see them) 
Error in optim(x = c(60.7075705026659, 60.6300379017397, 60.7669410153573, : 
    L-BFGS-B needs finite values of 'fn' 
In dweibull(x, shape, scale, log) : NaNs produced 

对我起初它只是NaNs produced,而不是当我看到它,所以我认为它不是那么有意义,因为估计是很好的第一次。经过一番搜索,似乎是相当流行的问题,我找不到原因和解决办法。一种替代方案可能是使用stats4包和mle()函数,但它似乎也有一些问题。但我可以为您提供通过danielmedic使用的code修改后的版本,我已经检查了几次:

thres <- 60 
x <- rweibull(200, 3, 1) + thres 

EPS = sqrt(.Machine$double.eps) # "epsilon" for very small numbers 

llik.weibull <- function(shape, scale, thres, x) 
{ 
    sum(dweibull(x - thres, shape, scale, log=T)) 
} 

thetahat.weibull <- function(x) 
{ 
    if(any(x <= 0)) stop("x values must be positive") 

    toptim <- function(theta) -llik.weibull(theta[1], theta[2], theta[3], x) 

    mu = mean(log(x)) 
    sigma2 = var(log(x)) 
    shape.guess = 1.2/sqrt(sigma2) 
    scale.guess = exp(mu + (0.572/shape.guess)) 
    thres.guess = 1 

    res = nlminb(c(shape.guess, scale.guess, thres.guess), toptim, lower=EPS) 

    c(shape=res$par[1], scale=res$par[2], thres=res$par[3]) 
} 

thetahat.weibull(x) 
    shape  scale  thres 
3.325556 1.021171 59.975470 
+0

我这样做,我得到一个错误信息如下:fitdistr(x,function(x,shape,scale dweibull(x - thres,: 优化失败 此外:警告消息: 1:在dweibull(x-thres,形状,比例):产生的NaN 2:在dweibull(x - thres,shape,scale ):产生的NaN 3:在dweibull(x-thres,shape,scale)中:产生NaN 4:在dweibull(x-thres,shape,scale)中:NaNs产生 – 2012-08-07 02:24:45

+0

@Wallhood,我编辑了答案,现在它似乎完美地工作,但不幸的是,它不提供有关差异的信息。 – Julius 2012-08-07 09:57:39

+1

哇,我不能告诉你这是多么可怕,我是多么感激。如果你曾经在俄勒冈州波特兰,我会很乐意给你买一瓶啤酒。 – 2012-08-09 02:24:23