Skip to content

Strange huber estimation failure #4749

Closed

Description

@arminsch

Running a huber estimate on the data in the attached script, produces NaN for the new scale estimate on the first huber iteration due to the fact that the SQRT gets a negative result as input.

bug_huber.txt

Activity

  1. josef-pkt commented on Jun 22, 2018

    @josef-pkt
    Member

    The separate class for mean and scale estimation are not well tested.
    I get a convergence failure, which raises an exception that maxiter has been reached, which doesn't allow seeing any results.

    Using RLM with just a constant as regressor works for me:

    >>> from statsmodels.robust.robust_linear_model import RLM
    >>> res = RLM(a, np.ones(len(a))).fit()
    >>> print(res.summary())
                        Robust linear Model Regression Results                    
    ==============================================================================
    Dep. Variable:                      y   No. Observations:                   25
    Model:                            RLM   Df Residuals:                       24
    Method:                          IRLS   Df Model:                            0
    Norm:                          HuberT                                         
    Scale Est.:                       mad                                         
    Cov Type:                          H1                                         
    Date:                Fri, 22 Jun 2018                                         
    Time:                        08:09:35                                         
    No. Iterations:                    42                                         
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const        1.31e-05   9.06e-07     14.460      0.000    1.13e-05    1.49e-05
    ==============================================================================
    
    If the model instance has been used for another fit with different fit
    parameters, then the fit options might not be the correct ones anymore .
    
  2. bashtage commented on May 10, 2019

    @bashtage
    Member

    The joint estimation of loc and scale in Huber().__call__ is almost certaintly wrong, and doesn't align with HuberScale().__call__ (which appears to be right). In this example, it quickly produces a nan and then cannot recover.

    In a quick look, I had

                # TODO: This is wrong and doesn't match up with the scale estimator below
                nscale = np.sum(subset * (a - nmu)**2, axis)
                denom = n * self.gamma - (a.shape[axis] - card) * self.c**2
                if denom <= 0:
                    raise RuntimeError('The number of observations clipped is too large to estimate the scale.')
                nscale = np.sqrt(nscale / denom)
    
  3. added this to the 0.15 milestone on Feb 13, 2023
  4. josef-pkt commented on Feb 13, 2023

    @josef-pkt
    Member

    aside: HuberScale in summary looks awful

    from statsmodels.robust.robust_linear_model import RLM
    res = RLM(a, np.ones(len(a))).fit(scale_est=HuberScale())
    print(res.summary())
                                                Robust linear Model Regression Results                                            
    ==============================================================================================================================
    Dep. Variable:                                                                      y   No. Observations:                   25
    Model:                                                                            RLM   Df Residuals:                       24
    Method:                                                                          IRLS   Df Model:                            0
    Norm:                                                                          HuberT                                         
    Scale Est.:        <statsmodels.robust.scale.HuberScale object at 0x0000018DA5F070D0>                                         
    Cov Type:                                                                          H1                                         
    Date:                                                                Mon, 13 Feb 2023                                         
    Time:                                                                        15:03:29                                         
    No. Iterations:                                                                    19                                         
    ==============================================================================
                     coef    std err          z      P>|z|      [0.025      0.975]
    ------------------------------------------------------------------------------
    const       1.367e-05   1.15e-06     11.920      0.000    1.14e-05    1.59e-05
    ==============================================================================
    
    If the model instance has been used for another fit with different fit parameters, then the fit options might not be the correct ones anymore .
    
  5. josef-pkt commented on Feb 13, 2023

    @josef-pkt
    Member

    bump for 0.15

    (plus unblackening the math code. Current code is very difficult to read, e.g.)

                        nmu = (
                            np.clip(
                                a, mu - self.c * scale, mu + self.c * scale
                            ).sum(axis)
                            / a.shape[axis]
                        )
    
  6. josef-pkt commented on Feb 13, 2023

    @josef-pkt
    Member

    It looks like one problem is using mad as initial scale if it is (almost) zero.

    Huber converges if I use a larger initscale.

    Note: initscale needs to be ndarray. float does not work because of all the squeeze, unsqueeze and reshape.
    (This might have been written as python/numpy beginner code)

    mad(a)
    1.3521628753216128e-08
    
    mu, sigma = huber(a, initscale=np.array([1e-5]))
    mu, sigma
    (array(1.33906562e-05), array(4.83233514e-06))
    

    compared to
    Using RLM with HuberScale()

    res.scale
    6.48692872694819e-06
    

    using RLM with mad scale_est

    res.scale
    4.2580486683866295e-06
    
  7. josef-pkt commented on Apr 15, 2024

    @josef-pkt
    Member

    I went through the scale iteration in Huber and don't understand the computation.
    If I change it to something standard, ie. scale_num is winsorized sum of squares, then I get convergence although it requires larger maxiter than default for the data in this issue.

    huber fit/__call__ does not have maxiter and tol option in "fit", but those are attributes that can be changed.
    update maxiter, tol are __init__ keywords, e.g. unit test has scale.Huber(maxiter=1000, tol=1.0e-05)

    from numpy import array
    ​
    a = array([  1.02286155e-05,   1.02279780e-05,   1.02387317e-05,
                 1.02357109e-05, 1.02307766e-05, 1.02350112e-05,
                 1.02341674e-05, 1.02320804e-05, 1.02283522e-05,
                 1.02287553e-05, 1.02288503e-05, 1.02372008e-05,
                 1.02308826e-05, 1.02377357e-05, 1.02387762e-05,
                 1.72003218e-05, 7.44319603e-05, 7.85037962e-05,
                 1.52950017e-05, 1.76249754e-05, 1.66930273e-05,
                 1.88197850e-05, 1.30830323e-05, 2.29240966e-05,
                 2.52001856e-05])
    ​
    huber.maxiter=1000
    mu, sigma = huber(a) 
    mu, sigma
    (array(1.33906561e-05), array(4.83233509e-06))
    

    (My current change still causes shape errors in unit tests ValueError: cannot reshape array of size 48000 into shape (40,1,30))
    axis option is a pain in the code, too many squeeze and unsqueeze, and requires that mu and initscale need to be arrays.

    related issue #9171 and upcoming PR for fixes and MScale enhancements.

    aside:
    HuberScale has a different default than Huber
    The matching RLM would be the following but scale estimate is much smaller than the huber proposal 2 estimate.

    res_rlm = RLM(a, np.ones((len(a), 1))).fit(scale_est=rscale.HuberScale(d=1.5), tol=1e-13)
    res_rlm.params, res_rlm.scale
    (array([1.03132439e-05]), 2.3462000755368284e-08)
    

    I don't know why there is not a closer match in the estimates between RLM and scale.Huber.
    (unless precision issues introduce several local minima)

  8. josef-pkt commented on Apr 15, 2024

    @josef-pkt
    Member

    BUG:
    I got a convergence failure in unit test test_scale.py::TestHuberAxes::test_axis1 after my changes.

    current Huber.__call__ has hardcoded axis=0 when computing nobs/df_resid n

            if mu is None:
                n = a.shape[0] - 1
                mu = np.median(a, axis=axis)
                est_mu = True
            else:
                n = a.shape[0]
                mu = mu
                est_mu = False
    

    unit tests don't fail on this because they only check shape and not correctness of numbers
    after fixing the axis here, I don't get convergence failures anymore, even if I reduce maxiter from 1000 to 100.
    (maxiter=1000 was working around the bug in the unit test).

  9. bashtage commented on Jul 30, 2026

    @bashtage
    Member

    Fixed via PR #9210 (commit dc0844f): replaced a hardcoded axis=0 with a.shape[axis], and replaced a scale-update formula that could go negative (feeding sqrt a negative value) with an always-positive winsorized-sum-of-squares formula in robust.scale.Huber (statsmodels/robust/scale.py). Closing as fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions