Fitting parameter b of the Gamma distribution from mean, 95% in Python

白昼怎懂夜的黑 提交于 2020-01-15 10:13:09

问题


This Mathematica function finds parameter b of the Gamma distribution, given mean and 95% values and scaled by the mean [Mu]; The two values bracket [Beta] makes it fast and there is a restriction for max pg95= 5.8[Mu]* gb[[Mu], p95]. I need to translate this code into Python:

gb[\[Mu]_, p95_] := Block[{p = Min[p95/\[Mu], 5.8]},
\[Mu] FindRoot[CDF[GammaDistribution[1/\[Beta], \[Beta]], p] - .95 == 0,
  {\[Beta], 1, If[p == 1, 1.1, p]}][[1, 2]]];

回答1:


Even if you cannot find exactly equivalent gamma functions you ought to be able to translate gb with SciPy's integration and root finding functions. The functions required can be obtained, e.g. (illustrating with some demo values)

For example

As you can see, the code constructed from the more basic functions produces the same answer, albeit more slowly.

Code

gamma[z_] := \!\(
\*SubsuperscriptBox[\(\[Integral]\), \(0\), \(\[Infinity]\)]\(
\*SuperscriptBox[\(t\), \(z - 1\)] 
\*SuperscriptBox[\(E\), \(-t\)] \[DifferentialD]t\)\)
gamma[a_, z0_, z1_] := \!\(
\*SubsuperscriptBox[\(\[Integral]\), \(z0\), \(z1\)]\(
\*SuperscriptBox[\(t\), \(a - 1\)] 
\*SuperscriptBox[\(E\), \(-t\)] \[DifferentialD]t\)\)
gammaregularized[a_, z1_] := gamma[a, 0, z1]/gamma[a]
cdf[\[Beta]_, p_] := 
 Piecewise[{{gammaregularized[1/\[Beta], p/\[Beta]], p > 0}}]
p = 1.2;
FindRoot[cdf[\[Beta], p] - .95, {\[Beta], 1, If[p == 1, 1.1, p]}]
FindRoot[CDF[GammaDistribution[1/\[Beta], \[Beta]], 
   p] - .95, {\[Beta], 1, If[p == 1, 1.1, p]}]


来源:https://stackoverflow.com/questions/55168437/fitting-parameter-b-of-the-gamma-distribution-from-mean-95-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!