Skip to content

Computing quantiles fails when shape of weights is (1,). #4282

Closed

Description

@ViralMehtaSWE
w = np.array([1])
data = np.array([1,2,3]).reshape((1,3))
assert(w.shape[0] == data.shape[0])
d1 = DescrStatsW(data, weights = w)
print(d1.quantile([0.5, 0.75], False))

Traceback (most recent call last):
  File "<pyshell#223>", line 1, in <module>
    print(d1.quantile([0.5, 0.75], False))
  File "C:\Users\t-vimeh\Downloads\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\statsmodels\stats\weightstats.py", line 283, in quantile
    rslt.append(self._quantile(vec, probs))
  File "C:\Users\t-vimeh\Downloads\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\statsmodels\stats\weightstats.py", line 303, in _quantile
    df = pd.DataFrame(index=np.arange(len(self.weights)))
TypeError: len() of unsized object

Activity

  1. changed the title [-]Computing quantiles fails when shape of weights is (1,1).[/-] [+]Computing quantiles fails when shape of weights is (1,).[/+] on Feb 28, 2018
  2. josef-pkt commented on Feb 28, 2018

    @josef-pkt
    Member

    @virmht Thanks for reporting.

    The current code doesn't support this, weights has to be either None or a length nobs array (after squeezing).

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

    if weights has only one value, then sum_weights would also raise, afaics. That would imply that not many methods work without raising an exception.

        def sum_weights(self):
            return self.weights.sum(0)
    

    We need at least some input checking, and raise immediately for not supported cases. And/or convert to usable weights.
    I'm not sure: What's the meaning of a scalar weights different from 1? In some other parts of statsmodels we expand it to w * np.ones(..))

  3. ViralMehtaSWE commented on Mar 1, 2018

    @ViralMehtaSWE
    Author

    Do you plan to add support for the same ? I am willing to raise a PR :)

  4. josef-pkt commented on Mar 1, 2018

    @josef-pkt
    Member

    I'm not sure yet about the various possible cases, e.g. when is it better to raise because the user made most likely a mistake.

    We need at least a few more, e.g. in __init__

        elif np.size(weights) == 1:
                self.weights = np.squeeze(weights) * np.ones(self.data.shape[0])
    ``
    which would handle all scalar and one element cases. 
    An alternative is to raise in this case if array.ndim > 0, i.e. only a accept scalar number for this
    Usage question: How did you end up with this case where weights is either 1-D or 2-D but only one element? Was this a mistake or a consequence of some usage code?
    
    and a len check after the if block:
    if len(self.weights) != nobs:
        raise ValueError(....)
    
  5. ViralMehtaSWE commented on Mar 2, 2018

    @ViralMehtaSWE
    Author

    It isnt a mistake. As per the documentation, it is mentioned that weights for each observation, should have same length as zero axis of data. Hence, it should work as expected.

  6. josef-pkt commented on Mar 2, 2018

    @josef-pkt
    Member

    Sorry, I didn't read your description carefully enough.
    The above problems with the current code still apply.

    However, there is the problem that your data has only a single observation. We always interpret observations in rows and different variables or data series in columns.
    It will not be possible to compute anything interesting with only one observation per series.

    Did you intend to have one data series with three observations or three series with one observations each?

  7. ViralMehtaSWE commented on Mar 2, 2018

    @ViralMehtaSWE
    Author

    My case was a much general case. It involved 2 D numpy arrays. In one of the cases, the 2D numpy array had just one row and statsmodels raised the above exception. I understand that my case is a very specific case. I wish to make changes in the statsmodels code so that it handles cases with just a single row of data successfully.

    By the way, I wish to contribute to Statamodels as part of Gsoc 2018. Can you suggest some task or bugfix ? May be this one as well.

    Please see my related post: #4285

    Thanks.

  8. josef-pkt commented on Mar 2, 2018

    @josef-pkt
    Member

    I wish to make changes in the statsmodels code so that it handles cases with just a single row of data successfully.

    The main problem here will be to decide what to do in every method, e.g. variance will raise or be nan. None of the hypothesis test related statistics will be valid, and end up with corner cases.
    I'm not sure what the quantiles should be if we only have one observation.

    The fix in __init__ would be to avoid the squeeze in this case, so that weights remains 1-D. However, that will just raise somewhere else or produce unverified numbers for the corner case.

    Related: I assume we also don't have unit tests for the case with two observations. In that case variance would be zero, and we would get division by zero problems, e.g. when computing a z-score.

    In general: AFAIK, we don't have yet a strict policy about what to do in cases when the sample size is too small, i.e. raise or warn and return nan/inf/... And in most cases we don't even have code yet to identify those cases.
    For the usecase of running the same function or computation over many samples, the preferred outcome are nans instead of exceptions.

  9. josef-pkt commented on Jan 21, 2021

    @josef-pkt
    Member

    fixed in #7230 which is rebased #7047

  10. added this to the 0.12 milestone on Jan 27, 2021
  11. modified the milestones: 0.12, 0.13 on Sep 9, 2021
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