FitResult#

class zfit.result.FitResult(loss, params, minimizer, valid, edm, fminopt, criterion, status=None, converged=None, message=None, info=None, approx=None, niter=None, evaluator=None)[source]#

Bases: ZfitResult

Create a FitResult from a minimization. Store parameter values, minimization infos and calculate errors.

Any errors calculated are saved under self.params dictionary with:

{parameter: {error_name1: {'low': value, 'high': value or similar}}

The ``FitResult can be used to temporarily update the parameter values to the values found by the minimization

with result:
    # do something with the new values
    ...
Parameters:
  • loss (ZfitLoss) – ​The loss function that was minimized. Usually, but not necessary, contains also the pdf, data and constraints.​

  • params (dict[ZfitParameter, float]) – ​Result of the fit where each Parameter key has the value from the minimum found by the minimizer.​

  • minimizer (ZfitMinimizer) – ​Minimizer that was used to obtain this FitResult and will be used to calculate certain errors. If the minimizer is state-based (like “iminuit”), then this is a copy and the state of other FitResults or of the actual minimizer that performed the minimization won’t be altered.​

  • valid (bool) –

    ​Indicating whether the result is valid or not. This is the strongest indication and serves as the global flag. The reasons why a result may be invalid can be arbitrary, including but not exclusive:

    • parameter(s) at the limit

    • maxiter reached without proper convergence

    • the minimizer maybe even converged but it is known that this is only a local minimum

    To indicate the reason for the invalidity, pass a message.​

  • edm (float) – ​The estimated distance to minimum which is the criterion value at the minimum.​

  • fminopt (float) – ​Value of the function at the minimum.​

  • criterion (ConvergenceCriterion | None) – ​Criterion that was used during the minimization. This determines the estimated distance to the minimum (edm)​

  • status (int | None) – ​A status code (if available) that describes the minimization termination. 0 means a valid termination.​

  • converged (bool | None) – ​Whether the fit has successfully converged or not. The result itself can still be an invalid minimum such as if the parameters are at or close to the limits or in case another minimum is found.​

  • message (str | None) – ​Human-readable message to indicate the reason if the fitresult is not valid. If the fit is valid, the message (should) be an empty string (or None), otherwise, it should denote the reason for the invalidity.​

  • info (Mapping | None) –

    ​Additional information (if available) such as number of gradient function calls or the original minimizer return message. This is a relatively free field and _no single field_ in it is guaranteed to be stable. Some recommended fields:

    • original: contains the original returned object by the minimizer used internally.

    • optimizer: the actual instance of the wrapped optimizer (if available)​

  • approx (Mapping | Approximations | None) – ​Collection of approximations found during the minimization process such as gradient and hessian.​

  • niter (int | None) – ​Approximate number of iterations ~= number of function evaluations ~= number of gradient evaluations. This is an approximated value and the exact meaning can differ between different minimizers.​

  • evaluator (LossEval) – ​Loss evaluator that was used during the minimization and that may contain information about the last evaluations of the gradient etc. which can serve as approximations.​

classmethod from_ipopt(loss, params, problem, minimizer, valid, values, message, converged, edm, niter, fminopt, status, criterion, evaluator)[source]#

Create a FitResult from an ipopt minimization.

Parameters:
  • loss (ZfitLoss) – ​The loss function that was minimized. Usually, but not necessary, contains also the pdf, data and constraints.​

  • params (Iterable[ZfitParameter]) – ​Result of the fit where each Parameter key has the value from the minimum found by the minimizer.​

  • problem (ipyopt.Problem) – |@doc:result.init.problem||@docend:result.init.problem|

  • minimizer (zfit.minimize.IpyoptV1) – ​Minimizer that was used to obtain this FitResult and will be used to calculate certain errors. If the minimizer is state-based (like “iminuit”), then this is a copy and the state of other FitResults or of the actual minimizer that performed the minimization won’t be altered.​

  • valid (bool) –

    ​Indicating whether the result is valid or not. This is the strongest indication and serves as the global flag. The reasons why a result may be invalid can be arbitrary, including but not exclusive:

    • parameter(s) at the limit

    • maxiter reached without proper convergence

    • the minimizer maybe even converged but it is known that this is only a local minimum

    To indicate the reason for the invalidity, pass a message.​

  • values (np.ndarray) – ​Values of the parameters at the found minimum.​

  • message (str | None) – ​Human-readable message to indicate the reason if the fitresult is not valid. If the fit is valid, the message (should) be an empty string (or None), otherwise, it should denote the reason for the invalidity.​

  • converged (bool | None) – ​Whether the fit has successfully converged or not. The result itself can still be an invalid minimum such as if the parameters are at or close to the limits or in case another minimum is found.​

  • edm (zfit.minimizers.termination.CriterionNotAvailable | float) – ​The estimated distance to minimum which is the criterion value at the minimum.​

  • niter (int | None) – ​Approximate number of iterations ~= number of function evaluations ~= number of gradient evaluations. This is an approximated value and the exact meaning can differ between different minimizers.​

  • fminopt (float | None) – ​Value of the function at the minimum.​

  • status (int | None) – ​A status code (if available) that describes the minimization termination. 0 means a valid termination.​

  • criterion (zfit.minimizers.termination.ConvergenceCriterion) – ​Criterion that was used during the minimization. This determines the estimated distance to the minimum (edm)​

  • evaluator (zfit.minimizers.evaluation.LossEval | None) – ​Loss evaluator that was used during the minimization and that may contain information about the last evaluations of the gradient etc. which can serve as approximations.​

Return type:

zfit.minimize.FitResult

classmethod from_minuit(loss, params, minuit, minimizer, valid, values=None, message=None, converged=None, edm=None, niter=None, fminopt=None, status=None, criterion=None, evaluator=None)[source]#

Create a FitResult from a MigradResult returned by iminuit.Minuit.migrad() and a iminuit Minuit instance with the corresponding zfit objects.

Parameters:
  • loss (ZfitLoss) – zfit Loss that was minimized.

  • params (Iterable[ZfitParameter]) – Iterable of the zfit parameters that were floating during the minimization.

  • minuit (Minuit) – Return value of the iminuit migrad command, the instance of iminuit.Minuit

  • minimizer (ZfitMinimizer | Minuit) – Instance of the zfit Minuit minimizer that was used to minimize the loss.

  • valid (bool | None) –

    ​Indicating whether the result is valid or not. This is the strongest indication and serves as the global flag. The reasons why a result may be invalid can be arbitrary, including but not exclusive:

    • parameter(s) at the limit

    • maxiter reached without proper convergence

    • the minimizer maybe even converged but it is known that this is only a local minimum

    To indicate the reason for the invalidity, pass a message.​

  • values (ndarray | None) – ​Values of the parameters at the found minimum.​

  • message (str | None) – ​Human-readable message to indicate the reason if the fitresult is not valid. If the fit is valid, the message (should) be an empty string (or None), otherwise, it should denote the reason for the invalidity.​

  • converged (bool | None) – ​Whether the fit has successfully converged or not. The result itself can still be an invalid minimum such as if the parameters are at or close to the limits or in case another minimum is found.​

  • edm (None | CriterionNotAvailable | float) – ​The estimated distance to minimum which is the criterion value at the minimum.​

  • niter (int | None) – ​Approximate number of iterations ~= number of function evaluations ~= number of gradient evaluations. This is an approximated value and the exact meaning can differ between different minimizers.​

  • fminopt (float | None) – ​Value of the function at the minimum.​

  • status (int | None) – ​A status code (if available) that describes the minimization termination. 0 means a valid termination.​

  • criterion (ConvergenceCriterion | None) – ​Criterion that was used during the minimization. This determines the estimated distance to the minimum (edm)​

  • evaluator (LossEval | None) – ​Loss evaluator that was used during the minimization and that may contain information about the last evaluations of the gradient etc. which can serve as approximations.​

Returns:

A FitResult as if zfit Minuit was used.

Return type:

zfit.minimize.FitResult

classmethod from_scipy(loss, params, result, minimizer, message, valid, criterion, edm=None, niter=None, evaluator=None)[source]#

Create a ``FitResult from a SciPy OptimizeResult.

Parameters:
  • loss – ​The loss function that was minimized. Usually, but not necessary, contains also the pdf, data and constraints.​

  • params – ​Result of the fit where each Parameter key has the value from the minimum found by the minimizer.​

  • result – Result of the SciPy optimization.

  • minimizer – ​Minimizer that was used to obtain this FitResult and will be used to calculate certain errors. If the minimizer is state-based (like “iminuit”), then this is a copy and the state of other FitResults or of the actual minimizer that performed the minimization won’t be altered.​

  • message – ​Human-readable message to indicate the reason if the fitresult is not valid. If the fit is valid, the message (should) be an empty string (or None), otherwise, it should denote the reason for the invalidity.​

  • edm – ​The estimated distance to minimum which is the criterion value at the minimum.​

  • niter – ​Approximate number of iterations ~= number of function evaluations ~= number of gradient evaluations. This is an approximated value and the exact meaning can differ between different minimizers.​

  • valid

    ​Indicating whether the result is valid or not. This is the strongest indication and serves as the global flag. The reasons why a result may be invalid can be arbitrary, including but not exclusive:

    • parameter(s) at the limit

    • maxiter reached without proper convergence

    • the minimizer maybe even converged but it is known that this is only a local minimum

    To indicate the reason for the invalidity, pass a message.​

  • criterion – ​Criterion that was used during the minimization. This determines the estimated distance to the minimum (edm)​

  • evaluator – ​Loss evaluator that was used during the minimization and that may contain information about the last evaluations of the gradient etc. which can serve as approximations.​

Return type:

zfit.minimize.FitResult

classmethod from_nlopt(loss, opt, params, minimizer, valid, values=None, message=None, converged=None, edm=None, niter=None, fminopt=None, status=None, criterion=None, evaluator=None, inv_hessian=None, hessian=None)[source]#

Create a FitResult from an NLopt optimizer.

Parameters:
  • loss (ZfitLoss) – ​The loss function that was minimized. Usually, but not necessary, contains also the pdf, data and constraints.​

  • opt – Optimizer instance of NLopt

  • params (Iterable[ZfitParameter]) – ​Result of the fit where each Parameter key has the value from the minimum found by the minimizer.​

  • minimizer (ZfitMinimizer | Minuit) – ​Minimizer that was used to obtain this FitResult and will be used to calculate certain errors. If the minimizer is state-based (like “iminuit”), then this is a copy and the state of other FitResults or of the actual minimizer that performed the minimization won’t be altered.​

  • valid (bool | None) –

    ​Indicating whether the result is valid or not. This is the strongest indication and serves as the global flag. The reasons why a result may be invalid can be arbitrary, including but not exclusive:

    • parameter(s) at the limit

    • maxiter reached without proper convergence

    • the minimizer maybe even converged but it is known that this is only a local minimum

    To indicate the reason for the invalidity, pass a message.​

  • values (ndarray | None) – ​Values of the parameters at the found minimum.​

  • message (str | None) – ​Human-readable message to indicate the reason if the fitresult is not valid. If the fit is valid, the message (should) be an empty string (or None), otherwise, it should denote the reason for the invalidity.​

  • converged (bool | None) – ​Whether the fit has successfully converged or not. The result itself can still be an invalid minimum such as if the parameters are at or close to the limits or in case another minimum is found.​

  • edm (None | CriterionNotAvailable | float) – ​The estimated distance to minimum which is the criterion value at the minimum.​

  • niter (int | None) – ​Approximate number of iterations ~= number of function evaluations ~= number of gradient evaluations. This is an approximated value and the exact meaning can differ between different minimizers.​

  • fminopt (float | None) – ​Value of the function at the minimum.​

  • status (int | None) – ​A status code (if available) that describes the minimization termination. 0 means a valid termination.​

  • criterion (ConvergenceCriterion | None) – ​Criterion that was used during the minimization. This determines the estimated distance to the minimum (edm)​

  • evaluator (LossEval | None) – ​Loss evaluator that was used during the minimization and that may contain information about the last evaluations of the gradient etc. which can serve as approximations.​

  • inv_hessian (ndarray | None) – The (approximated) inverse hessian matrix.

  • hessian (ndarray | None) – The (approximated) hessian matrix.

Return type:

zfit.minimizers.fitresult.FitResult

property edm: float#

The estimated distance to the minimum.

Returns:

Numeric

property fminopt: float#

Function value with possible optimizations at the minimum, namely constant subtraction.

Returns:

Numeric

property fmin: float#

Function value, fully evaluated, at the minimum.

Returns:

Numeric

property fminfull: float#

Function value, fully evaluated, at the minimum. (deprecated)

Deprecated: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use fmin instead which now returns the full minimum value. This will be removed in the future.

Returns:

Numeric

hesse(params=None, method=None, cl=None, name=None, error_name=None)[source]#

Calculate for params the symmetric error using the Hessian/covariance matrix. (deprecated arguments)

Deprecated: SOME ARGUMENTS ARE DEPRECATED: (error_name). They will be removed in a future version. Instructions for updating: Use name instead

This method estimates the covariance matrix using the inverse of the Hessian matrix. The assumption is that the loss profile - usually a likelihood or a \(\chi^2\) - is hyperbolic. This is usually the case for fits with many observations, i.e. it is exact in the asymptotic limit. If the loss profile is not hyperbolic, another method, “zfit_error” or “minuit_minos” should be used.

Weights Weighted likelihoods are a special class of likelihoods as they are not an actual likelihood. However, the minimum is still valid, however the profile is not a proper likelihood. Therefore, corrections will be automatically applied to the Hessian uncertainty estimation in order to correct for the effects in the weights. The corrections used are “asymptotically correct” and are described in Parameter uncertainties in weighted unbinned maximum likelihood fits` by Christoph Langenbruch. Since this method uses the jacobian matrix, it takes significantly longer to calculate than witout weights.

Parameters:
  • params (Optional[Iterable[ZfitParameter]]) – The parameters to calculate the Hessian symmetric error. If None, use all parameters.

  • method (str | Callable | None) – the method to calculate the covariance matrix. Can be {‘minuit_hesse’, ‘hesse_np’, ‘approx’} or a callable.

  • cl (float | None) – Confidence level for the error. If None, use the default value of 0.68.

  • name (str | bool | None) – The name for the error in the dictionary. This will be added to the information collected in params under params[p][name] where p is a Parameter. If the name is False, it won’t be added and only returned. Defaulst to 'hesse'.

Return type:

dict[ZfitIndependentParameter, dict]

Returns:

Result of the hessian (symmetric) error as dict with each parameter holding

the error dict {‘error’: sym_error}.

So given param_a (from zfit.Parameter(.)) error_a = result.hesse(params=param_a)[param_a]['error'] error_a is the hessian error.

error(params=None, method=None, error_name=None, sigma=1.0)[source]#

Deprecated since version unknown: Use errors() instead.

Parameters:
  • params (Optional[Iterable[ZfitParameter]]) – The parameters or their names to calculate the errors. If params is None, use all floating parameters.

  • method (str | Callable | None) – The method to use to calculate the errors. Valid choices are {‘minuit_minos’} or a Callable.

  • sigma (float) –

    Errors are calculated with respect to sigma std deviations. The definition of 1 sigma depends on the loss function and is defined there.

    For example, the negative log-likelihood (without the factor of 2) has a correspondents of \(\Delta\) NLL of 1 corresponds to 1 std deviation.

  • error_name (str | None) – The name for the error in the dictionary.

Return type:

dict

Returns:

A dict containing as keys the parameter names and as value a dict which

contains (next to probably more things) two keys ‘lower’ and ‘upper’, holding the calculated errors. Example: result[‘par1’][‘upper’] -> the asymmetric upper error of ‘par1’

errors(params=None, method=None, name=None, cl=None, *, sigma=None, error_name=None)[source]#

Calculate and set for params the asymmetric error using the set error method. (deprecated arguments)

Deprecated: SOME ARGUMENTS ARE DEPRECATED: (error_name). They will be removed in a future version. Instructions for updating: Use name instead.

Parameters:
  • params (Optional[Iterable[ZfitParameter]]) – The parameters or their names to calculate the errors. If params is None, use all floating parameters.

  • method (str | Callable | None) – The method to use to calculate the errors. Valid choices are {‘minuit_minos’, ‘zfit_errors’} or a Callable.

  • cl (float | None) – Uncertainties are calculated with respect to the confidence level cl. The default is 68.3%. For example, the negative log-likelihood (without the factor of 2) has a correspondents of \(\Delta\) NLL of 1 corresponds to 1 std deviation.

  • sigma – Errors are calculated with respect to sigma std deviations. The definition of 1 sigma depends on the loss function and is defined there.

  • name (str | None) – The name for the error in the dictionary. Defaults to errors

Return type:

tuple[dict, None | FitResult]

Returns:

A dict containing as keys the parameter and as value a dict which

contains (next to often more things) two keys ‘lower’ and ‘upper’, holding the calculated errors. Furthermore, it has cl to indicate the convidence level the uncertainty was calculated with. Example: result[par1][‘upper’] -> the asymmetric upper error of ‘par1’

covariance(params=None, method=None, as_dict=False)[source]#

Calculate the covariance matrix for params.

Parameters:
  • params (Optional[Iterable[ZfitParameter]]) – The parameters to calculate the covariance matrix. If params is None, use all floating parameters.

  • method (str | Callable | None) – The method to use to calculate the covariance matrix. Valid choices are {‘minuit_hesse’, ‘hesse_np’} or a Callable.

  • as_dict (bool) – Default False. If True then returns a dictionnary.

Returns:

2D numpy.array of shape (N, N); dict`(param1, param2) -> covariance if `as_dict == True.

correlation(params=None, method=None, as_dict=False)[source]#

Calculate the correlation matrix for params.

Parameters:
  • params (Optional[Iterable[ZfitParameter]]) – The parameters to calculate the correlation matrix. If params is None, use all floating parameters.

  • method (str | Callable | None) – The method to use to calculate the correlation matrix. Valid choices are {‘minuit_hesse’, ‘hesse_np’} or a Callable.

  • as_dict (bool) – Default False. If True then returns a dictionnary.

Returns:

2D numpy.array of shape (N, N); dict`(param1, param2) -> correlation if `as_dict == True.

freeze()[source]#

Freeze the result to make it pickleable and convert all TensorFlow elements to names (parameters) or arrays.

After this, no more uncertainties or covariances can be calculated. The already calculated ones remain however.

Parameters can be accessed by their string name.

update_params()[source]#

Update the parameters of the result to the current values.

Usually to be used chained with a minimize call to update the parameters to the current values.

(currently, the parameters are updated to the values of the result, this might change in the future. To enable this expected behavior, use zfit.run.experimental_disable_param_update().

result = minimizer.minimize(loss).update_params()  # update the parameters to the current values
Return type:

Self