Skip to content

BUG/ENH: broken code in RLM._scale_est, scale callback option is missing #9171

Closed

Description

@josef-pkt

_scale_est method has an else path that uses an undefined variable scale.scale_est. scale refers to the module robust.scale but there is no scale_est.

        else:
            return scale.scale_est(self, resid) ** 2

My guess is that this should be return self.scale_est(self, resid) ** 2
which would allow scale_est to be a callable.

Obviously, we don't have a unit test for that path.

This is more an ENH than bug, because callable scale_est is not in the docstring of the fit method.

        scale_est : str or HuberScale()
            'mad' or HuberScale()
            Indicates the estimate to use for scaling the weights in the IRLS.
            The default is 'mad' (median absolute deviation.  Other options are
            'HuberScale' for Huber's proposal 2. Huber's proposal 2 has
            optional keyword arguments d, tol, and maxiter for specifying the
            tuning constant, the convergence tolerance, and the maximum number
            of iterations. See statsmodels.robust.scale for more information.

Motivation:
I'm looking at reusing RLM for S-estimator for regression.

S-estimator for regression satisfies locally the moment conditions of RLM, M-estimator for the mean parameters.
Additionally, an S-estimator needs an M-scale based on a redescending rho function.
I'm not sure if the HuberScale is the correct M-scale for the S-estimator.
We need a scale_est callback function, so that we can compute the scale with a user chosen norm/rho for the M-scale.
The norm in the M-scale needs to be the same as the norm of the RLM mean parameter model. In the current RLM those two are separately chose.

I guess, RLM can provide the local solution for the S-estimator for given start_params. However, the S-estimator needs a global solution that minimizes the scale, i.e. choose the local solution that has the smallest estimated M-scale.

If this works, the Fast-S or Det-S regression only needs to handle the global problem, i.e. choose several good or many random starting points and pick the best global solution.

More generically:
Current RLM when used with a redescending norm computes a local optimum chosen through starting values based on the OLS estimate.
There is currently no attempt at finding a "good" local optimum.
(AFAIR, I have not seen a reference that would use the rho at the local optimum to chose between local optima. We need an extra criterion like minimizing M-scale across local optima in the case of S-estimators.)

Something to try:
Use mad scale with redescending norm in RLM and do global optimization, e.g. those in scipy.optimize or by random initializations.
This should have a high breakdown point, but very low efficiency.
(However, RLM.fit has currently only irls method and no scipy.optimizers)

update

AFAICS, HuberScale is a winsorized scale
This is the same as the rho function of TrimmedMean (called Talwar in Menenez et al 2021, and IIRC in SAS documentation)
i.e. RLM currently has a M-scale based on redescending rho.
(
I have no idea what are the breakdown point and relative efficiency when we also use a redescending norm for mean parameters, and use global optimization.
scale_bias correction term is h in HuberScale computed in __init__ which would determine efficiency and breakdown point for given threshold c for an S-estimator with TrimmedMean norm, which might be close to LTS.
)

Aside: (I don't remember which textbook mentioned this as comment.)

The scale_bias correction for M-scale and S-estimators is calibrated to achieve a specified breakdown point and implied efficiency for a given reference distribution.
If the actual distribution is different from the reference distribution, then the breakdown point will differ from the intended one. However, mean estimates are still consistent (assuming symmetric distribution, as usual)
Scale estimate will not be calibrated for the normal distribution, but will still be a valid (?) scale estimate.

update2
If we have one objective function for mean parameters and scale (or mean parameters, shape/scatter and scale in multivariate case), then we can use the objective function as target for global optimization.
If mean parameter and scale/cov estimates are based moment conditions that are not derived from a single objective function, then we need to define global minimum in a different way, e.g. as in S-estimators.
reference e.g. comments in
Kent, John T., and David E. Tyler. 1991. “Redescending M-Estimates of Multivariate Location and Scatter.” The Annals of Statistics 19 (4): 2102–19.

Activity

  1. added this to the 0.15 milestone on Mar 13, 2024
  2. josef-pkt commented on Mar 14, 2024

    @josef-pkt
    MemberAuthor

    checking HuberScale versus TrimmedMean

    second part is copied from HuberScale.__init__, dropping df_resid / nobs from h
    Results for scale_bias agrees with numerical expectation/integration at high precision

    stats.norm.expect(lambda x : norms.TrimmedMean(c=2.5).rho(x))
    0.4887799917273257
    
    d = 2.5
    (
    d ** 2
    + (1 - d ** 2) * stats.norm.cdf(d)
    - 0.5
    - d / (np.sqrt(2 * np.pi)) * np.exp(-0.5 * d ** 2)
    )
    0.4887799917264034
    

    It looks like breakdown point is only around 0.15, with 90% relative efficiency

    0.4887799917273257 / norms.TrimmedMean(c=2.5).rho(2.5)
    0.15640959735274423
    
    1 / var_normal_jump(norms.TrimmedMean(c=2.5))
    0.8999391668109229
    

    aside: comparing with TukeyBiweight, 91.7% efficiency at breakdown point 0.15
    print(bp, eff, c_bp, b)
    0.15 0.917435422551397 4.096255394231153 0.4194827063691953

    So I think we can add a generic MScale class for user chosen norm (rho) with the same interface as HuberScale for compatibility in RLM. And with option to either tune for breakdown point or for efficiency.

  3. josef-pkt commented on Mar 14, 2024

    @josef-pkt
    MemberAuthor

    and another piece again
    single objective function for joint optimization of loc parameter and scale

    Hampel et all book p. 312 Remark 2 on Huber Proposal two

    objective function: (rho((y - x * theta) / s) + b ) * s
    first order condition for s: chi(r) - b = 0, moment condition for mean parameters psi(.) = 0
    where chi(x) = r * psi(x) - rho(r) - b
    (alternative is to use a different chi function in the moment condition for scale without having a matching objective function)

    quick check
    The implied chi function for the scale of HuberT norm for mean parameters is the TrimmedMean rho function used in HuberScale, although with a different threshold parameter.

    norm = norms.HuberT()
    chi =(x * norm.psi(x) - norm.rho(x))
    rho_tm = norms.TrimmedMean(c=norm.t).rho(x)
    print(np.max(np.abs(xhi - rho_tm)))
    plt.plot(x, xhi)
    plt.plot(x, rho_tm, '--')
    1.1102230246251565e-16
    ...
    

    I went through this joint optimization in the context of nonlinear models, Huber-Dutter (PR ???)

    So we have potentially several options for scale method

    • fixed scale from preliminary estimator, e.g. MM-estimation or One-step (truncated M-estimator iterations)
    • separately defined moment conditions (that's what RLM currently does), no single objective function that includes scale estimate
    • Huber: single objective function, chi is implied by norm
    • S-estimator: scale function is rho function of norm for mean parameters

    For the case of nonlinear mean function, I had tried to get a single objective function, but that is not needed.

    estimation algorithm that uses scipy optimizers could be:

    • single objective function for both mean parameters and scale. Does not allow separately define moment conditions
    • use rootfinding algorithms, i.e. solve moment conditions directly without objective function
    • use current alternating optimization, This can be extended to using scipy.optimize similar to nonlinear least square, i.e. alternate between nonlinear mean estimation and nonlinear scale estimation. This treats scale as auxiliary parameter as in OLS/WLS and GLM.

    In the last case, we only have to replace fit in RLM by nonlinear optimization (or use nonlinear WLS in irls) and we could reuse separate scale estimation.
    The same would apply to S-estimation once we extend RLM and scale methods.

    update
    variation on alternating optimization, mainly performance related

    Alternating optimization requires outer iteration loop. How many inner optimization iterations are we using.

    • joint iteration, only one-step updating of each parameter in the iteration loop
      • example robust.scale.Huber only does one step updating of scale in iteration loop (AFAICS)
    • alternating full optimization: within each outer iteration we update each parameter to convergence
      • current RLM fully updates scale, or at least has large maxiter in the scale estimation
    • k-step updating: in Fast-S and other Fast-XXX, inner optimization has small maxiter, e.g. 2 or 5, which can differ for mean parameters and scale or other parameters. (Several articles mention that scale computation is expensive, e.g. when using q_n scale)

    Note, convergence occurs in one-step for linear mean parameters, e.g. WLS or weighted average, for given scale.

    Current RLM has no option to reduce maxiter for scale estimation during optimization. It also does not inform the user about whether scale optimization in HuberScale itself has converged, although the RLM convergence requires that params don't change anymore (up to tolerance), which will require extra RLM iteration steps if scale has not converged yet.

    For Fast-X this performance improvement are relevant because the number of random starts has to be large or very large.
    For Det-X and single optimization runs will not be affected as much

  4. josef-pkt commented on Mar 21, 2024

    @josef-pkt
    MemberAuthor

    another question for which I don't know the answer yet.

    What is the scale used in cov_params for two stage estimators (high breakdown followed by high efficiency estimators) like MM-estimators?
    Do we use scale from first stage also for inference or do we reestimate the scale after using fixed scale during optimization?

    e.g. MM-estimators: M-estimator with fixed scale following a preliminary S-estimator.

    • we keep the initial scale
    • we reestimate using the initial S-estimator rho function
    • we reestimate using the second stage rho or psi function
    • we reestimate using a separately chosen rho or psi function
    • or just treat it as a generic M-estimator and use the sandwich for the given score/hessian (moment condition and derivatives) treating initial scale which is fixed in second stage as "nonrandom".

    Theoretically they all estimate the same scale.
    Also, it does not affect the parameter estimate, it affects only (small sample) inference.

    I guess I have to look more at the outlier robust inference literature for details and (small sample) behavior of different estimators.

    (AFAICS, efficiency discussion usually looks at mean parameter estimation. I don't remember seeing much on breakdown point efficiency of the scale estimate and of inference. However, I never looked much directly at the inference literature.)

    related:
    Van Aelst, Stefan, Gert Willems, and Ruben H. Zamar. 2013. “Robust and Efficient Estimation of the Residual Scale in Linear Regression.” Journal of Multivariate Analysis 116 (April): 278–96. https://doi.org/10.1016/j.jmva.2012.12.008.

    maybe this is a starting point (I did not look at it):
    Koller, Manuel, and Werner A. Stahel. 2011. “Sharpening Wald-Type Inference in Robust Regression for Small Samples.” Computational Statistics & Data Analysis 55 (8): 2504–15. https://doi.org/10.1016/j.csda.2011.02.014.
    302 citations in google scholar (citations might be mainly for their norms, weight functions)

  5. josef-pkt commented on Apr 12, 2024

    @josef-pkt
    MemberAuthor

    Van Aelst, Stefan, Gert Willems, and Ruben H. Zamar. 2013. “Robust and Efficient Estimation of the Residual Scale in Linear Regression.” Journal of Multivariate Analysis 116 (April): 278–96. https://doi.org/10.1016/j.jmva.2012.12.008.

    table 1 has several rho functions for scale, but I'm not sure where they come from.
    e.g. Huber is HuberScale (winsorized quadratic)
    Cauchy is t^1 / (t^2 + c^2) which is not the rho function of Cauchy norm, StudentT(df=1)
    it could be: t * psi(t) for Cauchy/StudentT norm.

    aside: they scale the rho functions so that max rho = 1. Cauchy rho/chi/psi_scale reaches finite bound at +inf and -inf.
    (rho of Cauchy/StudentT norm in unbound, and cannot be used for M-scale with breakdown point)

    implementation details, naming

    • moment condition for scale: "chi", "rho", "psi_scale" (?), with or without fisher consistency factor scale_bias
      • moment condition subtracts scale bias in standard version
      • scale iteration divides by scale bias
      • rescaled moment condition could divide by scale bias and subtract hardcoded 1.
    • do we use a parameterization that can be the same if we have a single objective function for mean and scale?

    first draft: user provides chi function without scale bias correction, need scale_bias separately or internally computed.
    extended interface (still unclear): allow norms and type of chi function from norm class.
    possibly: keep helper function simple with only chi function, and norm and chi-types go into the estimation classes.

  6. josef-pkt commented on Apr 13, 2024

    @josef-pkt
    MemberAuthor

    some preliminary observations for robust scales from brief Monte Carlo

    eval_measure in rows, true/dgp scale = 1, nobs=100
    mean fixed at "true" value = 0 (i.e. we don't have an estimate for mean that could be influenced by outliers)
    500 MC replication, no random seed

    4 scale estimators in "columns":
    MScale bisquare with 50% breakdown point
    HuberScale, default
    robust.scale q_n
    nonrobust standard deviation (assuming zero mean, i.e. mean square)

    results:

    • biweight 50%bp has smallest bias, but larger variance of estimate (lower efficiency) at center model (no outliers)
    • q_n is almost as robust as biweight at larger outlier fraction, but more biased than q_n for smaller outlier fraction (note this might be affected by knowing the true mean in biweight)
    • HuberScale: nonrobust at 20% outliers (more than it's breakdown point), some bias at 5%.

    no outliers:

    res_mc.mean(0), np.median(res_mc, axis=0), np.std(res_mc, axis=0), np.mean((res_mc - sigma)**2, axis=0)
    (array([1.00389073, 1.00083699, 1.03965807, 0.99935253]),
     array([0.99752684, 0.9940063 , 1.03624561, 0.99391357]),
     array([0.09508445, 0.06971501, 0.08001388, 0.06832704]),
     array([0.00905619, 0.00486088, 0.00797498, 0.004669  ]))
    

    5% outliers

    res_mc.mean(0), np.median(res_mc, axis=0), np.std(res_mc, axis=0), np.mean((res_mc - sigma)**2, axis=0)
    (array([1.07045746, 1.18977233, 1.14588167, 2.43916177]),
     array([1.0697291 , 1.18661633, 1.14685539, 2.43688936]),
     array([0.09950228, 0.08385562, 0.09259717, 0.0272896 ]),
     array([0.01486496, 0.0430453 , 0.0298557 , 2.07193134]))
    

    20% outliers

    res_mc.mean(0), np.median(res_mc, axis=0), np.std(res_mc, axis=0), np.mean((res_mc - sigma)**2, axis=0)
    (array([1.36490603, 4.61264302, 1.40086158, 4.56059548]),
     array([1.37227369, 4.61208533, 1.40477863, 4.56004409]),
     array([0.12499111, 0.01374776, 0.11911009, 0.01359263]),
     array([ 0.14877919, 13.05137859,  0.17487722, 12.67802496]))
    
  7. josef-pkt commented on Apr 14, 2024

    @josef-pkt
    MemberAuthor

    update
    the following is not a bug.
    I had used the wrong data in the example. Data with 20% outliers where HuberScale and TrimmedMean-MScale are not robust.
    everything works correctly, HuberScale and TrimmedMean-MScale produce the same scale estimate


    bug ?
    _iter_scale does not seem to work with TrimmedMean.rho. Using scale_bias from above #9171 (comment)
    I get a scale estimate in my experimental example that is not close to the dgp scale.

    _iter_scale uses a weighted iteration sum (weights * x**2) instead of a rho iteration as, AFAICS, HuberScale does.
    However, _iter_scale works very well for bisquare m-scale.

    ??? I don't remember the details.

    why would using weights work with redescending rho?
    e.g. winsorizing needs to replace x**2 with max rho for |x| > c
    Are there some assumptions on the chi function for using the weight version of the iteration?

    if weights = c**2 / x**2, then weights * x**2 = c

    update
    Maronna et al book p. 35 equ (2.54), (2.55) has weights version of moment condition
    It uses weights = rho''(0) (second derivative of rho) if x = 0
    for x != 0: weights(x) = rho(x) / x**2
    assumption rho'(0)=0 and rho''(0) > 0
    requires second derivative at 0, i.e. no kink

    the weight iteration is on p. 41, equ. (2.70), (2.80)

    Note:
    weights * x**2 = rho(x) / x**2 * x**2 = rho(x)
    computing weights adds just one extra step that cancels x2 / x2.
    edit
    that's not quite right, in rho we have x / scale, i.e.
    weights(x/s) * x**2 = rho(x/s) / (x/s)**2 * x**2 = rho(x/s) * s**2
    but x2 still cancels, but we need to include s2 in rho iteration

    which book has the rho iteration (without weights detour) ?

  8. josef-pkt commented on Apr 15, 2024

    @josef-pkt
    MemberAuthor

    default for HuberScale

    unit test for chem example in test_scale refer to Venables, Ripley 2002 MASS book
    comparing results, has good match, but default winsorizing threshold is 1.5, much smaller than our default 2.5

    nobs_chem = len(chem)
    res_r_mass = 0.940962823535378
    sc = rscale.HuberScale(d=1.5)(nobs_chem, nobs_chem,chem - 3.68)
    sc, sc - res_r_mass
    (0.9409638427692734, 1.019233895394045e-06)
    

    in R:

    > library(MASS)
    > options(digits=15)
    > hubers(chem, mu=3.68)
    $mu
    [1] 3.68
    
    $s
    [1] 0.940962823535378
    

    Aside:
    it looks like the unit tests do duplicate fitting, e.g.

    def test_huber_huberT(self):
            n = scale.norms.HuberT()
            n.t = 1.5
            h = scale.Huber(norm=n)
            assert_almost_equal(
                scale.huber(self.chem)[0], h(self.chem)[0], DECIMAL
            )
            assert_almost_equal(
                scale.huber(self.chem)[1], h(self.chem)[1], DECIMAL
            )
    

    AFAICS, this fits the data twice just to get the two returns.
    similarly duplicate fitting in other unit tests

    robust.scale.Huber
    default threshold is 1.5, and unit tests match results for loc and scale with MASS
    e.g.

    > hubers(chem)
    $mu
    [1] 3.20549780344626
    
    $s
    [1] 0.673652040342699
    
    rscale.Huber()(chem)
    (array(3.20549808), array(0.6736526))
    

    only Huber (joint estimation) has unit test in test_scale, HuberScale/huber_scale has not unit test there.
    HuberScale is tested through RLM through examples that use scale_est=HuberScale()
    tests/results module comment

    # RLM Results with Huber's Proposal 2
    # Obtained from SAS
    

    So SAS might default to threshold=2.5 for huber scale (proposal 2) in RLM

    If we don't want to change the threshold default for backwards compatibility, then we should at least point the user (in docs, notebooks) to the option of using scale estimate with higher breakdown point (lower threshold).

    more naming inconsistencies
    Huber has threshold name c
    HuberScale has threshold name d
    Huber also use a for the data array. HuberScale uses data.

    (based on skimming and some examples. I haven't done a full review of Huber and HuberScale.)

    update

    You can use the D=d option to specify d. By default, D=2.5.
    https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.3/statug/statug_rreg_details01.htm

    running an example (chem) with rlm in MASS, it looks like they use threshold 1.5 for Huber scale. But it looks like MASS rlm does not use the df correction df_resid / nobs = (nobs - k) / nobs.
    The difference in scale estimates between us and MASS is close to the df correction.

  9. josef-pkt commented on Apr 15, 2024

    @josef-pkt
    MemberAuthor

    example in #4749 has numerical problem

    using a "nice" example to compare scale estimates in Huber and HuberScale (Huber is my currently uncommitted corrected version with essentially the same computation as HuberScale)

    Huber uses fixed mu, so we only estimate scale.
    agreement looks too good, but if I subtract a small mean from one of the methods, then I get small differences.

    a = np.random.randn(100)
    a[:2] = 10
    s0 = rscale.HuberScale(d=1.5)(len(a) - 0, len(a), a)
    s1 = rscale.Huber(maxiter=500)(a, mu=np.array([0]))
    s0, s1
    (1.0489199041507082, (array(0), array(1.0489199)))
    s0 / s1[1], s0 - s1[1]
    (1.0, 0.0)
    
  10. josef-pkt commented on Apr 15, 2024

    @josef-pkt
    MemberAuthor

    a bit of timeit for rootfinding of MScale

    rho iteration is faster than scipy.optimize
    both default secant and newton have problems if starting scale is not good, second goes to inf, newton goes to negative.

    from scipy import optimize
    func = lambda s: np.mean(rho(x / s)) - scale_bias
    fprime = lambda s: -np.mean(rho.psi(x / s) * x) / s**2
    
    %timeit optimize.root_scalar(func, x0 = rscale.mad(x)/ 2, x1 = 2*x.std()) # method="newton")
    1.27 ms ± 3.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    %timeit optimize.root_scalar(func, fprime=fprime, x0 = rscale.mad(x)/ 2, x1 = 2*x.std(),  method="newton")
    697 µs ± 2.11 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    %timeit func_iter()
    175 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    func_iter is a basic rho updating iteration

    maxiter = 200
    scale_bias = 0.778465216
    
    def func_iter():
        s0 = rscale.mad(x, center=0)
        for i in range(maxiter):
            s = s0 * np.sqrt(1 / scale_bias / nobs * np.sum(rho(x / s0)))
            if np.allclose(s, s0, atol=1e-8, rtol=0):
                break
            s0 = s
            return s
    

    example data is chem with 24 observations.

  11. josef-pkt commented on May 3, 2024

    @josef-pkt
    MemberAuthor

    Huber proposal 2 (continued) #9171 (comment)
    I'm still finding conflicting explanations or expressions for proposal 2

    going back to the original
    Huber, Peter J. 1964. “Robust Estimation of a Location Parameter.” The Annals of Mathematical Statistics 35 (1): 73–101.

    proposal 2 is only for the huber norm, huber psi, winsorized variance case, p. 96

    1/ n * sum psi(k, (xi - T)/S) = 0
    1/ n * sum psi^2(k, (xi - T)/S) = E_F psi^2(k, x)

    that is chi = psi-squared

    where psi is equ (4) p. 94

    psi(q, t) = t            if |t| < q
              = q  * sign(t) if |t| >= q
    

    So, AFAICS, Huber did not have a generic derivation of chi.
    However, for the special case of huber psi function, several definitions all result in the same chi function.

    I still need to collect the different versions for how to define chi as, e.g., derived from a joint objective function for loc and scale.

  12. bashtage commented on Jul 30, 2026

    @bashtage
    Member

    Fixed in commit 8095bbc (ENH: add MScale class, fix RLM scale_est option, 2024-04-15), which corrected the callable scale_est call in RLM._estimate_scale and added the MScale class (PR #9210). Closing as fixed.

  13. added a commit that references this issue on Aug 25, 2026
    6808dde
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