Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
182 changes: 182 additions & 0 deletions statsmodels/regression/special_linear_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 22:31:14 2016

Author: Josef Perktold
License: BSD-3
"""

import numpy as np
from scipy import sparse
#import scipy.sparse.linalg as sparsela
import pandas as pd


from statsmodels.regression.linear_model import OLS, WLS
from statsmodels.tools._sparse import PartialingSparse, dummy_sparse

def cat2dummy_sparse(xcat, use_pandas=False):
"""categorical to sparse dummy, use pandas for quick implementation

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

outdated pandas, now version using sparse directly


xcat needs to be ndarray for now

use_pandas is currently only for testing purposes, it uses dense intermediat dummy
"""
# prepare np array for column iteration
if xcat.ndim == 1:
xcat_t = [xcat]
else:
xcat_t = xcat.T

if use_pandas:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

drop this, not needed anymore

dfs = [pd.get_dummies(xc) for xc in xcat_t]
x = np.column_stack(dfs)[:, 1:] # full rank
xsp = sparse.csc_matrix(x) #.astype(int)) # int breaks in LU-solve
else:
ds = [dummy_sparse(xc) for xc in xcat_t]
xsp = sparse.hstack(ds, format='csr')[:, 1:] # full rank

return xsp


def _group_demean_iterative(exog_dense, groups, add_mean=True, max_iter=10,
atol=1e-8):
"""iteratively demean an array for two-way fixed effects

This is intended for almost balanced panels. The data is converted
to a 3-dimensional array with nans for missing cells.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this still require that entire data can be represented as 2_D, i.e. unique 2column multi-index?
I guess so.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs pandas group-demean as alternative.


currently works only for two-way effects
groups have to be integers corresponding to range(k_cati)

no input error checking

This function will change as more options and special cases are
included.

Parameters
----------
exog_dense : 2d ndarray
data with observations in rows and variables in columns.
This array will currently not be modified.
groups : 2d ndarray, int
groups labels specified as consecutive integers starting at zero
add_mean : bool
If true (default), then the total variable means are added back into
the group demeand exog_dense
max_iter : int
maximum number of iterations
atol : float
tolerance for convergence. Convergence is achieved if the
maximum absolute change (np.ptp) is smaller than atol.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change of what?


Returns
-------
ex_dm_w : ndarray
group demeaned exog_dense array in wide format
ex_dm : ndarray
group demeaned exog_dense array in long format
it : int
number of iterations used. If convergence has not been
achieved then it will be equal to max_iter - 1

"""

# with unbalanced panel

k_cat = tuple((groups.max(0) + 1).tolist())
xm = np.empty(exog_dense.shape[1:] + k_cat)
xm.fill(np.nan)
xm[:, groups[:, 0], groups[:, 1]] = exog_dense.T
keep = ~np.isnan(xm[0]).ravel()
finished = False
for it in range(max_iter):
for axis in range(1, xm.ndim):
group_mean = np.nanmean(xm, axis=axis, keepdims=True)
xm -= group_mean
if np.ptp(group_mean) < atol:
finished = True
break
if finished:
break

xd = xm.reshape(exog_dense.shape[-1], -1).T[keep]
if add_mean:
xmean = exog_dense.mean(0)
xd += xmean
xm += xmean[:, None, None]
return xm, xd, it


class OLSAbsorb(WLS):
"""OLS model that absorbs categorical explanatory variables

see docstring for OLS, the following only has the extra parameters for now

Parameters
----------
exog_absorb : ndarray, 1D or 2D
categorical, factor variables that will be absorbed

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add if 2d, then observations in rows and factors in columns.

absorb_method : string, 'lu' or 'lmgres'
method used in projection for absorbing the factor variables.
Currently the options use either sparse LU decomposition or sparse
`lmgres`

Notes
-----
constant: the current parameterization produces a constant when the mean
categorical effect is set to zero

Warning: currently not all inherited methods for OLS are correct.
Parameters and inference are correct and correspond to the full model for
OLS that includes all factor variables as dummies with zero mean factor
effects.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add comment about predict, ... that differ from OLS, at least in this version
also untested robust cov_params, differences in HC2, HC3

"""

def __init__(self, endog, exog, exog_absorb, absorb_method='lu', **kwds):
# TODO: does exog_absorb need to be a keyword for from_formula ?
# TODO: missing handling and shape, type check for exog_absorb in super
absorb = cat2dummy_sparse(exog_absorb)
self.projector = PartialingSparse(absorb, method=absorb_method)
super(OLSAbsorb, self).__init__(endog, exog, **kwds)
# projection is in whiten

self.k_absorb = absorb.shape[1]
#self.df_resid -= self.k_absorb
# inline doesn't work, df_resid is property
self.df_resid = self.df_resid - self.k_absorb + 1
#check this, why + 1
self.df_model = self.df_model + self.k_absorb - 1


self.absorb = absorb # mainly for checking

def whiten(self, y):
# add the mean back in to get a constant
# this does not reproduce the constant if fixed effect use reference encoding
# It produces the constant if the mean fixed effect is zero
y_mean = y.mean(0)
return self.projector.partial_sparse(y)[1] + y_mean


def _get_fixed_effects(self, resid):
"""temporary: recover fixed effects from regression using residuals

Warning: This uses dense fixed effects dummies at the moment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this needs to use SparseOLS instead, but in the sparse case we should already have lu-factor or can use gmres


We add a constant to correct for constant in absorbed regression.
This will depend on the encoding of the absorb fixed effects.

Parameter
---------
resid : ndarray
residuals of absorbed OLS regression

"""

exog_dummies = np.column_stack((np.ones(len(self.endog)),
self.absorb.toarray()[:, :-1]))

# [:, :-1] is just because I used it in the example, drop again

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This uses dummy coding dropping last level/unit. Other options, e.g. sum to zero with singular design? or drop constant?


return OLS(resid, exog_dummies).fit()
176 changes: 176 additions & 0 deletions statsmodels/regression/tests/test_special_linear.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 23:39:45 2016

Author: Josef Perktold
License: BSD-3
"""

import numpy as np
from scipy import sparse
import pandas as pd

from statsmodels.regression.linear_model import OLS
from statsmodels.regression.special_linear_model import (
OLSAbsorb, _group_demean_iterative, cat2dummy_sparse)
from statsmodels.tools._sparse import PartialingSparse, dummy_sparse

from numpy.testing import assert_allclose

# COMPAT: for numpy <= 1.7 until we increase minimum
from statsmodels.compat.scipy import NumpyVersion
np_smaller_108 = True if (NumpyVersion(np.__version__) < '1.8.0') else False
from numpy.testing import dec
from nose import SkipTest


class CompareModels(object):

def test_attributes(self):
res1 = self.res1
res2 = self.res2
slice_res1 = self.slice_res1
slice_res2 = self.slice_res2

good = ['HC0_se', 'HC1_se', '_data_attr', 'aic', 'bic', 'bse',
'centered_tss', 'df_model', 'df_resid', 'ess', 'f_pvalue',
'fvalue', 'k_constant', 'llf', 'mse_model', 'mse_resid',
'mse_total', 'nobs', 'params', 'pvalues', 'resid_pearson',
'rsquared', 'rsquared_adj', 'scale', 'ssr', 'tvalues',
'use_t', 'wresid']

known_fails = ['HC2_se', 'HC3_se', '_wexog_singular_values',
'condition_number', 'eigenvals', 'fittedvalues',
'resid', 'uncentered_tss']

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need doc comment what predict does, and what fittedvalues and resid are. They don't take fixed effects into account ?


for a in good:
a2 = getattr(res2, a)
a1 = getattr(res1, a)
alen = getattr(a2, '__len__', lambda:0)()
if alen > 0 and not alen == len(a1):
a1 = a1[slice_res1]
a2 = a2[slice_res2]
err_msg = a
# resid_pearson fails at tol=1e-13
assert_allclose(a1, a2, atol=1e-12, rtol=1e-12, err_msg=err_msg)


class TestSparseAbsorb(CompareModels):

@classmethod
def setup_class(self):
#def generate_sample2():
xcat1 = np.repeat(np.arange(5), 10)
xcat2 = np.tile(np.arange(5), 10)
exog_absorb = np.column_stack((xcat1, xcat2))

df1 = pd.get_dummies(xcat1) #sparse=True) #sparse requires v 0.16
df2 = pd.get_dummies(xcat2)
x = np.column_stack((np.asarray(df1)[:, 1:], np.asarray(df2)))
exog = sparse.csc_matrix(x) #.astype(np.int8))
beta = 1. / np.r_[np.arange(1, df1.shape[1]), np.arange(1, df2.shape[1] + 1)]

np.random.seed(999)
betad = np.ones(3)
exogd = np.column_stack((np.ones(exog.shape[0]), np.random.randn(exog.shape[0], len(betad) - 1)))
y = exogd.dot(betad) + exog.dot(beta) + 0.01 * np.random.randn(exog.shape[0])

exog_full = np.column_stack((exogd, exog.toarray()))

res_ols = OLS(y, exog_full[:, :-1]).fit()
#print(res_ols.params)
#print(res_ols.bse)

mod_absorb = OLSAbsorb(y, exogd, exog_absorb)
res_absorb = mod_absorb.fit()
#print(res_absorb.params)
#print(res_absorb.bse)

# recover and check fixed effects parameters
res_fe = mod_absorb._get_fixed_effects(res_absorb.resid)
#print(res_fe.params[1:] - res_ols.params[3:])

# check constant, corresponds to mean prediction of absorbed factors and constant
#print(res_ols.predict(np.concatenate(([1, 0, 0], exog.toarray()[:,:-1].mean(0))))
# - res_absorb.params[0])
# same as res_absorb.predict([1, 0, 0])

self.slice_res1 = slice(1, 3, None)
self.slice_res2 = slice(1, 3, None)

self.res1 = res_absorb
self.res2 = res_ols

# keep as attributes
self.endog = y
self.exog_absorb = exog_absorb
self.exog_dense = exogd


def test_temp(self):
res1 = self.res1
res2 = self.res2
slice_res1 = self.slice_res1
slice_res2 = self.slice_res2

assert_allclose(res1.params[slice_res1], res2.params[slice_res2], rtol=1e-13)
assert_allclose(res1.bse[slice_res1], res2.bse[slice_res2], rtol=1e-13)
assert_allclose(res1.pvalues[slice_res1], res2.pvalues[slice_res2], rtol=1e-10)
#assert_allclose(res_fe.params[1:], res_ols.params[3:], rtol=1e-13)

# the following test currently fails (len(y) is 25 instead of 50
# the example is not a pure two-way effect
def t_est_demean(self):
exog_absorb = self.exog_absorb
exog_dense = self.exog_dense
endog = self.endog

xm, xd, it = _group_demean_iterative(exog_dense, exog_absorb,
add_mean=True, max_iter=50)
ym, yd, it = _group_demean_iterative(endog[:,None], exog_absorb,
add_mean=True, max_iter=50)
mod_ols2 = OLS(yd, xd)
k_cat = (exog_absorb.max(0) + 1)
ddof = k_cat - 2
mod_ols2.df_resid = mod_ols2.df_resid - ddof
mod_ols2.df_model = mod_ols2.df_model + ddof
res1 = mod_ols2.fit()
res2 = self.res1 # compare with sparse OLSAbsorb

assert_allclose(res1.params, res2.params, rtol=1e-13)
assert_allclose(res1.bse, res2.bse, rtol=1e-13)
assert_allclose(res1.pvalues, res2.pvalues, rtol=1e-10)


class TestAbsorb():

@classmethod
def setup_class(cls):
if np_smaller_108: raise SkipTest("numpy too old for nanmean")
# use decorator if we have more tests in here that need skipping
k_cat1, k_cat2 = 50, 10
k_vars = 3

np.random.seed(654)
keep = (np.random.rand(k_cat1 * k_cat2) > 0.1).astype(bool)

xcat1 = np.repeat(np.arange(k_cat1), k_cat2)[keep]
xcat2 = np.tile(np.arange(k_cat2), k_cat1)[keep]
exog_absorb = np.column_stack((xcat1, xcat2))
nobs = len(xcat1)
exog_dense = np.random.randn(nobs, k_vars)
xm, xd1, it = _group_demean_iterative(exog_dense, exog_absorb,
add_mean=True, max_iter=50)

absorb = cat2dummy_sparse(exog_absorb)
projector = PartialingSparse(absorb, method='lu')
exog_dense_mean = exog_dense.mean(0)
xd2 = projector.partial_sparse(exog_dense)[1] + exog_dense_mean

cls.res1 = xd1
cls.res2 = xd2

#@dec.skipif(np_smaller_108)
def test_absorb(self):
# Note: agreement (atol) depends on convergence tolerance
assert_allclose(self.res1, self.res2, atol=1e-9)
Loading