Skip to content

Inconsistent behaviour of statsmodels.stats.weightstats.DescrStatsW #4797

Closed

Description

@jachymb

The code says all:

In [1]: DescrStatsW([1,1],weights=[1,1]).mean
Out[1]: 1.0

In [2]: DescrStatsW([1],weights=[1]).mean
Out[2]: array([1.])

Why an array is returned on the second time. It does not seem right.

Activity

  1. josef-pkt commented on Jul 14, 2018

    @josef-pkt
    Member

    There is no specific ndim/shape handling, squeeze or similar. The return shape is a consequence of the numpy behavior, specifically np.dot([1.], 1.) returns an array instead of scalar, at least in this version of numpy.

    >>> d1 = smw.DescrStatsW([1.],weights=[1.])
    >>> d1.sum
    array([ 1.])
    >>> d1.weights
    array(1.0)
    >>> d1.sum_weights
    1.0
    >>> d1.data
    array([ 1.])
    
    >>> np.dot([1.], 1.)
    array([ 1.])
    
    >>> np.__version__
    '1.11.2'
    
  2. josef-pkt commented on Jul 14, 2018

    @josef-pkt
    Member

    however, the __init__ removes extra dims

    if weights is None:
                self.weights = np.ones(self.data.shape[0])
            else:
                #why squeeze?
                self.weights = np.asarray(weights).squeeze().astype(float)
    

    I don't remember why squeeze. Most likely the squeeze should be removed.

  3. added this to the 0.10 milestone on Jul 14, 2018
  4. rhalbersma commented on Aug 20, 2020

    @rhalbersma

    Is there a fix for this? It's kind of annoying to special case N=1 in user-code.

  5. josef-pkt commented on Aug 20, 2020

    @josef-pkt
    Member

    N=1 is a special case, because variance cannot be computed.
    This needs unit test for N=1. I don't know what the behavior for statistic that involve var or std is. (zero division, nan, inf ?). Currently the behavior is just inherited as consequence of the standard computation.

    also behavior for different dimension of weights, if squeeze is removed.

    @rhalbersma what result statistics or methods are you using if N=1?

  6. josef-pkt commented on Aug 20, 2020

    @josef-pkt
    Member

    The squeeze is needed if we want to allow scalar 1. to allow for arbitrary shape weights.
    np.dot allows scalar multiplication, but checks shape if ndim > 0

    np.dot([1.], 1.), np.dot([1.], [1.])
    (array([1.]), 1.0)
    
    
    np.dot(np.ones((3, 4)), [1.])
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-487-2475bc4b8126> in <module>
    ----> 1 np.dot(np.ones((3, 4)), [1.])
    
    ValueError: shapes (3,4) and (1,) not aligned: 4 (dim 1) != 1 (dim 0)
    
    np.dot(np.ones((3, 4)), 1.)
    array([[1., 1., 1., 1.],
           [1., 1., 1., 1.],
           [1., 1., 1., 1.]])
    

    However, this is not the intended behavior, we need an inner product and not scalar multiplication.

    needs more checking and unit tests. (I don't remember the implementation details here)

  7. josef-pkt commented on Aug 20, 2020

    @josef-pkt
    Member

    aside naming inconsistency that I just saw:

    • 2 sample comparison in weightstats uses usevar='pooled'
    • I switched to use_var="equal" in oneway
  8. rhalbersma commented on Aug 20, 2020

    @rhalbersma

    @rhalbersma what result statistics or methods are you using if N=1?

    I just wanted sum and mean for N=1 and use them inside a print() statement. When applying a formatter, I get errors because the value is wrapped in an array. I'd expect just to get a scalar like for N > 1.

    Note that I'm not asking that all stats work for N=1, just that a well-behaved stat is returned as a scalar rather as an array of length 1.

    Edit: Just checked my code. I use DescrStatsW for a blackjack results tracker. I store the raw win/loss counts in a defaultdict and use data=list(dict.keys()) and weights=list(dict.values()). It's not just that I have to skip the first hand to get nobs > 1 in order to print out a running mean, I have to wait until I have both a win and a loss in order to get more than one different outcome.

  9. rhalbersma commented on Aug 20, 2020

    @rhalbersma

    I don't know what the behavior for statistic that involve var or std is. (zero division, nan, inf ?). Currently the behavior is just inherited as consequence of the standard computation.

    Sure, if there is a 1 / (nobs - 1) somewhere, users just receive an exception and can deal with that as they please.

  10. rhalbersma commented on Aug 21, 2020

    @rhalbersma

    The squeeze is needed if we want to allow scalar 1. to allow for arbitrary shape weights.

    But the documentation clearly says that weights is either None or a 1-D ndarray, so scalar or other arbitrary shape weights are not currently supported. Removing the squeeze in __init__ gives the correct scalar outcome from the np.dot for sum and mean even if nobs == 1.

  11. bashtage commented on Jul 30, 2026

    @bashtage
    Member

    Fixed by PR #7230, which only squeezes weights when they are genuinely multi-dimensional (statsmodels/stats/weightstats.py), fixing single-observation .mean returning an array instead of a scalar. A regression test (test_weightstats_len_1) was added for exactly this case. 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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions