Skip to content

formula: boolean endog, contingency table #878

Open

Description

@jankatins

I have two binary variables for which I want to see how they relate to each other, so I tried correlations and a simple regression and found the following error when I tried to get the regresison summary:

print df[["connection", "published"]].corr()

            connection  published
connection      1.0000     0.0335
published       0.0335     1.0000

res = sm.ols("published ~ connection", df).fit()
res.summary()


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-864f3205c5bd> in <module>()
----> 1 res.summary()

C:\portabel\Python27\lib\site-packages\statsmodels\regression\linear_model.pyc in summary(self, title, xname, yname, alpha, float_format)
   1198         jb, jbpv, skew, kurtosis = jarque_bera(self.wresid)
   1199         omni, omnipv = omni_normtest(self.wresid)
-> 1200         dw = durbin_watson(self.wresid)
   1201         condno = cond(self.model.wexog)
   1202         eigvals = eigvalsh(np.dot(self.model.wexog.T, self.model.wexog))

C:\portabel\Python27\lib\site-packages\statsmodels\stats\stattools.pyc in durbin_watson(resids)
     27     """
     28     diff_resids = np.diff(resids,1)
---> 29     dw = np.dot(diff_resids,diff_resids) / \
     30         np.dot(resids,resids);
     31     return dw

ValueError: matrices are not aligned

[Actually I would like to get some kind of contingency table and chi squared test, but up to now I haven't found how to do that in statsmodels]

Activity

  1. josef-pkt commented on Jun 19, 2013

    @josef-pkt
    Member

    Can you provide the data, or an artificial dataset that raises the same error?

    There is too little information to figure out what's going on, and I haven't seen an error in this part yet or in a while.
    This "should" work. What's the shape of your df?

    to contingency table:
    scipy.stats has a chisquare test for independence in contingency tables, and fisher_exact. There are some additional tests for proportion in the current master of statsmodels.
    There are a few more tests, like tests for marginal homogeneity.

    Note:if your published is binary, then you have a model that would be better analyzed with discrete Logit or Probit, or the corresponding GLM family.

  2. josef-pkt commented on Jun 19, 2013

    @josef-pkt
    Member

    my suspect was that formula converts endog to a 2-dimensional dummy variable.

    This happens if endog is an array of strings, but not if endog is an array of integers

    import numpy as np
    import statsmodels.api as sm
    import statsmodels.formula.api as smf
    
    nobs = 20
    x = np.repeat([0,1], [10, 10])
    y = np.random.randint(0, 2, nobs).astype(str)
    
    res = smf.ols("y ~ x", {'y':y, 'x':x}).fit()
    print res.model.endog
    
    >>> res.model.endog.shape
    (20, 2)
    >>> res.wresid.shape
    (20, 2)
    

    the simplest way, that I know, to convert string levels to integer levels is with np.unique

    >>> y
    array(['0', '1', '0', '0', '0', '1', '0', '0', '1', '1', '1', '0', '1',
           '0', '0', '0', '0', '1', '1', '1'], 
          dtype='|S1')
    >>> np.unique(y, return_inverse=True)[1]
    array([0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1])
    
  3. josef-pkt commented on Jun 19, 2013

    @josef-pkt
    Member

    I haven't looked at the OLS, Logit version before:

    For two sample test of proportion, using Logit, OLS, ..., the proportion tests should be almost the same in large samples. In small samples, discreteness (binomial), different transformations, whether t or normal/chisquare distribution is used, and the degrees of freedom will result in some differences.

  4. jankatins commented on Jun 19, 2013

    @jankatins
    ContributorAuthor

    Sorry, should have send that in the intial report:

    >>> df = df[["connection", "published"]].head()
    >>> df
      connection published
    0      False     False
    1      False     False
    2      False      True
    3      False     False
    4      False     False
    
    >>> type(df["connection"][1])
    numpy.bool_
    
    >>> res = sm.ols("published ~ connection", df).fit()
    >>> res.summary()
    # Same error as above
  5. jankatins commented on Jun 19, 2013

    @jankatins
    ContributorAuthor

    Re contingency table:

    So nothing like sm.xtabs("published ~ connection", df) exists yet, which would output per default a contingency table and a chi squared test result?

  6. josef-pkt commented on Jun 19, 2013

    @josef-pkt
    Member

    bool doesn't work, you need to convert your df to integers, astype(int)

    there is no xtabs is as a single step function, xtabs contingency table creation can be done with pandas (AFAIK), but the test statistics are in scipy.stats or statsmodels.

    I haven't looked at the contingency table class in scipy.stats recently, but IIRC it uses the count table as input.

    So, currently it's a two step process.

    related: mean of the booleans give you the proportion

    the statsmodels.stats functions take proportion and nobs.
    statsmodels.sourceforge.net/devel/generated/statsmodels.stats.proportion.proportions_chisquare.html

    I haven't yet thought much about a more user friendly interface for proportions.

    suggestions and pull requests are welcome.

  7. josef-pkt commented on Jun 19, 2013

    @josef-pkt
    Member

    did you mean this http://www.inside-r.org/packages/cran/prettyR/docs/xtab xtab in R?

    I'm not a user for these things and only know how to use numpy directly. It would be possible to add a formula based wrapper around pandas and the stats functions.

  8. jankatins commented on Jun 19, 2013

    @jankatins
    ContributorAuthor
  9. josef-pkt commented on Jun 19, 2013

    @josef-pkt
    Member

    I opened #879 (but I won't have time to work on it, especially the pandas and patsy parts which I don't know so well)

    From the statistical backend:
    We have many but not all tests that are in the SPSS description. Part of the work is to just collect them together as methods to a class and write some nice "summary()" tables.

    One question for the implementation is that 2x2, 2xk, 2x2xk and arbitrarily sized contingency tables will have different options/tests available, many tests are for 2x2 only, and some like chisquare or kendall_tau work for any contingency tables.

    2x2 and 2xk are largely covered by statsmodels.stats.proportions (once that has a wrapper/summary interface).

  10. jankatins commented on Jun 20, 2013

    @jankatins
    ContributorAuthor

    To continue on topic: I would vote that using a formula and bool/string-variables for the LHS catches such cases with a helpful error message ("Can't run regressions with bool on LHS: use '(%s)' in the formula" % offending_variable).

    Maybe add a new transformation in patsy like "as_int(...)" which would transform bool and strings (if a variable is string and has only two values) to int and error on all other cases?

    On the other hand, sometimes it's convenient to use factor levels as LHS...

  11. josef-pkt commented on Jul 27, 2013

    @josef-pkt
    Member

    renamed issue title from Error while computing durbin_watson

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions