_fit.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. import warnings
  2. from collections import namedtuple
  3. import numpy as np
  4. from scipy import optimize, stats
  5. from scipy._lib._array_api import xp_capabilities
  6. from scipy._lib._util import check_random_state, _transition_to_rng
  7. def _combine_bounds(name, user_bounds, shape_domain, integral):
  8. """Intersection of user-defined bounds and distribution PDF/PMF domain"""
  9. user_bounds = np.atleast_1d(user_bounds)
  10. if user_bounds[0] > user_bounds[1]:
  11. message = (f"There are no values for `{name}` on the interval "
  12. f"{list(user_bounds)}.")
  13. raise ValueError(message)
  14. bounds = (max(user_bounds[0], shape_domain[0]),
  15. min(user_bounds[1], shape_domain[1]))
  16. if integral and (np.ceil(bounds[0]) > np.floor(bounds[1])):
  17. message = (f"There are no integer values for `{name}` on the interval "
  18. f"defined by the user-provided bounds and the domain "
  19. "of the distribution.")
  20. raise ValueError(message)
  21. elif not integral and (bounds[0] > bounds[1]):
  22. message = (f"There are no values for `{name}` on the interval "
  23. f"defined by the user-provided bounds and the domain "
  24. "of the distribution.")
  25. raise ValueError(message)
  26. if not np.all(np.isfinite(bounds)):
  27. message = (f"The intersection of user-provided bounds for `{name}` "
  28. f"and the domain of the distribution is not finite. Please "
  29. f"provide finite bounds for shape `{name}` in `bounds`.")
  30. raise ValueError(message)
  31. return bounds
  32. class FitResult:
  33. r"""Result of fitting a discrete or continuous distribution to data
  34. Attributes
  35. ----------
  36. params : namedtuple
  37. A namedtuple containing the maximum likelihood estimates of the
  38. shape parameters, location, and (if applicable) scale of the
  39. distribution.
  40. success : bool or None
  41. Whether the optimizer considered the optimization to terminate
  42. successfully or not.
  43. message : str or None
  44. Any status message provided by the optimizer.
  45. """
  46. def __init__(self, dist, data, discrete, res):
  47. self._dist = dist
  48. self._data = data
  49. self.discrete = discrete
  50. self.pxf = getattr(dist, "pmf", None) or getattr(dist, "pdf", None)
  51. shape_names = [] if dist.shapes is None else dist.shapes.split(", ")
  52. if not discrete:
  53. FitParams = namedtuple('FitParams', shape_names + ['loc', 'scale'])
  54. else:
  55. FitParams = namedtuple('FitParams', shape_names + ['loc'])
  56. self.params = FitParams(*res.x)
  57. # Optimizer can report success even when nllf is infinite
  58. if res.success and not np.isfinite(self.nllf()):
  59. res.success = False
  60. res.message = ("Optimization converged to parameter values that "
  61. "are inconsistent with the data.")
  62. self.success = getattr(res, "success", None)
  63. self.message = getattr(res, "message", None)
  64. def __repr__(self):
  65. keys = ["params", "success", "message"]
  66. m = max(map(len, keys)) + 1
  67. return '\n'.join([key.rjust(m) + ': ' + repr(getattr(self, key))
  68. for key in keys if getattr(self, key) is not None])
  69. def nllf(self, params=None, data=None):
  70. """Negative log-likelihood function
  71. Evaluates the negative of the log-likelihood function of the provided
  72. data at the provided parameters.
  73. Parameters
  74. ----------
  75. params : tuple, optional
  76. The shape parameters, location, and (if applicable) scale of the
  77. distribution as a single tuple. Default is the maximum likelihood
  78. estimates (``self.params``).
  79. data : array_like, optional
  80. The data for which the log-likelihood function is to be evaluated.
  81. Default is the data to which the distribution was fit.
  82. Returns
  83. -------
  84. nllf : float
  85. The negative of the log-likelihood function.
  86. """
  87. params = params if params is not None else self.params
  88. data = data if data is not None else self._data
  89. return self._dist.nnlf(theta=params, x=data)
  90. def plot(self, ax=None, *, plot_type="hist"):
  91. """Visually compare the data against the fitted distribution.
  92. Available only if `matplotlib` is installed.
  93. Parameters
  94. ----------
  95. ax : `matplotlib.axes.Axes`
  96. Axes object to draw the plot onto, otherwise uses the current Axes.
  97. plot_type : {"hist", "qq", "pp", "cdf"}
  98. Type of plot to draw. Options include:
  99. - "hist": Superposes the PDF/PMF of the fitted distribution
  100. over a normalized histogram of the data.
  101. - "qq": Scatter plot of theoretical quantiles against the
  102. empirical quantiles. Specifically, the x-coordinates are the
  103. values of the fitted distribution PPF evaluated at the
  104. percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is the
  105. number of data points, and the y-coordinates are the sorted
  106. data points.
  107. - "pp": Scatter plot of theoretical percentiles against the
  108. observed percentiles. Specifically, the x-coordinates are the
  109. percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
  110. the number of data points, and the y-coordinates are the values
  111. of the fitted distribution CDF evaluated at the sorted
  112. data points.
  113. - "cdf": Superposes the CDF of the fitted distribution over the
  114. empirical CDF. Specifically, the x-coordinates of the empirical
  115. CDF are the sorted data points, and the y-coordinates are the
  116. percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
  117. the number of data points.
  118. Returns
  119. -------
  120. ax : `matplotlib.axes.Axes`
  121. The matplotlib Axes object on which the plot was drawn.
  122. Examples
  123. --------
  124. >>> import numpy as np
  125. >>> from scipy import stats
  126. >>> import matplotlib.pyplot as plt # matplotlib must be installed
  127. >>> rng = np.random.default_rng()
  128. >>> data = stats.nbinom(5, 0.5).rvs(size=1000, random_state=rng)
  129. >>> bounds = [(0, 30), (0, 1)]
  130. >>> res = stats.fit(stats.nbinom, data, bounds)
  131. >>> ax = res.plot() # save matplotlib Axes object
  132. The `matplotlib.axes.Axes` object can be used to customize the plot.
  133. See `matplotlib.axes.Axes` documentation for details.
  134. >>> ax.set_xlabel('number of trials') # customize axis label
  135. >>> ax.get_children()[0].set_linewidth(5) # customize line widths
  136. >>> ax.legend()
  137. >>> plt.show()
  138. """
  139. try:
  140. import matplotlib # noqa: F401
  141. except ModuleNotFoundError as exc:
  142. message = "matplotlib must be installed to use method `plot`."
  143. raise ModuleNotFoundError(message) from exc
  144. plots = {'histogram': self._hist_plot, 'qq': self._qq_plot,
  145. 'pp': self._pp_plot, 'cdf': self._cdf_plot,
  146. 'hist': self._hist_plot}
  147. if plot_type.lower() not in plots:
  148. message = f"`plot_type` must be one of {set(plots.keys())}"
  149. raise ValueError(message)
  150. plot = plots[plot_type.lower()]
  151. if ax is None:
  152. import matplotlib.pyplot as plt
  153. ax = plt.gca()
  154. fit_params = np.atleast_1d(self.params)
  155. return plot(ax=ax, fit_params=fit_params)
  156. def _hist_plot(self, ax, fit_params):
  157. from matplotlib.ticker import MaxNLocator
  158. support = self._dist.support(*fit_params)
  159. lb = support[0] if np.isfinite(support[0]) else min(self._data)
  160. ub = support[1] if np.isfinite(support[1]) else max(self._data)
  161. pxf = "PMF" if self.discrete else "PDF"
  162. if self.discrete:
  163. x = np.arange(lb, ub + 2)
  164. y = self.pxf(x, *fit_params)
  165. ax.vlines(x[:-1], 0, y[:-1], label='Fitted Distribution PMF',
  166. color='C0')
  167. options = dict(density=True, bins=x, align='left', color='C1')
  168. ax.xaxis.set_major_locator(MaxNLocator(integer=True))
  169. ax.set_xlabel('k')
  170. ax.set_ylabel('PMF')
  171. else:
  172. x = np.linspace(lb, ub, 200)
  173. y = self.pxf(x, *fit_params)
  174. ax.plot(x, y, '--', label='Fitted Distribution PDF', color='C0')
  175. options = dict(density=True, bins=50, align='mid', color='C1')
  176. ax.set_xlabel('x')
  177. ax.set_ylabel('PDF')
  178. if len(self._data) > 50 or self.discrete:
  179. ax.hist(self._data, label="Histogram of Data", **options)
  180. else:
  181. ax.plot(self._data, np.zeros_like(self._data), "*",
  182. label='Data', color='C1')
  183. ax.set_title(rf"Fitted $\tt {self._dist.name}$ {pxf} and Histogram")
  184. ax.legend(*ax.get_legend_handles_labels())
  185. return ax
  186. def _qp_plot(self, ax, fit_params, qq):
  187. data = np.sort(self._data)
  188. ps = self._plotting_positions(len(self._data))
  189. if qq:
  190. qp = "Quantiles"
  191. plot_type = 'Q-Q'
  192. x = self._dist.ppf(ps, *fit_params)
  193. y = data
  194. else:
  195. qp = "Percentiles"
  196. plot_type = 'P-P'
  197. x = ps
  198. y = self._dist.cdf(data, *fit_params)
  199. ax.plot(x, y, '.', label=f'Fitted Distribution {plot_type}',
  200. color='C0', zorder=1)
  201. xlim = ax.get_xlim()
  202. ylim = ax.get_ylim()
  203. lim = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])]
  204. if not qq:
  205. lim = max(lim[0], 0), min(lim[1], 1)
  206. if self.discrete and qq:
  207. q_min, q_max = int(lim[0]), int(lim[1]+1)
  208. q_ideal = np.arange(q_min, q_max)
  209. # q_ideal = np.unique(self._dist.ppf(ps, *fit_params))
  210. ax.plot(q_ideal, q_ideal, 'o', label='Reference', color='k',
  211. alpha=0.25, markerfacecolor='none', clip_on=True)
  212. elif self.discrete and not qq:
  213. # The intent of this is to match the plot that would be produced
  214. # if x were continuous on [0, 1] and y were cdf(ppf(x)).
  215. # It can be approximated by letting x = np.linspace(0, 1, 1000),
  216. # but this might not look great when zooming in. The vertical
  217. # portions are included to indicate where the transition occurs
  218. # where the data completely obscures the horizontal portions.
  219. p_min, p_max = lim
  220. a, b = self._dist.support(*fit_params)
  221. p_min = max(p_min, 0 if np.isfinite(a) else 1e-3)
  222. p_max = min(p_max, 1 if np.isfinite(b) else 1-1e-3)
  223. q_min, q_max = self._dist.ppf([p_min, p_max], *fit_params)
  224. qs = np.arange(q_min-1, q_max+1)
  225. ps = self._dist.cdf(qs, *fit_params)
  226. ax.step(ps, ps, '-', label='Reference', color='k', alpha=0.25,
  227. clip_on=True)
  228. else:
  229. ax.plot(lim, lim, '-', label='Reference', color='k', alpha=0.25,
  230. clip_on=True)
  231. ax.set_xlim(lim)
  232. ax.set_ylim(lim)
  233. ax.set_xlabel(rf"Fitted $\tt {self._dist.name}$ Theoretical {qp}")
  234. ax.set_ylabel(f"Data {qp}")
  235. ax.set_title(rf"Fitted $\tt {self._dist.name}$ {plot_type} Plot")
  236. ax.legend(*ax.get_legend_handles_labels())
  237. ax.set_aspect('equal')
  238. return ax
  239. def _qq_plot(self, **kwargs):
  240. return self._qp_plot(qq=True, **kwargs)
  241. def _pp_plot(self, **kwargs):
  242. return self._qp_plot(qq=False, **kwargs)
  243. def _plotting_positions(self, n, a=.5):
  244. # See https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot#Plotting_positions
  245. k = np.arange(1, n+1)
  246. return (k-a) / (n + 1 - 2*a)
  247. def _cdf_plot(self, ax, fit_params):
  248. data = np.sort(self._data)
  249. ecdf = self._plotting_positions(len(self._data))
  250. ls = '--' if len(np.unique(data)) < 30 else '.'
  251. xlabel = 'k' if self.discrete else 'x'
  252. ax.step(data, ecdf, ls, label='Empirical CDF', color='C1', zorder=0)
  253. xlim = ax.get_xlim()
  254. q = np.linspace(*xlim, 300)
  255. tcdf = self._dist.cdf(q, *fit_params)
  256. ax.plot(q, tcdf, label='Fitted Distribution CDF', color='C0', zorder=1)
  257. ax.set_xlim(xlim)
  258. ax.set_ylim(0, 1)
  259. ax.set_xlabel(xlabel)
  260. ax.set_ylabel("CDF")
  261. ax.set_title(rf"Fitted $\tt {self._dist.name}$ and Empirical CDF")
  262. handles, labels = ax.get_legend_handles_labels()
  263. ax.legend(handles[::-1], labels[::-1])
  264. return ax
  265. @xp_capabilities(out_of_scope=True)
  266. def fit(dist, data, bounds=None, *, guess=None, method='mle',
  267. optimizer=optimize.differential_evolution):
  268. r"""Fit a discrete or continuous distribution to data
  269. Given a distribution, data, and bounds on the parameters of the
  270. distribution, return maximum likelihood estimates of the parameters.
  271. Parameters
  272. ----------
  273. dist : `scipy.stats.rv_continuous` or `scipy.stats.rv_discrete`
  274. The object representing the distribution to be fit to the data.
  275. data : 1D array_like
  276. The data to which the distribution is to be fit. If the data contain
  277. any of ``np.nan``, ``np.inf``, or -``np.inf``, the fit method will
  278. raise a ``ValueError``.
  279. bounds : dict or sequence of tuples, optional
  280. If a dictionary, each key is the name of a parameter of the
  281. distribution, and the corresponding value is a tuple containing the
  282. lower and upper bound on that parameter. If the distribution is
  283. defined only for a finite range of values of that parameter, no entry
  284. for that parameter is required; e.g., some distributions have
  285. parameters which must be on the interval [0, 1]. Bounds for parameters
  286. location (``loc``) and scale (``scale``) are optional; by default,
  287. they are fixed to 0 and 1, respectively.
  288. If a sequence, element *i* is a tuple containing the lower and upper
  289. bound on the *i*\ th parameter of the distribution. In this case,
  290. bounds for *all* distribution shape parameters must be provided.
  291. Optionally, bounds for location and scale may follow the
  292. distribution shape parameters.
  293. If a shape is to be held fixed (e.g. if it is known), the
  294. lower and upper bounds may be equal. If a user-provided lower or upper
  295. bound is beyond a bound of the domain for which the distribution is
  296. defined, the bound of the distribution's domain will replace the
  297. user-provided value. Similarly, parameters which must be integral
  298. will be constrained to integral values within the user-provided bounds.
  299. guess : dict or array_like, optional
  300. If a dictionary, each key is the name of a parameter of the
  301. distribution, and the corresponding value is a guess for the value
  302. of the parameter.
  303. If a sequence, element *i* is a guess for the *i*\ th parameter of the
  304. distribution. In this case, guesses for *all* distribution shape
  305. parameters must be provided.
  306. If `guess` is not provided, guesses for the decision variables will
  307. not be passed to the optimizer. If `guess` is provided, guesses for
  308. any missing parameters will be set at the mean of the lower and
  309. upper bounds. Guesses for parameters which must be integral will be
  310. rounded to integral values, and guesses that lie outside the
  311. intersection of the user-provided bounds and the domain of the
  312. distribution will be clipped.
  313. method : {'mle', 'mse'}
  314. With ``method="mle"`` (default), the fit is computed by minimizing
  315. the negative log-likelihood function. A large, finite penalty
  316. (rather than infinite negative log-likelihood) is applied for
  317. observations beyond the support of the distribution.
  318. With ``method="mse"``, the fit is computed by minimizing
  319. the negative log-product spacing function. The same penalty is applied
  320. for observations beyond the support. We follow the approach of [1]_,
  321. which is generalized for samples with repeated observations.
  322. optimizer : callable, optional
  323. `optimizer` is a callable that accepts the following positional
  324. argument.
  325. fun : callable
  326. The objective function to be optimized. `fun` accepts one argument
  327. ``x``, candidate shape parameters of the distribution, and returns
  328. the objective function value given ``x``, `dist`, and the provided
  329. `data`.
  330. The job of `optimizer` is to find values of the decision variables
  331. that minimizes `fun`.
  332. `optimizer` must also accept the following keyword argument.
  333. bounds : sequence of tuples
  334. The bounds on values of the decision variables; each element will
  335. be a tuple containing the lower and upper bound on a decision
  336. variable.
  337. If `guess` is provided, `optimizer` must also accept the following
  338. keyword argument.
  339. x0 : array_like
  340. The guesses for each decision variable.
  341. If the distribution has any shape parameters that must be integral or
  342. if the distribution is discrete and the location parameter is not
  343. fixed, `optimizer` must also accept the following keyword argument.
  344. integrality : array_like of bools
  345. For each decision variable, True if the decision variable
  346. must be constrained to integer values and False if the decision
  347. variable is continuous.
  348. `optimizer` must return an object, such as an instance of
  349. `scipy.optimize.OptimizeResult`, which holds the optimal values of
  350. the decision variables in an attribute ``x``. If attributes
  351. ``fun``, ``status``, or ``message`` are provided, they will be
  352. included in the result object returned by `fit`.
  353. Returns
  354. -------
  355. result : `~scipy.stats._result_classes.FitResult`
  356. An object with the following fields.
  357. params : namedtuple
  358. A namedtuple containing the maximum likelihood estimates of the
  359. shape parameters, location, and (if applicable) scale of the
  360. distribution.
  361. success : bool or None
  362. Whether the optimizer considered the optimization to terminate
  363. successfully or not.
  364. message : str or None
  365. Any status message provided by the optimizer.
  366. The object has the following method:
  367. nllf(params=None, data=None)
  368. By default, the negative log-likelihood function at the fitted
  369. `params` for the given `data`. Accepts a tuple containing
  370. alternative shapes, location, and scale of the distribution and
  371. an array of alternative data.
  372. plot(ax=None)
  373. Superposes the PDF/PMF of the fitted distribution over a normalized
  374. histogram of the data.
  375. See Also
  376. --------
  377. rv_continuous, rv_discrete
  378. Notes
  379. -----
  380. Optimization is more likely to converge to the maximum likelihood estimate
  381. when the user provides tight bounds containing the maximum likelihood
  382. estimate. For example, when fitting a binomial distribution to data, the
  383. number of experiments underlying each sample may be known, in which case
  384. the corresponding shape parameter ``n`` can be fixed.
  385. References
  386. ----------
  387. .. [1] Shao, Yongzhao, and Marjorie G. Hahn. "Maximum product of spacings
  388. method: a unified formulation with illustration of strong
  389. consistency." Illinois Journal of Mathematics 43.3 (1999): 489-499.
  390. Examples
  391. --------
  392. Suppose we wish to fit a distribution to the following data.
  393. >>> import numpy as np
  394. >>> from scipy import stats
  395. >>> rng = np.random.default_rng()
  396. >>> dist = stats.nbinom
  397. >>> shapes = (5, 0.5)
  398. >>> data = dist.rvs(*shapes, size=1000, random_state=rng)
  399. Suppose we do not know how the data were generated, but we suspect that
  400. it follows a negative binomial distribution with parameters *n* and *p*\.
  401. (See `scipy.stats.nbinom`.) We believe that the parameter *n* was fewer
  402. than 30, and we know that the parameter *p* must lie on the interval
  403. [0, 1]. We record this information in a variable `bounds` and pass
  404. this information to `fit`.
  405. >>> bounds = [(0, 30), (0, 1)]
  406. >>> res = stats.fit(dist, data, bounds)
  407. `fit` searches within the user-specified `bounds` for the
  408. values that best match the data (in the sense of maximum likelihood
  409. estimation). In this case, it found shape values similar to those
  410. from which the data were actually generated.
  411. >>> res.params
  412. FitParams(n=5.0, p=0.5028157644634368, loc=0.0) # may vary
  413. We can visualize the results by superposing the probability mass function
  414. of the distribution (with the shapes fit to the data) over a normalized
  415. histogram of the data.
  416. >>> import matplotlib.pyplot as plt # matplotlib must be installed to plot
  417. >>> res.plot()
  418. >>> plt.show()
  419. Note that the estimate for *n* was exactly integral; this is because
  420. the domain of the `nbinom` PMF includes only integral *n*, and the `nbinom`
  421. object "knows" that. `nbinom` also knows that the shape *p* must be a
  422. value between 0 and 1. In such a case - when the domain of the distribution
  423. with respect to a parameter is finite - we are not required to specify
  424. bounds for the parameter.
  425. >>> bounds = {'n': (0, 30)} # omit parameter p using a `dict`
  426. >>> res2 = stats.fit(dist, data, bounds)
  427. >>> res2.params
  428. FitParams(n=5.0, p=0.5016492009232932, loc=0.0) # may vary
  429. If we wish to force the distribution to be fit with *n* fixed at 6, we can
  430. set both the lower and upper bounds on *n* to 6. Note, however, that the
  431. value of the objective function being optimized is typically worse (higher)
  432. in this case.
  433. >>> bounds = {'n': (6, 6)} # fix parameter `n`
  434. >>> res3 = stats.fit(dist, data, bounds)
  435. >>> res3.params
  436. FitParams(n=6.0, p=0.5486556076755706, loc=0.0) # may vary
  437. >>> res3.nllf() > res.nllf()
  438. True # may vary
  439. Note that the numerical results of the previous examples are typical, but
  440. they may vary because the default optimizer used by `fit`,
  441. `scipy.optimize.differential_evolution`, is stochastic. However, we can
  442. customize the settings used by the optimizer to ensure reproducibility -
  443. or even use a different optimizer entirely - using the `optimizer`
  444. parameter.
  445. >>> from scipy.optimize import differential_evolution
  446. >>> rng = np.random.default_rng(767585560716548)
  447. >>> def optimizer(fun, bounds, *, integrality):
  448. ... return differential_evolution(fun, bounds, strategy='best2bin',
  449. ... rng=rng, integrality=integrality)
  450. >>> bounds = [(0, 30), (0, 1)]
  451. >>> res4 = stats.fit(dist, data, bounds, optimizer=optimizer)
  452. >>> res4.params
  453. FitParams(n=5.0, p=0.5015183149259951, loc=0.0)
  454. """
  455. # --- Input Validation / Standardization --- #
  456. user_bounds = bounds
  457. user_guess = guess
  458. # distribution input validation and information collection
  459. if hasattr(dist, "pdf"): # can't use isinstance for types
  460. default_bounds = {'loc': (0, 0), 'scale': (1, 1)}
  461. discrete = False
  462. elif hasattr(dist, "pmf"):
  463. default_bounds = {'loc': (0, 0)}
  464. discrete = True
  465. else:
  466. message = ("`dist` must be an instance of `rv_continuous` "
  467. "or `rv_discrete.`")
  468. raise ValueError(message)
  469. try:
  470. param_info = dist._param_info()
  471. except AttributeError as e:
  472. message = (f"Distribution `{dist.name}` is not yet supported by "
  473. "`scipy.stats.fit` because shape information has "
  474. "not been defined.")
  475. raise ValueError(message) from e
  476. # data input validation
  477. data = np.asarray(data)
  478. if data.ndim != 1:
  479. message = "`data` must be exactly one-dimensional."
  480. raise ValueError(message)
  481. if not (np.issubdtype(data.dtype, np.number)
  482. and np.all(np.isfinite(data))):
  483. message = "All elements of `data` must be finite numbers."
  484. raise ValueError(message)
  485. # bounds input validation and information collection
  486. n_params = len(param_info)
  487. n_shapes = n_params - (1 if discrete else 2)
  488. param_list = [param.name for param in param_info]
  489. param_names = ", ".join(param_list)
  490. shape_names = ", ".join(param_list[:n_shapes])
  491. if user_bounds is None:
  492. user_bounds = {}
  493. if isinstance(user_bounds, dict):
  494. default_bounds.update(user_bounds)
  495. user_bounds = default_bounds
  496. user_bounds_array = np.empty((n_params, 2))
  497. for i in range(n_params):
  498. param_name = param_info[i].name
  499. user_bound = user_bounds.pop(param_name, None)
  500. if user_bound is None:
  501. user_bound = param_info[i].domain
  502. user_bounds_array[i] = user_bound
  503. if user_bounds:
  504. message = ("Bounds provided for the following unrecognized "
  505. f"parameters will be ignored: {set(user_bounds)}")
  506. warnings.warn(message, RuntimeWarning, stacklevel=2)
  507. else:
  508. try:
  509. user_bounds = np.asarray(user_bounds, dtype=float)
  510. if user_bounds.size == 0:
  511. user_bounds = np.empty((0, 2))
  512. except ValueError as e:
  513. message = ("Each element of a `bounds` sequence must be a tuple "
  514. "containing two elements: the lower and upper bound of "
  515. "a distribution parameter.")
  516. raise ValueError(message) from e
  517. if (user_bounds.ndim != 2 or user_bounds.shape[1] != 2):
  518. message = ("Each element of `bounds` must be a tuple specifying "
  519. "the lower and upper bounds of a shape parameter")
  520. raise ValueError(message)
  521. if user_bounds.shape[0] < n_shapes:
  522. message = (f"A `bounds` sequence must contain at least {n_shapes} "
  523. "elements: tuples specifying the lower and upper "
  524. f"bounds of all shape parameters {shape_names}.")
  525. raise ValueError(message)
  526. if user_bounds.shape[0] > n_params:
  527. message = ("A `bounds` sequence may not contain more than "
  528. f"{n_params} elements: tuples specifying the lower and "
  529. "upper bounds of distribution parameters "
  530. f"{param_names}.")
  531. raise ValueError(message)
  532. user_bounds_array = np.empty((n_params, 2))
  533. user_bounds_array[n_shapes:] = list(default_bounds.values())
  534. user_bounds_array[:len(user_bounds)] = user_bounds
  535. user_bounds = user_bounds_array
  536. validated_bounds = []
  537. for i in range(n_params):
  538. name = param_info[i].name
  539. user_bound = user_bounds_array[i]
  540. param_domain = param_info[i].domain
  541. integral = param_info[i].integrality
  542. combined = _combine_bounds(name, user_bound, param_domain, integral)
  543. validated_bounds.append(combined)
  544. bounds = np.asarray(validated_bounds)
  545. integrality = [param.integrality for param in param_info]
  546. # guess input validation
  547. if user_guess is None:
  548. guess_array = None
  549. elif isinstance(user_guess, dict):
  550. default_guess = {param.name: np.mean(bound)
  551. for param, bound in zip(param_info, bounds)}
  552. unrecognized = set(user_guess) - set(default_guess)
  553. if unrecognized:
  554. message = ("Guesses provided for the following unrecognized "
  555. f"parameters will be ignored: {unrecognized}")
  556. warnings.warn(message, RuntimeWarning, stacklevel=2)
  557. default_guess.update(user_guess)
  558. message = ("Each element of `guess` must be a scalar "
  559. "guess for a distribution parameter.")
  560. try:
  561. guess_array = np.asarray([default_guess[param.name]
  562. for param in param_info], dtype=float)
  563. except ValueError as e:
  564. raise ValueError(message) from e
  565. else:
  566. message = ("Each element of `guess` must be a scalar "
  567. "guess for a distribution parameter.")
  568. try:
  569. user_guess = np.asarray(user_guess, dtype=float)
  570. except ValueError as e:
  571. raise ValueError(message) from e
  572. if user_guess.ndim != 1:
  573. raise ValueError(message)
  574. if user_guess.shape[0] < n_shapes:
  575. message = (f"A `guess` sequence must contain at least {n_shapes} "
  576. "elements: scalar guesses for the distribution shape "
  577. f"parameters {shape_names}.")
  578. raise ValueError(message)
  579. if user_guess.shape[0] > n_params:
  580. message = ("A `guess` sequence may not contain more than "
  581. f"{n_params} elements: scalar guesses for the "
  582. f"distribution parameters {param_names}.")
  583. raise ValueError(message)
  584. guess_array = np.mean(bounds, axis=1)
  585. guess_array[:len(user_guess)] = user_guess
  586. if guess_array is not None:
  587. guess_rounded = guess_array.copy()
  588. guess_rounded[integrality] = np.round(guess_rounded[integrality])
  589. rounded = np.where(guess_rounded != guess_array)[0]
  590. for i in rounded:
  591. message = (f"Guess for parameter `{param_info[i].name}` "
  592. f"rounded from {guess_array[i]} to {guess_rounded[i]}.")
  593. warnings.warn(message, RuntimeWarning, stacklevel=2)
  594. guess_clipped = np.clip(guess_rounded, bounds[:, 0], bounds[:, 1])
  595. clipped = np.where(guess_clipped != guess_rounded)[0]
  596. for i in clipped:
  597. message = (f"Guess for parameter `{param_info[i].name}` "
  598. f"clipped from {guess_rounded[i]} to "
  599. f"{guess_clipped[i]}.")
  600. warnings.warn(message, RuntimeWarning, stacklevel=2)
  601. guess = guess_clipped
  602. else:
  603. guess = None
  604. # --- Fitting --- #
  605. def nllf(free_params, data=data): # bind data NOW
  606. with np.errstate(invalid='ignore', divide='ignore'):
  607. return dist._penalized_nnlf(free_params, data)
  608. def nlpsf(free_params, data=data): # bind data NOW
  609. with np.errstate(invalid='ignore', divide='ignore'):
  610. return dist._penalized_nlpsf(free_params, data)
  611. methods = {'mle': nllf, 'mse': nlpsf}
  612. objective = methods[method.lower()]
  613. with np.errstate(invalid='ignore', divide='ignore'):
  614. kwds = {}
  615. if bounds is not None:
  616. kwds['bounds'] = bounds
  617. if np.any(integrality):
  618. kwds['integrality'] = integrality
  619. if guess is not None:
  620. kwds['x0'] = guess
  621. res = optimizer(objective, **kwds)
  622. return FitResult(dist, data, discrete, res)
  623. GoodnessOfFitResult = namedtuple('GoodnessOfFitResult',
  624. ('fit_result', 'statistic', 'pvalue',
  625. 'null_distribution'))
  626. @xp_capabilities(out_of_scope=True)
  627. @_transition_to_rng('random_state')
  628. def goodness_of_fit(dist, data, *, known_params=None, fit_params=None,
  629. guessed_params=None, statistic='ad', n_mc_samples=9999,
  630. rng=None):
  631. r"""
  632. Perform a goodness of fit test comparing data to a distribution family.
  633. Given a distribution family and data, perform a test of the null hypothesis
  634. that the data were drawn from a distribution in that family. Any known
  635. parameters of the distribution may be specified. Remaining parameters of
  636. the distribution will be fit to the data, and the p-value of the test
  637. is computed accordingly. Several statistics for comparing the distribution
  638. to data are available.
  639. Parameters
  640. ----------
  641. dist : `scipy.stats.rv_continuous`
  642. The object representing the distribution family under the null
  643. hypothesis.
  644. data : 1D array_like
  645. Finite, uncensored data to be tested.
  646. known_params : dict, optional
  647. A dictionary containing name-value pairs of known distribution
  648. parameters. Monte Carlo samples are randomly drawn from the
  649. null-hypothesized distribution with these values of the parameters.
  650. Before the statistic is evaluated for the observed `data` and each
  651. Monte Carlo sample, only remaining unknown parameters of the
  652. null-hypothesized distribution family are fit to the samples; the
  653. known parameters are held fixed. If all parameters of the distribution
  654. family are known, then the step of fitting the distribution family to
  655. each sample is omitted.
  656. fit_params : dict, optional
  657. A dictionary containing name-value pairs of distribution parameters
  658. that have already been fit to the data, e.g. using `scipy.stats.fit`
  659. or the ``fit`` method of `dist`. Monte Carlo samples are drawn from the
  660. null-hypothesized distribution with these specified values of the
  661. parameter. However, these and all other unknown parameters of the
  662. null-hypothesized distribution family are always fit to the sample,
  663. whether that is the observed `data` or a Monte Carlo sample, before
  664. the statistic is evaluated.
  665. guessed_params : dict, optional
  666. A dictionary containing name-value pairs of distribution parameters
  667. which have been guessed. These parameters are always considered as
  668. free parameters and are fit both to the provided `data` as well as
  669. to the Monte Carlo samples drawn from the null-hypothesized
  670. distribution. The purpose of these `guessed_params` is to be used as
  671. initial values for the numerical fitting procedure.
  672. statistic : {"ad", "ks", "cvm", "filliben"} or callable, optional
  673. The statistic used to compare data to a distribution after fitting
  674. unknown parameters of the distribution family to the data. The
  675. Anderson-Darling ("ad") [1]_, Kolmogorov-Smirnov ("ks") [1]_,
  676. Cramer-von Mises ("cvm") [1]_, and Filliben ("filliben") [7]_
  677. statistics are available. Alternatively, a callable with signature
  678. ``(dist, data, axis)`` may be supplied to compute the statistic. Here
  679. ``dist`` is a frozen distribution object (potentially with array
  680. parameters), ``data`` is an array of Monte Carlo samples (of
  681. compatible shape), and ``axis`` is the axis of ``data`` along which
  682. the statistic must be computed.
  683. n_mc_samples : int, default: 9999
  684. The number of Monte Carlo samples drawn from the null hypothesized
  685. distribution to form the null distribution of the statistic. The
  686. sample size of each is the same as the given `data`.
  687. rng : `numpy.random.Generator`, optional
  688. Pseudorandom number generator state. When `rng` is None, a new
  689. `numpy.random.Generator` is created using entropy from the
  690. operating system. Types other than `numpy.random.Generator` are
  691. passed to `numpy.random.default_rng` to instantiate a ``Generator``.
  692. Returns
  693. -------
  694. res : GoodnessOfFitResult
  695. An object with the following attributes.
  696. fit_result : `~scipy.stats._result_classes.FitResult`
  697. An object representing the fit of the provided `dist` to `data`.
  698. This object includes the values of distribution family parameters
  699. that fully define the null-hypothesized distribution, that is,
  700. the distribution from which Monte Carlo samples are drawn.
  701. statistic : float
  702. The value of the statistic comparing provided `data` to the
  703. null-hypothesized distribution.
  704. pvalue : float
  705. The proportion of elements in the null distribution with
  706. statistic values at least as extreme as the statistic value of the
  707. provided `data`.
  708. null_distribution : ndarray
  709. The value of the statistic for each Monte Carlo sample
  710. drawn from the null-hypothesized distribution.
  711. Notes
  712. -----
  713. This is a generalized Monte Carlo goodness-of-fit procedure, special cases
  714. of which correspond with various Anderson-Darling tests, Lilliefors' test,
  715. etc. The test is described in [2]_, [3]_, and [4]_ as a parametric
  716. bootstrap test. This is a Monte Carlo test in which parameters that
  717. specify the distribution from which samples are drawn have been estimated
  718. from the data. We describe the test using "Monte Carlo" rather than
  719. "parametric bootstrap" throughout to avoid confusion with the more familiar
  720. nonparametric bootstrap, and describe how the test is performed below.
  721. *Traditional goodness of fit tests*
  722. Traditionally, critical values corresponding with a fixed set of
  723. significance levels are pre-calculated using Monte Carlo methods. Users
  724. perform the test by calculating the value of the test statistic only for
  725. their observed `data` and comparing this value to tabulated critical
  726. values. This practice is not very flexible, as tables are not available for
  727. all distributions and combinations of known and unknown parameter values.
  728. Also, results can be inaccurate when critical values are interpolated from
  729. limited tabulated data to correspond with the user's sample size and
  730. fitted parameter values. To overcome these shortcomings, this function
  731. allows the user to perform the Monte Carlo trials adapted to their
  732. particular data.
  733. *Algorithmic overview*
  734. In brief, this routine executes the following steps:
  735. 1. Fit unknown parameters to the given `data`, thereby forming the
  736. "null-hypothesized" distribution, and compute the statistic of
  737. this pair of data and distribution.
  738. 2. Draw random samples from this null-hypothesized distribution.
  739. 3. Fit the unknown parameters to each random sample.
  740. 4. Calculate the statistic between each sample and the distribution that
  741. has been fit to the sample.
  742. 5. Compare the value of the statistic corresponding with `data` from (1)
  743. against the values of the statistic corresponding with the random
  744. samples from (4). The p-value is the proportion of samples with a
  745. statistic value greater than or equal to the statistic of the observed
  746. data.
  747. In more detail, the steps are as follows.
  748. First, any unknown parameters of the distribution family specified by
  749. `dist` are fit to the provided `data` using maximum likelihood estimation.
  750. (One exception is the normal distribution with unknown location and scale:
  751. we use the bias-corrected standard deviation ``np.std(data, ddof=1)`` for
  752. the scale as recommended in [1]_.)
  753. These values of the parameters specify a particular member of the
  754. distribution family referred to as the "null-hypothesized distribution",
  755. that is, the distribution from which the data were sampled under the null
  756. hypothesis. The `statistic`, which compares data to a distribution, is
  757. computed between `data` and the null-hypothesized distribution.
  758. Next, many (specifically `n_mc_samples`) new samples, each containing the
  759. same number of observations as `data`, are drawn from the
  760. null-hypothesized distribution. All unknown parameters of the distribution
  761. family `dist` are fit to *each resample*, and the `statistic` is computed
  762. between each sample and its corresponding fitted distribution. These
  763. values of the statistic form the Monte Carlo null distribution (not to be
  764. confused with the "null-hypothesized distribution" above).
  765. The p-value of the test is the proportion of statistic values in the Monte
  766. Carlo null distribution that are at least as extreme as the statistic value
  767. of the provided `data`. More precisely, the p-value is given by
  768. .. math::
  769. p = \frac{b + 1}
  770. {m + 1}
  771. where :math:`b` is the number of statistic values in the Monte Carlo null
  772. distribution that are greater than or equal to the statistic value
  773. calculated for `data`, and :math:`m` is the number of elements in the
  774. Monte Carlo null distribution (`n_mc_samples`). The addition of :math:`1`
  775. to the numerator and denominator can be thought of as including the
  776. value of the statistic corresponding with `data` in the null distribution,
  777. but a more formal explanation is given in [5]_.
  778. *Limitations*
  779. The test can be very slow for some distribution families because unknown
  780. parameters of the distribution family must be fit to each of the Monte
  781. Carlo samples, and for most distributions in SciPy, distribution fitting
  782. performed via numerical optimization.
  783. *Anti-Pattern*
  784. For this reason, it may be tempting
  785. to treat parameters of the distribution pre-fit to `data` (by the user)
  786. as though they were `known_params`, as specification of all parameters of
  787. the distribution precludes the need to fit the distribution to each Monte
  788. Carlo sample. (This is essentially how the original Kilmogorov-Smirnov
  789. test is performed.) Although such a test can provide evidence against the
  790. null hypothesis, the test is conservative in the sense that small p-values
  791. will tend to (greatly) *overestimate* the probability of making a type I
  792. error (that is, rejecting the null hypothesis although it is true), and the
  793. power of the test is low (that is, it is less likely to reject the null
  794. hypothesis even when the null hypothesis is false).
  795. This is because the Monte Carlo samples are less likely to agree with the
  796. null-hypothesized distribution as well as `data`. This tends to increase
  797. the values of the statistic recorded in the null distribution, so that a
  798. larger number of them exceed the value of statistic for `data`, thereby
  799. inflating the p-value.
  800. References
  801. ----------
  802. .. [1] M. A. Stephens (1974). "EDF Statistics for Goodness of Fit and
  803. Some Comparisons." Journal of the American Statistical Association,
  804. Vol. 69, pp. 730-737.
  805. .. [2] W. Stute, W. G. Manteiga, and M. P. Quindimil (1993).
  806. "Bootstrap based goodness-of-fit-tests." Metrika 40.1: 243-256.
  807. .. [3] C. Genest, & B Rémillard. (2008). "Validity of the parametric
  808. bootstrap for goodness-of-fit testing in semiparametric models."
  809. Annales de l'IHP Probabilités et statistiques. Vol. 44. No. 6.
  810. .. [4] I. Kojadinovic and J. Yan (2012). "Goodness-of-fit testing based on
  811. a weighted bootstrap: A fast large-sample alternative to the
  812. parametric bootstrap." Canadian Journal of Statistics 40.3: 480-500.
  813. .. [5] B. Phipson and G. K. Smyth (2010). "Permutation P-values Should
  814. Never Be Zero: Calculating Exact P-values When Permutations Are
  815. Randomly Drawn." Statistical Applications in Genetics and Molecular
  816. Biology 9.1.
  817. .. [6] H. W. Lilliefors (1967). "On the Kolmogorov-Smirnov test for
  818. normality with mean and variance unknown." Journal of the American
  819. statistical Association 62.318: 399-402.
  820. .. [7] Filliben, James J. "The probability plot correlation coefficient
  821. test for normality." Technometrics 17.1 (1975): 111-117.
  822. Examples
  823. --------
  824. A well-known test of the null hypothesis that data were drawn from a
  825. given distribution is the Kolmogorov-Smirnov (KS) test, available in SciPy
  826. as `scipy.stats.ks_1samp`. Suppose we wish to test whether the following
  827. data:
  828. >>> import numpy as np
  829. >>> from scipy import stats
  830. >>> rng = np.random.default_rng(1638083107694713882823079058616272161)
  831. >>> x = stats.uniform.rvs(size=75, random_state=rng)
  832. were sampled from a normal distribution. To perform a KS test, the
  833. empirical distribution function of the observed data will be compared
  834. against the (theoretical) cumulative distribution function of a normal
  835. distribution. Of course, to do this, the normal distribution under the null
  836. hypothesis must be fully specified. This is commonly done by first fitting
  837. the ``loc`` and ``scale`` parameters of the distribution to the observed
  838. data, then performing the test.
  839. >>> loc, scale = np.mean(x), np.std(x, ddof=1)
  840. >>> cdf = stats.norm(loc, scale).cdf
  841. >>> stats.ks_1samp(x, cdf)
  842. KstestResult(statistic=0.1119257570456813,
  843. pvalue=0.2827756409939257,
  844. statistic_location=0.7751845155861765,
  845. statistic_sign=-1)
  846. An advantage of the KS-test is that the p-value - the probability of
  847. obtaining a value of the test statistic under the null hypothesis as
  848. extreme as the value obtained from the observed data - can be calculated
  849. exactly and efficiently. `goodness_of_fit` can only approximate these
  850. results.
  851. >>> known_params = {'loc': loc, 'scale': scale}
  852. >>> res = stats.goodness_of_fit(stats.norm, x, known_params=known_params,
  853. ... statistic='ks', rng=rng)
  854. >>> res.statistic, res.pvalue
  855. (0.1119257570456813, 0.2788)
  856. The statistic matches exactly, but the p-value is estimated by forming
  857. a "Monte Carlo null distribution", that is, by explicitly drawing random
  858. samples from `scipy.stats.norm` with the provided parameters and
  859. calculating the stastic for each. The fraction of these statistic values
  860. at least as extreme as ``res.statistic`` approximates the exact p-value
  861. calculated by `scipy.stats.ks_1samp`.
  862. However, in many cases, we would prefer to test only that the data were
  863. sampled from one of *any* member of the normal distribution family, not
  864. specifically from the normal distribution with the location and scale
  865. fitted to the observed sample. In this case, Lilliefors [6]_ argued that
  866. the KS test is far too conservative (that is, the p-value overstates
  867. the actual probability of rejecting a true null hypothesis) and thus lacks
  868. power - the ability to reject the null hypothesis when the null hypothesis
  869. is actually false.
  870. Indeed, our p-value above is approximately 0.28, which is far too large
  871. to reject the null hypothesis at any common significance level.
  872. Consider why this might be. Note that in the KS test above, the statistic
  873. always compares data against the CDF of a normal distribution fitted to the
  874. *observed data*. This tends to reduce the value of the statistic for the
  875. observed data, but it is "unfair" when computing the statistic for other
  876. samples, such as those we randomly draw to form the Monte Carlo null
  877. distribution. It is easy to correct for this: whenever we compute the KS
  878. statistic of a sample, we use the CDF of a normal distribution fitted
  879. to *that sample*. The null distribution in this case has not been
  880. calculated exactly and is tyically approximated using Monte Carlo methods
  881. as described above. This is where `goodness_of_fit` excels.
  882. >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ks', rng=rng)
  883. >>> res.statistic, res.pvalue
  884. (0.1119257570456813, 0.0196)
  885. Indeed, this p-value is much smaller, and small enough to (correctly)
  886. reject the null hypothesis at common significance levels, including 5% and
  887. 2.5%.
  888. However, the KS statistic is not very sensitive to all deviations from
  889. normality. The original advantage of the KS statistic was the ability
  890. to compute the null distribution theoretically, but a more sensitive
  891. statistic - resulting in a higher test power - can be used now that we can
  892. approximate the null distribution
  893. computationally. The Anderson-Darling statistic [1]_ tends to be more
  894. sensitive, and critical values of this statistic have been tabulated
  895. for various significance levels and sample sizes using Monte Carlo methods.
  896. >>> res = stats.anderson(x, 'norm', method='interpolate')
  897. >>> print(res.statistic)
  898. 1.2139573337497467
  899. >>> print(res.pvalue)
  900. 0.01
  901. Here, the observed value of the statistic exceeds the critical value
  902. corresponding with a 1% significance level. This tells us that the p-value
  903. of the observed data is 1% or less, but what is it? `goodness_of_fit` can
  904. estimate it directly.
  905. >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ad', rng=rng)
  906. >>> res.statistic, res.pvalue
  907. (1.2139573337497467, 0.0034)
  908. A further advantage is that use of `goodness_of_fit` is not limited to
  909. a particular set of distributions or conditions on which parameters
  910. are known versus which must be estimated from data. Instead,
  911. `goodness_of_fit` can estimate p-values relatively quickly for any
  912. distribution with a sufficiently fast and reliable ``fit`` method. For
  913. instance, here we perform a goodness of fit test using the Cramer-von Mises
  914. statistic against the Rayleigh distribution with known location and unknown
  915. scale.
  916. >>> rng = np.random.default_rng()
  917. >>> x = stats.chi(df=2.2, loc=0, scale=2).rvs(size=1000, random_state=rng)
  918. >>> res = stats.goodness_of_fit(stats.rayleigh, x, statistic='cvm',
  919. ... known_params={'loc': 0}, rng=rng)
  920. This executes fairly quickly, but to check the reliability of the ``fit``
  921. method, we should inspect the fit result.
  922. >>> res.fit_result # location is as specified, and scale is reasonable
  923. params: FitParams(loc=0.0, scale=2.1026719844231243)
  924. success: True
  925. message: 'The fit was performed successfully.'
  926. >>> import matplotlib.pyplot as plt # matplotlib must be installed to plot
  927. >>> res.fit_result.plot()
  928. >>> plt.show()
  929. If the distribution is not fit to the observed data as well as possible,
  930. the test may not control the type I error rate, that is, the chance of
  931. rejecting the null hypothesis even when it is true.
  932. We should also look for extreme outliers in the null distribution that
  933. may be caused by unreliable fitting. These do not necessarily invalidate
  934. the result, but they tend to reduce the test's power.
  935. >>> _, ax = plt.subplots()
  936. >>> ax.hist(np.log10(res.null_distribution))
  937. >>> ax.set_xlabel("log10 of CVM statistic under the null hypothesis")
  938. >>> ax.set_ylabel("Frequency")
  939. >>> ax.set_title("Histogram of the Monte Carlo null distribution")
  940. >>> plt.show()
  941. This plot seems reassuring.
  942. If ``fit`` method is working reliably, and if the distribution of the test
  943. statistic is not particularly sensitive to the values of the fitted
  944. parameters, then the p-value provided by `goodness_of_fit` is expected to
  945. be a good approximation.
  946. >>> res.statistic, res.pvalue
  947. (0.2231991510248692, 0.0525)
  948. """
  949. args = _gof_iv(dist, data, known_params, fit_params, guessed_params,
  950. statistic, n_mc_samples, rng)
  951. (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params,
  952. guessed_rfd_params, statistic, n_mc_samples_int, rng) = args
  953. # Fit null hypothesis distribution to data
  954. nhd_fit_fun = _get_fit_fun(dist, data, guessed_nhd_params,
  955. fixed_nhd_params)
  956. nhd_vals = nhd_fit_fun(data)
  957. nhd_dist = dist(*nhd_vals)
  958. def rvs(size):
  959. return nhd_dist.rvs(size=size, random_state=rng)
  960. # Define statistic
  961. fit_fun = _get_fit_fun(dist, data, guessed_rfd_params, fixed_rfd_params)
  962. if callable(statistic):
  963. compare_fun = statistic
  964. else:
  965. compare_fun = _compare_dict[statistic]
  966. alternative = getattr(compare_fun, 'alternative', 'greater')
  967. def statistic_fun(data, axis):
  968. # Make things simple by always working along the last axis.
  969. data = np.moveaxis(data, axis, -1)
  970. rfd_vals = fit_fun(data)
  971. rfd_dist = dist(*rfd_vals)
  972. return compare_fun(rfd_dist, data, axis=-1)
  973. res = stats.monte_carlo_test(data, rvs, statistic_fun, vectorized=True,
  974. n_resamples=n_mc_samples, axis=-1,
  975. alternative=alternative)
  976. opt_res = optimize.OptimizeResult()
  977. opt_res.success = True
  978. opt_res.message = "The fit was performed successfully."
  979. opt_res.x = nhd_vals
  980. # Only continuous distributions for now, hence discrete=False
  981. # There's no fundamental limitation; it's just that we're not using
  982. # stats.fit, discrete distributions don't have `fit` method, and
  983. # we haven't written any vectorized fit functions for a discrete
  984. # distribution yet.
  985. return GoodnessOfFitResult(FitResult(dist, data, False, opt_res),
  986. res.statistic, res.pvalue,
  987. res.null_distribution)
  988. def _get_fit_fun(dist, data, guessed_params, fixed_params):
  989. shape_names = [] if dist.shapes is None else dist.shapes.split(", ")
  990. param_names = shape_names + ['loc', 'scale']
  991. fparam_names = ['f'+name for name in param_names]
  992. all_fixed = not set(fparam_names).difference(fixed_params)
  993. guessed_shapes = [guessed_params.pop(x, None)
  994. for x in shape_names if x in guessed_params]
  995. if all_fixed:
  996. def fit_fun(data):
  997. return [fixed_params[name] for name in fparam_names]
  998. # Define statistic, including fitting distribution to data
  999. elif dist in _fit_funs:
  1000. def fit_fun(data):
  1001. params = _fit_funs[dist](data, **fixed_params)
  1002. params = np.asarray(np.broadcast_arrays(*params))
  1003. if params.ndim > 1:
  1004. params = params[..., np.newaxis]
  1005. return params
  1006. else:
  1007. def fit_fun_1d(data):
  1008. return dist.fit(data, *guessed_shapes, **guessed_params,
  1009. **fixed_params)
  1010. def fit_fun(data):
  1011. params = np.apply_along_axis(fit_fun_1d, axis=-1, arr=data)
  1012. if params.ndim > 1:
  1013. params = params.T[..., np.newaxis]
  1014. return params
  1015. return fit_fun
  1016. # Vectorized fitting functions. These are to accept ND `data` in which each
  1017. # row (slice along last axis) is a sample to fit and scalar fixed parameters.
  1018. # They return a tuple of shape parameter arrays, each of shape data.shape[:-1].
  1019. def _fit_norm(data, floc=None, fscale=None):
  1020. loc = floc
  1021. scale = fscale
  1022. if loc is None and scale is None:
  1023. loc = np.mean(data, axis=-1)
  1024. scale = np.std(data, ddof=1, axis=-1)
  1025. elif loc is None:
  1026. loc = np.mean(data, axis=-1)
  1027. elif scale is None:
  1028. scale = np.sqrt(((data - loc)**2).mean(axis=-1))
  1029. return loc, scale
  1030. _fit_funs = {stats.norm: _fit_norm} # type: ignore[attr-defined]
  1031. # Vectorized goodness of fit statistic functions. These accept a frozen
  1032. # distribution object and `data` in which each row (slice along last axis) is
  1033. # a sample.
  1034. def _anderson_darling(dist, data, axis):
  1035. x = np.sort(data, axis=-1)
  1036. n = data.shape[-1]
  1037. i = np.arange(1, n+1)
  1038. Si = (2*i - 1)/n * (dist.logcdf(x) + dist.logsf(x[..., ::-1]))
  1039. S = np.sum(Si, axis=-1)
  1040. return -n - S
  1041. def _compute_dplus(cdfvals): # adapted from _stats_py before gh-17062
  1042. n = cdfvals.shape[-1]
  1043. return (np.arange(1.0, n + 1) / n - cdfvals).max(axis=-1)
  1044. def _compute_dminus(cdfvals):
  1045. n = cdfvals.shape[-1]
  1046. return (cdfvals - np.arange(0.0, n)/n).max(axis=-1)
  1047. def _kolmogorov_smirnov(dist, data, axis=-1):
  1048. x = np.sort(data, axis=axis)
  1049. cdfvals = dist.cdf(x)
  1050. cdfvals = np.moveaxis(cdfvals, axis, -1)
  1051. Dplus = _compute_dplus(cdfvals) # always works along last axis
  1052. Dminus = _compute_dminus(cdfvals)
  1053. return np.maximum(Dplus, Dminus)
  1054. def _corr(X, M):
  1055. # Correlation coefficient r, simplified and vectorized as we need it.
  1056. # See [7] Equation (2). Lemma 1/2 are only for distributions symmetric
  1057. # about 0.
  1058. Xm = X.mean(axis=-1, keepdims=True)
  1059. Mm = M.mean(axis=-1, keepdims=True)
  1060. num = np.sum((X - Xm) * (M - Mm), axis=-1)
  1061. den = np.sqrt(np.sum((X - Xm)**2, axis=-1) * np.sum((M - Mm)**2, axis=-1))
  1062. return num/den
  1063. def _filliben(dist, data, axis):
  1064. # [7] Section 8 # 1
  1065. X = np.sort(data, axis=-1)
  1066. # [7] Section 8 # 2
  1067. n = data.shape[-1]
  1068. k = np.arange(1, n+1)
  1069. # Filliben used an approximation for the uniform distribution order
  1070. # statistic medians.
  1071. # m = (k - .3175)/(n + 0.365)
  1072. # m[-1] = 0.5**(1/n)
  1073. # m[0] = 1 - m[-1]
  1074. # We can just as easily use the (theoretically) exact values. See e.g.
  1075. # https://en.wikipedia.org/wiki/Order_statistic
  1076. # "Order statistics sampled from a uniform distribution"
  1077. m = stats.beta(k, n + 1 - k).median()
  1078. # [7] Section 8 # 3
  1079. M = dist.ppf(m)
  1080. # [7] Section 8 # 4
  1081. return _corr(X, M)
  1082. _filliben.alternative = 'less' # type: ignore[attr-defined]
  1083. def _cramer_von_mises(dist, data, axis):
  1084. x = np.sort(data, axis=-1)
  1085. n = data.shape[-1]
  1086. cdfvals = dist.cdf(x)
  1087. u = (2*np.arange(1, n+1) - 1)/(2*n)
  1088. w = 1 / (12*n) + np.sum((u - cdfvals)**2, axis=-1)
  1089. return w
  1090. _compare_dict = {"ad": _anderson_darling, "ks": _kolmogorov_smirnov,
  1091. "cvm": _cramer_von_mises, "filliben": _filliben}
  1092. def _gof_iv(dist, data, known_params, fit_params, guessed_params, statistic,
  1093. n_mc_samples, rng):
  1094. if not isinstance(dist, stats.rv_continuous):
  1095. message = ("`dist` must be a (non-frozen) instance of "
  1096. "`stats.rv_continuous`.")
  1097. raise TypeError(message)
  1098. data = np.asarray(data, dtype=float)
  1099. if not data.ndim == 1:
  1100. message = "`data` must be a one-dimensional array of numbers."
  1101. raise ValueError(message)
  1102. # Leave validation of these key/value pairs to the `fit` method,
  1103. # but collect these into dictionaries that will be used
  1104. known_params = known_params or dict()
  1105. fit_params = fit_params or dict()
  1106. guessed_params = guessed_params or dict()
  1107. known_params_f = {("f"+key): val for key, val in known_params.items()}
  1108. fit_params_f = {("f"+key): val for key, val in fit_params.items()}
  1109. # These are the values of parameters of the null distribution family
  1110. # with which resamples are drawn
  1111. fixed_nhd_params = known_params_f.copy()
  1112. fixed_nhd_params.update(fit_params_f)
  1113. # These are fixed when fitting the distribution family to resamples
  1114. fixed_rfd_params = known_params_f.copy()
  1115. # These are used as guesses when fitting the distribution family to
  1116. # the original data
  1117. guessed_nhd_params = guessed_params.copy()
  1118. # These are used as guesses when fitting the distribution family to
  1119. # resamples
  1120. guessed_rfd_params = fit_params.copy()
  1121. guessed_rfd_params.update(guessed_params)
  1122. if not callable(statistic):
  1123. statistic = statistic.lower()
  1124. statistics = {'ad', 'ks', 'cvm', 'filliben'}
  1125. if statistic not in statistics:
  1126. message = f"`statistic` must be one of {statistics}."
  1127. raise ValueError(message)
  1128. n_mc_samples_int = int(n_mc_samples)
  1129. if n_mc_samples_int != n_mc_samples:
  1130. message = "`n_mc_samples` must be an integer."
  1131. raise TypeError(message)
  1132. rng = check_random_state(rng)
  1133. return (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params,
  1134. guessed_rfd_params, statistic, n_mc_samples_int, rng)