Quiero muestrear de acuerdo con una densidad
dondeyson estrictamente positivo. (Motivación: Esto podría ser útil para el muestreo de Gibbs cuando el parámetro de forma de una densidad Gamma tiene un previo uniforme).
¿Alguien sabe cómo tomar muestras de esta densidad fácilmente? ¿Tal vez es estándar y solo algo que no sé?
Se me ocurre un estúpido algoritmo de muestreo de rechazo que funcionará más o menos (encuentre el modo de , muestra de uniforme en una caja grande y rechazar si ), pero (i) no es del todo eficiente y (ii) será demasiado grande para que una computadora pueda manejarlo fácilmente incluso con y moderadamente grandes . (Tenga en cuenta que el modo para la gran y es aproximadamente a .)
¡Gracias de antemano por cualquier ayuda!
Respuestas:
El muestreo de rechazo funcionará excepcionalmente bien cuando y es razonable para c d ≥ exp ( 2 ) .cd≥exp(5) cd≥exp(2)
Para simplificar un poco las matemáticas, deje , escriba x = a , y observe quek=cd x=a
para . Configuración de x = u 3 / 2 dax≥1 x=u3/2
para . Cuando k ≥ exp ( 5 ) , esta distribución es extremadamente cercana a Normal (y se acerca a medida que k se hace más grande). Específicamente, puedesu≥1 k≥exp(5) k
Encuentre el modo de numéricamente (usando, por ejemplo, Newton-Raphson).f(u)
Expanda al segundo orden sobre su modo.logf(u)
Esto produce los parámetros de una distribución normal muy aproximada. Para una alta precisión, esta Normal aproximada domina excepto en las colas extremas. (Cuando k < exp ( 5 ) , es posible que deba escalar un poco el PDF normal para garantizar la dominación).f(u) k<exp(5)
Después de haber realizado este trabajo preliminar para cualquier valor dado de , y haber estimado una constante M > 1 (como se describe a continuación), obtener una variable aleatoria es una cuestión de:k M>1
Dibuje un valor de la distribución Normal dominante g ( u ) .u g(u)
Si o si una nueva variante uniforme X excede f ( uu<1 X , regrese al paso 1.f(u)/(Mg(u))
Conjunto .x=u3/2
El número esperado de evaluaciones de debido a las discrepancias entre g y f es sólo ligeramente mayor que 1. (Algunas evaluaciones adicionales se producirá debido a rechazos de variables aleatorias de menos de 1 , pero incluso cuando k es tan bajo como 2 la frecuencia de tales las ocurrencias son pequeñas)f g f 1 k 2
Este gráfico muestra los logaritmos de g y f como una función de u para . Debido a que los gráficos están tan cerca, necesitamos inspeccionar su relación para ver qué está pasando:k=exp(5)
Esto muestra la relación de ; se incluyó el factor de M = exp ( 0.004 ) para asegurar que el logaritmo sea positivo en toda la parte principal de la distribución; es decir, para asegurar M g ( u ) ≥ f ( u ), excepto posiblemente en regiones de probabilidad insignificante. Al hacer que M sea lo suficientemente grande, puede garantizar que M ⋅ glog(exp(0.004)g(u)/f(u)) M=exp(0.004) Mg(u)≥f(u) M M⋅g domina en todas las colas excepto en las más extremas (que prácticamente no tienen posibilidades de ser elegidas en una simulación de todos modos). Sin embargo, cuanto mayor sea M , más frecuentemente ocurrirán los rechazos. A medida que k crece, M puede elegirse muy cerca de 1 , lo que prácticamente no conlleva penalización.f M k M 1
Un enfoque similar funciona incluso para , pero pueden ser necesarios valores bastante grandes de M cuando exp ( 2 ) < k < exp ( 5 ) , porque f ( u ) es notablemente asimétrico. Por ejemplo, con k = exp ( 2 ) , para obtener una g razonablemente precisa , necesitamos establecer M = 1 :k>exp(2) M exp(2)<k<exp(5) f(u) k=exp(2) g M=1
La curva roja superior es el gráfico de mientras que la curva azul inferior es el gráfico de log ( f ( u ) ) . El muestreo de rechazo de f en relación con exp ( 1 ) g causará que se rechacen aproximadamente 2/3 de todos los sorteos de prueba, triplicando el esfuerzo: aún no está mal. La cola de la derecha ( T > 10 o x > 10 3 / 2 ~ 30log(exp(1)g(u)) log(f(u)) f exp(1)g u>10 x>103/2∼30 ) estará subrepresentada en el muestreo de rechazo (porque exp(1)g ya no domina allí), pero esa cola comprende menos de exp ( - 20 ) ∼ 10 - 9 de la probabilidad total.f exp(−20)∼10−9
To summarize, after an initial effort to compute the mode and evaluate the quadratic term of the power series off(u) around the mode--an effort that requires a few tens of function evaluations at most--you can use rejection sampling at an expected cost of between 1 and 3 (or so) evaluations per variate. The cost multiplier rapidly drops to 1 as k=cd increases beyond 5.
Even when just one draw fromf is needed, this method is reasonable. It comes into its own when many independent draws are needed for the same value of k , for then the overhead of the initial calculations is amortized over many draws.
Addendum
@Cardinal has asked, quite reasonably, for support of some of the hand-waving analysis in the forgoing. In particular, why should the transformationx=u3/2 make the distribution approximately Normal?
In light of the theory of Box-Cox transformations, it is natural to seek some power transformation of the formx=uα (for a constant α , hopefully not too different from unity) that will make a distribution "more" Normal. Recall that all Normal distributions are simply characterized: the logarithms of their pdfs are purely quadratic, with zero linear term and no higher order terms. Therefore we can take any pdf and compare it to a Normal distribution by expanding its logarithm as a power series around its (highest) peak. We seek a value of α that makes (at least) the third power vanish, at least approximately: that is the most we can reasonably hope that a single free coefficient will accomplish. Often this works well.
But how to get a handle on this particular distribution? Upon effecting the power transformation, its pdf is
Take its logarithm and use Stirling's asymptotic expansion oflog(Γ) :
(for small values ofc , which is not constant). This works provided α is positive, which we will assume to be the case (for otherwise we cannot neglect the remainder of the expansion).
Compute its third derivative (which, when divided by3! , will be the coefficient of the third power of u in the power series) and exploit the fact that at the peak, the first derivative must be zero. This simplifies the third derivative greatly, giving (approximately, because we are ignoring the derivative of c )
Whenk is not too small, u will indeed be large at the peak. Because α is positive, the dominant term in this expression is the 2α power, which we can set to zero by making its coefficient vanish:
That's whyα=3/2 works so well: with this choice, the coefficient of the cubic term around the peak behaves like u−3 , which is close to exp(−2k) . Once k exceeds 10 or so, you can practically forget about it, and it's reasonably small even for k down to 2. The higher powers, from the fourth on, play less and less of a role as k gets large, because their coefficients grow proportionately smaller, too. Incidentally, the same calculations (based on the second derivative of log(f(u)) at its peak) show the standard deviation of this Normal approximation is slightly less than 23exp(k/6) , with the error proportional to exp(−k/2) .
fuente
I like @whuber's answer very much; it's likely to be very efficient and has a beautiful analysis. But it requires some deep insight with respect to this particular distribution. For situations where you don't have that insight (so for different distributions), I also like the following approach which works for all distributions where the PDF is twice differentiable and that second derivative has finitely many roots. It requires quite a bit of work to set up, but then afterwards you have an engine that works for most distributions you can throw at it.
Basically, the idea is to use a piecewise linear upper bound to the PDF which you adapt as you are doing rejection sampling. At the same time you have a piecewise linear lower bound for the PDF which prevents you from having to evaluate the PDF too frequently. The upper and lower bounds are given by chords and tangents to the PDF graph. The initial division into intervals is such that on each interval, the PDF is either all concave or all convex; whenever you have to reject a point (x, y) you subdivide that interval at x. (You can also do an extra subdivision at x if you had to compute the PDF because the lower bound is really bad.) This makes the subdivisions occur especially frequently where the upper (and lower) bounds are bad, so you get a really good approximation of your PDF essentially for free. The details are a little tricky to get right, but I've tried to explain most of them in this series of blog posts - especially the last one.
Those posts don't discuss what to do if the PDF is unbounded either in domain or in values; I'd recommend the somewhat obvious solution of either doing a transformation that makes them finite (which would be hard to automate) or using a cutoff. I would choose the cutoff depending on the total number of points you expect to generate, say N, and choose the cutoff so that the removed part has less than1/(10N) probability. (This is easy enough if you have a closed form for the CDF; otherwise it might also be tricky.)
This method is implemented in Maple as the default method for user-defined continuous distributions. (Full disclosure - I work for Maplesoft.)
I did an example run, generating 10^4 points for c = 2, d = 3, specifying [1, 100] as the initial range for the values:
There were 23 rejections (in red), 51 points "on probation" which were at the time in between the lower bound and the actual PDF, and 9949 points which were accepted after checking only linear inequalities. That's 74 evaluations of the PDF in total, or about one PDF evaluation per 135 points. The ratio should get better as you generate more points, since the approximation gets better and better (and conversely, if you generate only few points, the ratio is worse).
fuente
You could do it by numerically executing the inversion method, which says that if you plug uniform(0,1) random variables in the inverse CDF, you get a draw from the distribution. I've included some R code below that does this, and from the few checks I've done, it is working well, but it is a bit sloppy and I'm sure you could optimize it.
If you're not familiar with R, lgamma() is the log of the gamma function; integrate() calculates a definite 1-D integral; uniroot() calculates a root of a function using 1-D bisection.
The main arbitrary thing I do here is assuming that(1,10000) is a sufficient bracket for the bisection - I was lazy about this and there might be a more efficient way to choose this bracket. For very large values, the numerical calculation of the CDF (say, >100000 ) fails, so the bracket must be below this. The CDF is effectively equal to 1 at those points (unless c,d are very large), so something could probably be included that would prevent miscalculation of the CDF for very large input values.
Edit: Whencd is very large, a numerical problem occurs with this method. As whuber points out in the comments, once this has occurred, the distribution is essentially degenerate at it's mode, making it a trivial sampling problem.
fuente