修订版 | d98741928ecb2febd67065825ddfa9d0c8d43ca1 (tree) |
---|---|
时间 | 2017-12-21 19:57:18 |
作者 | Lorenzo Isella <lorenzo.isella@gmai...> |
Commiter | Lorenzo Isella |
A code showing how to fit a beta distributions using a couple of methods and also explicitly writing the log-likelyhood function.
@@ -0,0 +1,87 @@ | ||
1 | +rm(list=ls()) | |
2 | + | |
3 | +library(MASS) | |
4 | +library(stats4) | |
5 | + | |
6 | + | |
7 | +dbeta1 <- function(x, shape, ...) | |
8 | + dbeta(x, shape, shape, ...) | |
9 | + | |
10 | + | |
11 | +dbeta2 <- function(x, shape){ | |
12 | + | |
13 | + | |
14 | + res <- x^(shape-1)*(1-x)^(shape-1)/beta(shape, shape) | |
15 | + | |
16 | + return(res) | |
17 | + | |
18 | +} | |
19 | + | |
20 | + | |
21 | + | |
22 | +LL1 <- function(shape){ | |
23 | + | |
24 | + | |
25 | + R <- dbeta1(x, shape) | |
26 | + | |
27 | + | |
28 | + res <- -sum(log(R)) | |
29 | + | |
30 | + return(res) | |
31 | + | |
32 | + | |
33 | +} | |
34 | + | |
35 | + | |
36 | + | |
37 | + | |
38 | +LL2 <- function(shape){ | |
39 | + | |
40 | + | |
41 | + R <- dbeta2(x, shape) | |
42 | + | |
43 | + | |
44 | + res <- -sum(log(R)) | |
45 | + | |
46 | + return(res) | |
47 | + | |
48 | + | |
49 | +} | |
50 | + | |
51 | + | |
52 | + | |
53 | + | |
54 | +set.seed(124) | |
55 | + | |
56 | +x <-rbeta(1000, 0.2, 0.2) | |
57 | + | |
58 | + | |
59 | +fit_dbeta1 <- fitdistr( x , dbeta1, start=list(shape=0.5) , method="Brent", lower=c(0), upper=c(1)) | |
60 | + | |
61 | +print("estimate of shape from fit_dbeta1 is") | |
62 | +print(fit_dbeta1$estimate) | |
63 | + | |
64 | + | |
65 | + | |
66 | + | |
67 | +fit_dbeta2 <- fitdistr( x , dbeta2, start=list(shape=0.5) , method="Brent", lower=c(0), upper=c(1)) | |
68 | + | |
69 | +print("estimate of shape from fit_dbeta2 is") | |
70 | +print(fit_dbeta2$estimate) | |
71 | + | |
72 | + | |
73 | + | |
74 | +fit_LL1 <- mle(LL1, start=list(shape=0.5)) | |
75 | + | |
76 | +print("estimate of from fit_LL1") | |
77 | +print(coef(fit_LL1)) | |
78 | + | |
79 | + | |
80 | +## this does not work | |
81 | +fit_LL2 <- mle(LL2, start=list(shape=0.5)) | |
82 | +print(coef(fit_LL2)) | |
83 | + | |
84 | + | |
85 | + | |
86 | + | |
87 | +print("So far so good") |