code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
182
url
stringlengths
46
251
license
stringclasses
4 values
def isInDomain(xy): """Used for filter to check if point is in the domain""" u = (xy[0]-x)/self.h return np.all((u >= self.domain[0]) & (u <= self.domain[1]))
Used for filter to check if point is in the domain
in_domain.isInDomain
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def in_domain(self, xs, ys, x): """ Returns the filtered (xs, ys) based on the Kernel domain centred on x """ # Disable black-list functions: filter used for speed instead of # list-comprehension # pylint: disable-msg=W0141 def isInDomain(xy): """Used for filter to check if point is in the domain""" u = (xy[0]-x)/self.h return np.all((u >= self.domain[0]) & (u <= self.domain[1])) if self.domain is None: return (xs, ys) else: filtered = lfilter(isInDomain, lzip(xs, ys)) if len(filtered) > 0: xs, ys = lzip(*filtered) return (xs, ys) else: return ([], [])
Returns the filtered (xs, ys) based on the Kernel domain centred on x
in_domain
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def density(self, xs, x): """Returns the kernel density estimate for point x based on x-values xs """ xs = np.asarray(xs) n = len(xs) # before in_domain? if self.weights is not None: xs, weights = self.in_domain( xs, self.weights, x ) else: xs = self.in_domain( xs, xs, x )[0] xs = np.asarray(xs) #print 'len(xs)', len(xs), x if xs.ndim == 1: xs = xs[:,None] if len(xs)>0: h = self.h if self.weights is not None: w = 1 / h * np.sum(self((xs-x)/h).T * weights, axis=1) else: w = 1. / (h * n) * np.sum(self((xs-x)/h), axis=0) return w else: return np.nan
Returns the kernel density estimate for point x based on x-values xs
density
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def density_var(self, density, nobs): """approximate pointwise variance for kernel density not verified Parameters ---------- density : array_lie pdf of the kernel density nobs : int number of observations used in the KDE estimation Returns ------- kde_var : ndarray estimated variance of the density estimate Notes ----- This uses the asymptotic normal approximation to the distribution of the density estimate. """ return np.asarray(density) * self.L2Norm / self.h / nobs
approximate pointwise variance for kernel density not verified Parameters ---------- density : array_lie pdf of the kernel density nobs : int number of observations used in the KDE estimation Returns ------- kde_var : ndarray estimated variance of the density estimate Notes ----- This uses the asymptotic normal approximation to the distribution of the density estimate.
density_var
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def density_confint(self, density, nobs, alpha=0.05): """approximate pointwise confidence interval for kernel density The confidence interval is centered at the estimated density and ignores the bias of the density estimate. not verified Parameters ---------- density : array_lie pdf of the kernel density nobs : int number of observations used in the KDE estimation Returns ------- conf_int : ndarray estimated confidence interval of the density estimate, lower bound in first column and upper bound in second column Notes ----- This uses the asymptotic normal approximation to the distribution of the density estimate. The lower bound can be negative for density values close to zero. """ from scipy import stats crit = stats.norm.isf(alpha / 2.) density = np.asarray(density) half_width = crit * np.sqrt(self.density_var(density, nobs)) conf_int = np.column_stack((density - half_width, density + half_width)) return conf_int
approximate pointwise confidence interval for kernel density The confidence interval is centered at the estimated density and ignores the bias of the density estimate. not verified Parameters ---------- density : array_lie pdf of the kernel density nobs : int number of observations used in the KDE estimation Returns ------- conf_int : ndarray estimated confidence interval of the density estimate, lower bound in first column and upper bound in second column Notes ----- This uses the asymptotic normal approximation to the distribution of the density estimate. The lower bound can be negative for density values close to zero.
density_confint
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def smooth(self, xs, ys, x): """Returns the kernel smoothing estimate for point x based on x-values xs and y-values ys. Not expected to be called by the user. """ xs, ys = self.in_domain(xs, ys, x) if len(xs)>0: w = np.sum(self((xs-x)/self.h)) #TODO: change the below to broadcasting when shape is sorted v = np.sum([yy*self((xx-x)/self.h) for xx, yy in zip(xs, ys)]) return v / w else: return np.nan
Returns the kernel smoothing estimate for point x based on x-values xs and y-values ys. Not expected to be called by the user.
smooth
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def smoothvar(self, xs, ys, x): """Returns the kernel smoothing estimate of the variance at point x. """ xs, ys = self.in_domain(xs, ys, x) if len(xs) > 0: fittedvals = np.array([self.smooth(xs, ys, xx) for xx in xs]) sqresid = square( subtract(ys, fittedvals) ) w = np.sum(self((xs-x)/self.h)) v = np.sum([rr*self((xx-x)/self.h) for xx, rr in zip(xs, sqresid)]) return v / w else: return np.nan
Returns the kernel smoothing estimate of the variance at point x.
smoothvar
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def smoothconf(self, xs, ys, x, alpha=0.05): """Returns the kernel smoothing estimate with confidence 1sigma bounds """ xs, ys = self.in_domain(xs, ys, x) if len(xs) > 0: fittedvals = np.array([self.smooth(xs, ys, xx) for xx in xs]) #fittedvals = self.smooth(xs, ys, x) # x or xs in Haerdle sqresid = square( subtract(ys, fittedvals) ) w = np.sum(self((xs-x)/self.h)) #var = sqresid.sum() / (len(sqresid) - 0) # nonlocal var ? JP just trying v = np.sum([rr*self((xx-x)/self.h) for xx, rr in zip(xs, sqresid)]) var = v / w sd = np.sqrt(var) K = self.L2Norm yhat = self.smooth(xs, ys, x) from scipy import stats crit = stats.norm.isf(alpha / 2) err = crit * sd * np.sqrt(K) / np.sqrt(w * self.h * self.norm_const) return (yhat - err, yhat, yhat + err) else: return (np.nan, np.nan, np.nan)
Returns the kernel smoothing estimate with confidence 1sigma bounds
smoothconf
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def L2Norm(self): """Returns the integral of the square of the kernal from -inf to inf""" if self._L2Norm is None: def L2Func(x): return (self.norm_const * self._shape(x)) ** 2 if self.domain is None: self._L2Norm = scipy.integrate.quad(L2Func, -inf, inf)[0] else: self._L2Norm = scipy.integrate.quad(L2Func, self.domain[0], self.domain[1])[0] return self._L2Norm
Returns the integral of the square of the kernal from -inf to inf
L2Norm
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def norm_const(self): """ Normalising constant for kernel (integral from -inf to inf) """ if self._normconst is None: if self.domain is None: quadres = scipy.integrate.quad(self._shape, -inf, inf) else: quadres = scipy.integrate.quad(self._shape, self.domain[0], self.domain[1]) self._normconst = 1.0/(quadres[0]) return self._normconst
Normalising constant for kernel (integral from -inf to inf)
norm_const
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def kernel_var(self): """Returns the second moment of the kernel""" if self._kernel_var is None: def func(x): return x ** 2 * self.norm_const * self._shape(x) if self.domain is None: self._kernel_var = scipy.integrate.quad(func, -inf, inf)[0] else: self._kernel_var = scipy.integrate.quad(func, self.domain[0], self.domain[1])[0] return self._kernel_var
Returns the second moment of the kernel
kernel_var
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def normal_reference_constant(self): """ Constant used for silverman normal reference asymtotic bandwidth calculation. C = 2((pi^(1/2)*(nu!)^3 R(k))/(2nu(2nu)!kap_nu(k)^2))^(1/(2nu+1)) nu = kernel order kap_nu = nu'th moment of kernel R = kernel roughness (square of L^2 norm) Note: L2Norm property returns square of norm. """ nu = self._order if not nu == 2: msg = "Only implemented for second order kernels" raise NotImplementedError(msg) if self._normal_reference_constant is None: C = np.pi**(.5) * factorial(nu)**3 * self.L2Norm C /= (2 * nu * factorial(2 * nu) * self.moments(nu)**2) C = 2*C**(1.0/(2*nu+1)) self._normal_reference_constant = C return self._normal_reference_constant
Constant used for silverman normal reference asymtotic bandwidth calculation. C = 2((pi^(1/2)*(nu!)^3 R(k))/(2nu(2nu)!kap_nu(k)^2))^(1/(2nu+1)) nu = kernel order kap_nu = nu'th moment of kernel R = kernel roughness (square of L^2 norm) Note: L2Norm property returns square of norm.
normal_reference_constant
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def weight(self, x): """This returns the normalised weight at distance x""" return self.norm_const*self._shape(x)
This returns the normalised weight at distance x
weight
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def smooth(self, xs, ys, x): """Returns the kernel smoothing estimate for point x based on x-values xs and y-values ys. Not expected to be called by the user. Special implementation optimized for Biweight. """ xs, ys = self.in_domain(xs, ys, x) if len(xs) > 0: w = np.sum(square(subtract(1, square(divide(subtract(xs, x), self.h))))) v = np.sum(multiply(ys, square(subtract(1, square(divide( subtract(xs, x), self.h)))))) return v / w else: return np.nan
Returns the kernel smoothing estimate for point x based on x-values xs and y-values ys. Not expected to be called by the user. Special implementation optimized for Biweight.
smooth
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def smooth(self, xs, ys, x): """Returns the kernel smoothing estimate for point x based on x-values xs and y-values ys. Not expected to be called by the user. Special implementation optimized for Gaussian. """ w = np.sum(exp(multiply(square(divide(subtract(xs, x), self.h)),-0.5))) v = np.sum(multiply(ys, exp(multiply(square(divide(subtract(xs, x), self.h)), -0.5)))) return v/w
Returns the kernel smoothing estimate for point x based on x-values xs and y-values ys. Not expected to be called by the user. Special implementation optimized for Gaussian.
smooth
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kernels.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kernels.py
BSD-3-Clause
def _compute_covariance_(self): '''not used''' self.inv_cov = np.linalg.inv(self.covariance) self._norm_factor = np.sqrt(np.linalg.det(2*np.pi*self.covariance)) * self.n
not used
_compute_covariance_
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/kdecovclass.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/kdecovclass.py
BSD-3-Clause
def predict(self, x): """ Returns the kernel smoothed prediction at x If x is a real number then a single value is returned. Otherwise an attempt is made to cast x to numpy.ndarray and an array of corresponding y-points is returned. """ if np.size(x) == 1: # if isinstance(x, numbers.Real): return self.Kernel.smooth(self.x, self.y, x) else: return np.array([self.Kernel.smooth(self.x, self.y, xx) for xx in np.array(x)])
Returns the kernel smoothed prediction at x If x is a real number then a single value is returned. Otherwise an attempt is made to cast x to numpy.ndarray and an array of corresponding y-points is returned.
predict
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/smoothers.py
BSD-3-Clause
def conf(self, x): """ Returns the fitted curve and 1-sigma upper and lower point-wise confidence. These bounds are based on variance only, and do not include the bias. If the bandwidth is much larger than the curvature of the underlying function then the bias could be large. x is the points on which you want to evaluate the fit and the errors. Alternatively if x is specified as a positive integer, then the fit and confidence bands points will be returned after every xth sample point - so they are closer together where the data is denser. """ if isinstance(x, int): sorted_x = np.sort(np.array(self.x)) confx = sorted_x[::x] conffit = self.conf(confx) return (confx, conffit) else: return np.array([self.Kernel.smoothconf(self.x, self.y, xx) for xx in x])
Returns the fitted curve and 1-sigma upper and lower point-wise confidence. These bounds are based on variance only, and do not include the bias. If the bandwidth is much larger than the curvature of the underlying function then the bias could be large. x is the points on which you want to evaluate the fit and the errors. Alternatively if x is specified as a positive integer, then the fit and confidence bands points will be returned after every xth sample point - so they are closer together where the data is denser.
conf
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/smoothers.py
BSD-3-Clause
def df_fit(self): '''alias of df_model for backwards compatibility ''' return self.df_model()
alias of df_model for backwards compatibility
df_fit
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/smoothers.py
BSD-3-Clause
def df_model(self): """ Degrees of freedom used in the fit. """ return self.order + 1
Degrees of freedom used in the fit.
df_model
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/smoothers.py
BSD-3-Clause
def smooth(self,*args, **kwds): '''alias for fit, for backwards compatibility, do we need it with different behavior than fit? ''' return self.fit(*args, **kwds)
alias for fit, for backwards compatibility, do we need it with different behavior than fit?
smooth
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/smoothers.py
BSD-3-Clause
def df_resid(self): """ Residual degrees of freedom from last fit. """ return self.N - self.order - 1
Residual degrees of freedom from last fit.
df_resid
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/smoothers.py
BSD-3-Clause
def fg1(x): '''Fan and Gijbels example function 1 ''' return x + 2 * np.exp(-16 * x**2)
Fan and Gijbels example function 1
fg1
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/dgp_examples.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/dgp_examples.py
BSD-3-Clause
def fg1eu(x): '''Eubank similar to Fan and Gijbels example function 1 ''' return x + 0.5 * np.exp(-50 * (x - 0.5)**2)
Eubank similar to Fan and Gijbels example function 1
fg1eu
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/dgp_examples.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/dgp_examples.py
BSD-3-Clause
def fg2(x): '''Fan and Gijbels example function 2 ''' return np.sin(2 * x) + 2 * np.exp(-16 * x**2)
Fan and Gijbels example function 2
fg2
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/dgp_examples.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/dgp_examples.py
BSD-3-Clause
def func1(x): '''made up example with sin, square ''' return np.sin(x * 5) / x + 2. * x - 1. * x**2
made up example with sin, square
func1
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/dgp_examples.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/dgp_examples.py
BSD-3-Clause
def plot(self, scatter=True, ax=None): '''plot the mean function and optionally the scatter of the sample Parameters ---------- scatter : bool If true, then add scatterpoints of sample to plot. ax : None or matplotlib axis instance If None, then a matplotlib.pyplot figure is created, otherwise the given axis, ax, is used. Returns ------- Figure This is either the created figure instance or the one associated with ax if ax is given. ''' if ax is None: import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) if scatter: ax.plot(self.x, self.y, 'o', alpha=0.5) xx = np.linspace(self.x.min(), self.x.max(), 100) ax.plot(xx, self.func(xx), lw=2, color='b', label='dgp mean') return ax.figure
plot the mean function and optionally the scatter of the sample Parameters ---------- scatter : bool If true, then add scatterpoints of sample to plot. ax : None or matplotlib axis instance If None, then a matplotlib.pyplot figure is created, otherwise the given axis, ax, is used. Returns ------- Figure This is either the created figure instance or the one associated with ax if ax is given.
plot
python
statsmodels/statsmodels
statsmodels/sandbox/nonparametric/dgp_examples.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/nonparametric/dgp_examples.py
BSD-3-Clause
def mcarma22(niter=10, nsample=1000, ar=None, ma=None, sig=0.5): '''run Monte Carlo for ARMA(2,2) DGP parameters currently hard coded also sample size `nsample` was not a self contained function, used instances from outer scope now corrected ''' #nsample = 1000 #ar = [1.0, 0, 0] if ar is None: ar = [1.0, -0.55, -0.1] #ma = [1.0, 0, 0] if ma is None: ma = [1.0, 0.3, 0.2] results = [] results_bse = [] for _ in range(niter): y2 = arma_generate_sample(ar,ma,nsample+1000, sig)[-nsample:] y2 -= y2.mean() arest2 = Arma(y2) rhohat2a, cov_x2a, infodict, mesg, ier = arest2.fit((2,2)) results.append(rhohat2a) err2a = arest2.geterrors(rhohat2a) sige2a = np.sqrt(np.dot(err2a,err2a)/nsample) #print('sige2a', sige2a, #print('cov_x2a.shape', cov_x2a.shape #results_bse.append(sige2a * np.sqrt(np.diag(cov_x2a))) if cov_x2a is not None: results_bse.append(sige2a * np.sqrt(np.diag(cov_x2a))) else: results_bse.append(np.nan + np.zeros_like(rhohat2a)) return np.r_[ar[1:], ma[1:]], np.array(results), np.array(results_bse)
run Monte Carlo for ARMA(2,2) DGP parameters currently hard coded also sample size `nsample` was not a self contained function, used instances from outer scope now corrected
mcarma22
python
statsmodels/statsmodels
statsmodels/sandbox/mcevaluate/arma.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/mcevaluate/arma.py
BSD-3-Clause
def __init__(self, n): """ Leave-One-Out cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4]] >>> y = [1, 2] >>> loo = cross_val.LeaveOneOut(2) >>> for train_index, test_index in loo: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) ... print X_train, X_test, y_train, y_test TRAIN: [False True] TEST: [ True False] [[3 4]] [[1 2]] [2] [1] TRAIN: [ True False] TEST: [False True] [[1 2]] [[3 4]] [1] [2] """ self.n = n
Leave-One-Out cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4]] >>> y = [1, 2] >>> loo = cross_val.LeaveOneOut(2) >>> for train_index, test_index in loo: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) ... print X_train, X_test, y_train, y_test TRAIN: [False True] TEST: [ True False] [[3 4]] [[1 2]] [2] [1] TRAIN: [ True False] TEST: [False True] [[1 2]] [[3 4]] [1] [2]
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/tools/cross_val.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/cross_val.py
BSD-3-Clause
def __init__(self, n, p): """ Leave-P-Out cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements p: int Size test sets Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4], [5, 6], [7, 8]] >>> y = [1, 2, 3, 4] >>> lpo = cross_val.LeavePOut(4, 2) >>> for train_index, test_index in lpo: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) TRAIN: [False False True True] TEST: [ True True False False] TRAIN: [False True False True] TEST: [ True False True False] TRAIN: [False True True False] TEST: [ True False False True] TRAIN: [ True False False True] TEST: [False True True False] TRAIN: [ True False True False] TEST: [False True False True] TRAIN: [ True True False False] TEST: [False False True True] """ self.n = n self.p = p
Leave-P-Out cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements p: int Size test sets Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4], [5, 6], [7, 8]] >>> y = [1, 2, 3, 4] >>> lpo = cross_val.LeavePOut(4, 2) >>> for train_index, test_index in lpo: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) TRAIN: [False False True True] TEST: [ True True False False] TRAIN: [False True False True] TEST: [ True False True False] TRAIN: [False True True False] TEST: [ True False False True] TRAIN: [ True False False True] TEST: [False True True False] TRAIN: [ True False True False] TEST: [False True False True] TRAIN: [ True True False False] TEST: [False False True True]
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/tools/cross_val.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/cross_val.py
BSD-3-Clause
def __init__(self, n, k): """ K-Folds cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements k: int number of folds Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4], [1, 2], [3, 4]] >>> y = [1, 2, 3, 4] >>> kf = cross_val.KFold(4, k=2) >>> for train_index, test_index in kf: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) TRAIN: [False False True True] TEST: [ True True False False] TRAIN: [ True True False False] TEST: [False False True True] Notes ----- All the folds have size trunc(n/k), the last one has the complementary """ assert k>0, ValueError('cannot have k below 1') assert k<n, ValueError('cannot have k=%d greater than %d'% (k, n)) self.n = n self.k = k
K-Folds cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements k: int number of folds Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4], [1, 2], [3, 4]] >>> y = [1, 2, 3, 4] >>> kf = cross_val.KFold(4, k=2) >>> for train_index, test_index in kf: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) TRAIN: [False False True True] TEST: [ True True False False] TRAIN: [ True True False False] TEST: [False False True True] Notes ----- All the folds have size trunc(n/k), the last one has the complementary
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/tools/cross_val.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/cross_val.py
BSD-3-Clause
def __init__(self, labels): """ Leave-One-Label_Out cross validation: Provides train/test indexes to split data in train test sets Parameters ---------- labels : list List of labels Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4], [5, 6], [7, 8]] >>> y = [1, 2, 1, 2] >>> labels = [1, 1, 2, 2] >>> lol = cross_val.LeaveOneLabelOut(labels) >>> for train_index, test_index in lol: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, \ test_index, X, y) ... print X_train, X_test, y_train, y_test TRAIN: [False False True True] TEST: [ True True False False] [[5 6] [7 8]] [[1 2] [3 4]] [1 2] [1 2] TRAIN: [ True True False False] TEST: [False False True True] [[1 2] [3 4]] [[5 6] [7 8]] [1 2] [1 2] """ self.labels = labels
Leave-One-Label_Out cross validation: Provides train/test indexes to split data in train test sets Parameters ---------- labels : list List of labels Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4], [5, 6], [7, 8]] >>> y = [1, 2, 1, 2] >>> labels = [1, 1, 2, 2] >>> lol = cross_val.LeaveOneLabelOut(labels) >>> for train_index, test_index in lol: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, \ test_index, X, y) ... print X_train, X_test, y_train, y_test TRAIN: [False False True True] TEST: [ True True False False] [[5 6] [7 8]] [[1 2] [3 4]] [1 2] [1 2] TRAIN: [ True True False False] TEST: [False False True True] [[1 2] [3 4]] [[5 6] [7 8]] [1 2] [1 2]
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/tools/cross_val.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/cross_val.py
BSD-3-Clause
def split(train_indexes, test_indexes, *args): """ For each arg return a train and test subsets defined by indexes provided in train_indexes and test_indexes """ ret = [] for arg in args: arg = np.asanyarray(arg) arg_train = arg[train_indexes] arg_test = arg[test_indexes] ret.append(arg_train) ret.append(arg_test) return ret
For each arg return a train and test subsets defined by indexes provided in train_indexes and test_indexes
split
python
statsmodels/statsmodels
statsmodels/sandbox/tools/cross_val.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/cross_val.py
BSD-3-Clause
def __init__(self, n, k=1, start=None, kall=True, return_slice=True): """ KStepAhead cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements k : int number of steps ahead start : int initial size of data for fitting kall : bool if true. all values for up to k-step ahead are included in the test index. If false, then only the k-th step ahead value is returnd Notes ----- I do not think this is really useful, because it can be done with a very simple loop instead. Useful as a plugin, but it could return slices instead for faster array access. Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4]] >>> y = [1, 2] >>> loo = cross_val.LeaveOneOut(2) >>> for train_index, test_index in loo: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) ... print X_train, X_test, y_train, y_test TRAIN: [False True] TEST: [ True False] [[3 4]] [[1 2]] [2] [1] TRAIN: [ True False] TEST: [False True] [[1 2]] [[3 4]] [1] [2] """ self.n = n self.k = k if start is None: start = int(np.trunc(n*0.25)) # pick something arbitrary self.start = start self.kall = kall self.return_slice = return_slice
KStepAhead cross validation iterator: Provides train/test indexes to split data in train test sets Parameters ---------- n: int Total number of elements k : int number of steps ahead start : int initial size of data for fitting kall : bool if true. all values for up to k-step ahead are included in the test index. If false, then only the k-th step ahead value is returnd Notes ----- I do not think this is really useful, because it can be done with a very simple loop instead. Useful as a plugin, but it could return slices instead for faster array access. Examples -------- >>> from scikits.learn import cross_val >>> X = [[1, 2], [3, 4]] >>> y = [1, 2] >>> loo = cross_val.LeaveOneOut(2) >>> for train_index, test_index in loo: ... print "TRAIN:", train_index, "TEST:", test_index ... X_train, X_test, y_train, y_test = cross_val.split(train_index, test_index, X, y) ... print X_train, X_test, y_train, y_test TRAIN: [False True] TEST: [ True False] [[3 4]] [[1 2]] [2] [1] TRAIN: [ True False] TEST: [False True] [[1 2]] [[3 4]] [1] [2]
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/tools/cross_val.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/cross_val.py
BSD-3-Clause
def pca(data, keepdim=0, normalize=0, demean=True): '''principal components with eigenvector decomposition similar to princomp in matlab Parameters ---------- data : ndarray, 2d data with observations by rows and variables in columns keepdim : int number of eigenvectors to keep if keepdim is zero, then all eigenvectors are included normalize : bool if true, then eigenvectors are normalized by sqrt of eigenvalues demean : bool if true, then the column mean is subtracted from the data Returns ------- xreduced : ndarray, 2d, (nobs, nvars) projection of the data x on the kept eigenvectors factors : ndarray, 2d, (nobs, nfactors) factor matrix, given by np.dot(x, evecs) evals : ndarray, 2d, (nobs, nfactors) eigenvalues evecs : ndarray, 2d, (nobs, nfactors) eigenvectors, normalized if normalize is true Notes ----- See Also -------- pcasvd : principal component analysis using svd ''' x = np.array(data) #make copy so original does not change, maybe not necessary anymore if demean: m = x.mean(0) else: m = np.zeros(x.shape[1]) x -= m # Covariance matrix xcov = np.cov(x, rowvar=0) # Compute eigenvalues and sort into descending order evals, evecs = np.linalg.eig(xcov) indices = np.argsort(evals) indices = indices[::-1] evecs = evecs[:,indices] evals = evals[indices] if keepdim > 0 and keepdim < x.shape[1]: evecs = evecs[:,:keepdim] evals = evals[:keepdim] if normalize: #for i in range(shape(evecs)[1]): # evecs[:,i] / linalg.norm(evecs[:,i]) * sqrt(evals[i]) evecs = evecs/np.sqrt(evals) #np.sqrt(np.dot(evecs.T, evecs) * evals) # get factor matrix #x = np.dot(evecs.T, x.T) factors = np.dot(x, evecs) # get original data from reduced number of components #xreduced = np.dot(evecs.T, factors) + m #print x.shape, factors.shape, evecs.shape, m.shape xreduced = np.dot(factors, evecs.T) + m return xreduced, factors, evals, evecs
principal components with eigenvector decomposition similar to princomp in matlab Parameters ---------- data : ndarray, 2d data with observations by rows and variables in columns keepdim : int number of eigenvectors to keep if keepdim is zero, then all eigenvectors are included normalize : bool if true, then eigenvectors are normalized by sqrt of eigenvalues demean : bool if true, then the column mean is subtracted from the data Returns ------- xreduced : ndarray, 2d, (nobs, nvars) projection of the data x on the kept eigenvectors factors : ndarray, 2d, (nobs, nfactors) factor matrix, given by np.dot(x, evecs) evals : ndarray, 2d, (nobs, nfactors) eigenvalues evecs : ndarray, 2d, (nobs, nfactors) eigenvectors, normalized if normalize is true Notes ----- See Also -------- pcasvd : principal component analysis using svd
pca
python
statsmodels/statsmodels
statsmodels/sandbox/tools/tools_pca.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/tools_pca.py
BSD-3-Clause
def pcasvd(data, keepdim=0, demean=True): '''principal components with svd Parameters ---------- data : ndarray, 2d data with observations by rows and variables in columns keepdim : int number of eigenvectors to keep if keepdim is zero, then all eigenvectors are included demean : bool if true, then the column mean is subtracted from the data Returns ------- xreduced : ndarray, 2d, (nobs, nvars) projection of the data x on the kept eigenvectors factors : ndarray, 2d, (nobs, nfactors) factor matrix, given by np.dot(x, evecs) evals : ndarray, 2d, (nobs, nfactors) eigenvalues evecs : ndarray, 2d, (nobs, nfactors) eigenvectors, normalized if normalize is true See Also -------- pca : principal component analysis using eigenvector decomposition Notes ----- This does not have yet the normalize option of pca. ''' nobs, nvars = data.shape #print nobs, nvars, keepdim x = np.array(data) #make copy so original does not change if demean: m = x.mean(0) else: m = 0 ## if keepdim == 0: ## keepdim = nvars ## "print reassigning keepdim to max", keepdim x -= m U, s, v = np.linalg.svd(x.T, full_matrices=1) factors = np.dot(U.T, x.T).T #princomps if keepdim: xreduced = np.dot(factors[:,:keepdim], U[:,:keepdim].T) + m else: xreduced = data keepdim = nvars "print reassigning keepdim to max", keepdim # s = evals, U = evecs # no idea why denominator for s is with minus 1 evals = s**2/(x.shape[0]-1) #print keepdim return xreduced, factors[:,:keepdim], evals[:keepdim], U[:,:keepdim] #, v
principal components with svd Parameters ---------- data : ndarray, 2d data with observations by rows and variables in columns keepdim : int number of eigenvectors to keep if keepdim is zero, then all eigenvectors are included demean : bool if true, then the column mean is subtracted from the data Returns ------- xreduced : ndarray, 2d, (nobs, nvars) projection of the data x on the kept eigenvectors factors : ndarray, 2d, (nobs, nfactors) factor matrix, given by np.dot(x, evecs) evals : ndarray, 2d, (nobs, nfactors) eigenvalues evecs : ndarray, 2d, (nobs, nfactors) eigenvectors, normalized if normalize is true See Also -------- pca : principal component analysis using eigenvector decomposition Notes ----- This does not have yet the normalize option of pca.
pcasvd
python
statsmodels/statsmodels
statsmodels/sandbox/tools/tools_pca.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/tools_pca.py
BSD-3-Clause
def run(self, nrepl, statindices=None, dgpargs=[], statsargs=[]): '''run the actual Monte Carlo and save results Parameters ---------- nrepl : int number of Monte Carlo repetitions statindices : None or list of integers determines which values of the return of the statistic functions are stored in the Monte Carlo. Default None means the entire return. If statindices is a list of integers, then it will be used as index into the return. dgpargs : tuple optional parameters for the DGP statsargs : tuple optional parameters for the statistics function Returns ------- None, all results are attached ''' self.nrepl = nrepl self.statindices = statindices self.dgpargs = dgpargs self.statsargs = statsargs dgp = self.dgp statfun = self.statistic # name ? #introspect len of return of statfun, #possible problems with ndim>1, check ValueError mcres0 = statfun(dgp(*dgpargs), *statsargs) self.nreturn = nreturns = len(np.ravel(mcres0)) #single return statistic if statindices is None: #self.nreturn = nreturns = 1 mcres = np.zeros(nrepl) mcres[0] = mcres0 for ii in range(1, nrepl-1, nreturns): x = dgp(*dgpargs) #(1e-4+np.random.randn(nobs)).cumsum() #should I ravel? mcres[ii] = statfun(x, *statsargs) #more than one return statistic else: self.nreturn = nreturns = len(statindices) self.mcres = mcres = np.zeros((nrepl, nreturns)) mcres[0] = [mcres0[i] for i in statindices] for ii in range(1, nrepl-1): x = dgp(*dgpargs) #(1e-4+np.random.randn(nobs)).cumsum() ret = statfun(x, *statsargs) mcres[ii] = [ret[i] for i in statindices] self.mcres = mcres
run the actual Monte Carlo and save results Parameters ---------- nrepl : int number of Monte Carlo repetitions statindices : None or list of integers determines which values of the return of the statistic functions are stored in the Monte Carlo. Default None means the entire return. If statindices is a list of integers, then it will be used as index into the return. dgpargs : tuple optional parameters for the DGP statsargs : tuple optional parameters for the statistics function Returns ------- None, all results are attached
run
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def histogram(self, idx=None, critval=None): '''calculate histogram values does not do any plotting I do not remember what I wanted here, looks similar to the new cdf method, but this also does a binned pdf (self.histo) ''' if self.mcres.ndim == 2: if idx is not None: mcres = self.mcres[:,idx] else: raise ValueError('currently only 1 statistic at a time') else: mcres = self.mcres if critval is None: histo = np.histogram(mcres, bins=10) else: if not critval[0] == -np.inf: bins=np.r_[-np.inf, critval, np.inf] if not critval[0] == -np.inf: bins=np.r_[bins, np.inf] histo = np.histogram(mcres, bins=np.r_[-np.inf, critval, np.inf]) self.histo = histo self.cumhisto = np.cumsum(histo[0])*1./self.nrepl self.cumhistoreversed = np.cumsum(histo[0][::-1])[::-1]*1./self.nrepl return histo, self.cumhisto, self.cumhistoreversed
calculate histogram values does not do any plotting I do not remember what I wanted here, looks similar to the new cdf method, but this also does a binned pdf (self.histo)
histogram
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def quantiles(self, idx=None, frac=[0.01, 0.025, 0.05, 0.1, 0.975]): '''calculate quantiles of Monte Carlo results similar to ppf Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation frac : array_like, float Defines which quantiles should be calculated. For example a frac of 0.1 finds the 10% quantile, x such that cdf(x)=0.1 Returns ------- frac : ndarray same values as input, TODO: I should drop this again ? quantiles : ndarray, (len(frac), len(idx)) the quantiles with frac in rows and idx variables in columns Notes ----- rename to ppf ? make frac required change sequence idx, frac ''' if self.mcres.ndim == 2: if idx is not None: self.mcres[:,idx] else: raise ValueError('currently only 1 statistic at a time') else: pass self.frac = frac = np.asarray(frac) mc_sorted = self.get_mc_sorted()[:,idx] return frac, mc_sorted[(self.nrepl*frac).astype(int)]
calculate quantiles of Monte Carlo results similar to ppf Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation frac : array_like, float Defines which quantiles should be calculated. For example a frac of 0.1 finds the 10% quantile, x such that cdf(x)=0.1 Returns ------- frac : ndarray same values as input, TODO: I should drop this again ? quantiles : ndarray, (len(frac), len(idx)) the quantiles with frac in rows and idx variables in columns Notes ----- rename to ppf ? make frac required change sequence idx, frac
quantiles
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def cdf(self, x, idx=None): '''calculate cumulative probabilities of Monte Carlo results Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation frac : array_like, float Defines which quantiles should be calculated. For example a frac of 0.1 finds the 10% quantile, x such that cdf(x)=0.1 Returns ------- x : ndarray same as input, TODO: I should drop this again ? probs : ndarray, (len(x), len(idx)) the quantiles with frac in rows and idx variables in columns ''' idx = np.atleast_1d(idx).tolist() #assure iterable, use list ? # if self.mcres.ndim == 2: # if not idx is None: # mcres = self.mcres[:,idx] # else: # raise ValueError('currently only 1 statistic at a time') # else: # mcres = self.mcres mc_sorted = self.get_mc_sorted() x = np.asarray(x) #TODO:autodetect or explicit option ? if x.ndim > 1 and x.shape[1]==len(idx): use_xi = True else: use_xi = False x_ = x #alias probs = [] for i,ix in enumerate(idx): if use_xi: x_ = x[:,i] probs.append(np.searchsorted(mc_sorted[:,ix], x_)/float(self.nrepl)) probs = np.asarray(probs).T return x, probs
calculate cumulative probabilities of Monte Carlo results Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation frac : array_like, float Defines which quantiles should be calculated. For example a frac of 0.1 finds the 10% quantile, x such that cdf(x)=0.1 Returns ------- x : ndarray same as input, TODO: I should drop this again ? probs : ndarray, (len(x), len(idx)) the quantiles with frac in rows and idx variables in columns
cdf
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def plot_hist(self, idx, distpdf=None, bins=50, ax=None, kwds=None): '''plot the histogram against a reference distribution Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation distpdf : callable probability density function of reference distribution bins : {int, array_like} used unchanged for matplotlibs hist call ax : TODO: not implemented yet kwds : None or tuple of dicts extra keyword options to the calls to the matplotlib functions, first dictionary is for his, second dictionary for plot of the reference distribution Returns ------- None ''' if kwds is None: kwds = ({},{}) if self.mcres.ndim == 2: if idx is not None: mcres = self.mcres[:,idx] else: raise ValueError('currently only 1 statistic at a time') else: mcres = self.mcres lsp = np.linspace(mcres.min(), mcres.max(), 100) import matplotlib.pyplot as plt #I do not want to figure this out now # if ax=None: # fig = plt.figure() # ax = fig.addaxis() plt.figure() plt.hist(mcres, bins=bins, normed=True, **kwds[0]) plt.plot(lsp, distpdf(lsp), 'r', **kwds[1])
plot the histogram against a reference distribution Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation distpdf : callable probability density function of reference distribution bins : {int, array_like} used unchanged for matplotlibs hist call ax : TODO: not implemented yet kwds : None or tuple of dicts extra keyword options to the calls to the matplotlib functions, first dictionary is for his, second dictionary for plot of the reference distribution Returns ------- None
plot_hist
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def summary_quantiles(self, idx, distppf, frac=[0.01, 0.025, 0.05, 0.1, 0.975], varnames=None, title=None): '''summary table for quantiles (critical values) Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation distppf : callable probability density function of reference distribution TODO: use `crit` values instead or additional, see summary_cdf frac : array_like, float probabilities for which varnames : None, or list of strings optional list of variable names, same length as idx Returns ------- table : instance of SimpleTable use `print(table` to see results ''' idx = np.atleast_1d(idx) #assure iterable, use list ? quant, mcq = self.quantiles(idx, frac=frac) #not sure whether this will work with single quantile #crit = stats.chi2([2,4]).ppf(np.atleast_2d(quant).T) crit = distppf(np.atleast_2d(quant).T) mml=[] for i, ix in enumerate(idx): #TODO: hardcoded 2 ? mml.extend([mcq[:,i], crit[:,i]]) #mmlar = np.column_stack(mml) mmlar = np.column_stack([quant] + mml) #print(mmlar.shape if title: title = title +' Quantiles (critical values)' else: title='Quantiles (critical values)' #TODO use stub instead if varnames is None: varnames = ['var%d' % i for i in range(mmlar.shape[1]//2)] headers = ['\nprob'] + [f'{i}\n{t}' for i in varnames for t in ['mc', 'dist']] return SimpleTable(mmlar, txt_fmt={'data_fmts': ["%#6.3f"]+["%#10.4f"]*(mmlar.shape[1]-1)}, title=title, headers=headers)
summary table for quantiles (critical values) Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation distppf : callable probability density function of reference distribution TODO: use `crit` values instead or additional, see summary_cdf frac : array_like, float probabilities for which varnames : None, or list of strings optional list of variable names, same length as idx Returns ------- table : instance of SimpleTable use `print(table` to see results
summary_quantiles
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def summary_cdf(self, idx, frac, crit, varnames=None, title=None): '''summary table for cumulative density function Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation frac : array_like, float probabilities for which crit : array_like values for which cdf is calculated varnames : None, or list of strings optional list of variable names, same length as idx Returns ------- table : instance of SimpleTable use `print(table` to see results ''' idx = np.atleast_1d(idx) #assure iterable, use list ? mml=[] #TODO:need broadcasting in cdf for i in range(len(idx)): #print(i, mc1.cdf(crit[:,i], [idx[i]])[1].ravel() mml.append(self.cdf(crit[:,i], [idx[i]])[1].ravel()) #mml = self.cdf(crit, idx)[1] #mmlar = np.column_stack(mml) #print(mml[0].shape, np.shape(frac) mmlar = np.column_stack([frac] + mml) #print(mmlar.shape if title: title = title +' Probabilites' else: title='Probabilities' #TODO use stub instead #headers = ['\nprob'] + ['var%d\n%s' % (i, t) for i in range(mmlar.shape[1]-1) for t in ['mc']] if varnames is None: varnames = ['var%d' % i for i in range(mmlar.shape[1]-1)] headers = ['prob'] + varnames return SimpleTable(mmlar, txt_fmt={'data_fmts': ["%#6.3f"]+["%#10.4f"]*(np.array(mml).shape[1]-1)}, title=title, headers=headers)
summary table for cumulative density function Parameters ---------- idx : None or list of integers List of indices into the Monte Carlo results (columns) that should be used in the calculation frac : array_like, float probabilities for which crit : array_like values for which cdf is calculated varnames : None, or list of strings optional list of variable names, same length as idx Returns ------- table : instance of SimpleTable use `print(table` to see results
summary_cdf
python
statsmodels/statsmodels
statsmodels/sandbox/tools/mctools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/tools/mctools.py
BSD-3-Clause
def contrast_allpairs(nm): '''contrast or restriction matrix for all pairs of nm variables Parameters ---------- nm : int Returns ------- contr : ndarray, 2d, (nm*(nm-1)/2, nm) contrast matrix for all pairwise comparisons ''' contr = [] for i in range(nm): for j in range(i+1, nm): contr_row = np.zeros(nm) contr_row[i] = 1 contr_row[j] = -1 contr.append(contr_row) return np.array(contr)
contrast or restriction matrix for all pairs of nm variables Parameters ---------- nm : int Returns ------- contr : ndarray, 2d, (nm*(nm-1)/2, nm) contrast matrix for all pairwise comparisons
contrast_allpairs
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def contrast_all_one(nm): '''contrast or restriction matrix for all against first comparison Parameters ---------- nm : int Returns ------- contr : ndarray, 2d, (nm-1, nm) contrast matrix for all against first comparisons ''' contr = np.column_stack((np.ones(nm-1), -np.eye(nm-1))) return contr
contrast or restriction matrix for all against first comparison Parameters ---------- nm : int Returns ------- contr : ndarray, 2d, (nm-1, nm) contrast matrix for all against first comparisons
contrast_all_one
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def contrast_diff_mean(nm): '''contrast or restriction matrix for all against mean comparison Parameters ---------- nm : int Returns ------- contr : ndarray, 2d, (nm-1, nm) contrast matrix for all against mean comparisons ''' return np.eye(nm) - np.ones((nm,nm))/nm
contrast or restriction matrix for all against mean comparison Parameters ---------- nm : int Returns ------- contr : ndarray, 2d, (nm-1, nm) contrast matrix for all against mean comparisons
contrast_diff_mean
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def contrast_product(names1, names2, intgroup1=None, intgroup2=None, pairs=False): '''build contrast matrices for products of two categorical variables this is an experimental script and should be converted to a class Parameters ---------- names1, names2 : lists of strings contains the list of level labels for each categorical variable intgroup1, intgroup2 : ndarrays TODO: this part not tested, finished yet categorical variable Notes ----- This creates a full rank matrix. It does not do all pairwise comparisons, parameterization is using contrast_all_one to get differences with first level. ? does contrast_all_pairs work as a plugin to get all pairs ? ''' n1 = len(names1) n2 = len(names2) names_prod = [f'{i}_{j}' for i in names1 for j in names2] ee1 = np.zeros((1,n1)) ee1[0,0] = 1 if not pairs: dd = np.r_[ee1, -contrast_all_one(n1)] else: dd = np.r_[ee1, -contrast_allpairs(n1)] contrast_prod = np.kron(dd[1:], np.eye(n2)) contrast_labels(contrast_prod, names_prod, reverse=True) names_contrast_prod = [''.join([f'{signstr(c, noplus=True)}{v}' for c,v in zip(row, names_prod)[::-1] if c != 0]) for row in contrast_prod] ee2 = np.zeros((1,n2)) ee2[0,0] = 1 #dd2 = np.r_[ee2, -contrast_all_one(n2)] if not pairs: dd2 = np.r_[ee2, -contrast_all_one(n2)] else: dd2 = np.r_[ee2, -contrast_allpairs(n2)] contrast_prod2 = np.kron(np.eye(n1), dd2[1:]) names_contrast_prod2 = [''.join([f'{signstr(c, noplus=True)}{v}' for c,v in zip(row, names_prod)[::-1] if c != 0]) for row in contrast_prod2] if (intgroup1 is not None) and (intgroup1 is not None): d1, _ = dummy_1d(intgroup1) d2, _ = dummy_1d(intgroup2) dummy = dummy_product(d1, d2) else: dummy = None return (names_prod, contrast_prod, names_contrast_prod, contrast_prod2, names_contrast_prod2, dummy)
build contrast matrices for products of two categorical variables this is an experimental script and should be converted to a class Parameters ---------- names1, names2 : lists of strings contains the list of level labels for each categorical variable intgroup1, intgroup2 : ndarrays TODO: this part not tested, finished yet categorical variable Notes ----- This creates a full rank matrix. It does not do all pairwise comparisons, parameterization is using contrast_all_one to get differences with first level. ? does contrast_all_pairs work as a plugin to get all pairs ?
contrast_product
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def dummy_1d(x, varname=None): '''dummy variable for id integer groups Parameters ---------- x : ndarray, 1d categorical variable, requires integers if varname is None varname : str name of the variable used in labels for category levels Returns ------- dummy : ndarray, 2d array of dummy variables, one column for each level of the category (full set) labels : list[str] labels for the columns, i.e. levels of each category Notes ----- use tools.categorical instead for more more options See Also -------- statsmodels.tools.categorical Examples -------- >>> x = np.array(['F', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'M', 'M'], dtype='|S1') >>> dummy_1d(x, varname='gender') (array([[1, 0], [1, 0], [0, 1], [0, 1], [1, 0], [1, 0], [0, 1], [0, 1], [1, 0], [1, 0], [0, 1], [0, 1]]), ['gender_F', 'gender_M']) ''' if varname is None: #assumes integer labels = ['level_%d' % i for i in range(x.max() + 1)] return (x[:,None]==np.arange(x.max()+1)).astype(int), labels else: grouplabels = np.unique(x) labels = [varname + '_%s' % str(i) for i in grouplabels] return (x[:,None]==grouplabels).astype(int), labels
dummy variable for id integer groups Parameters ---------- x : ndarray, 1d categorical variable, requires integers if varname is None varname : str name of the variable used in labels for category levels Returns ------- dummy : ndarray, 2d array of dummy variables, one column for each level of the category (full set) labels : list[str] labels for the columns, i.e. levels of each category Notes ----- use tools.categorical instead for more more options See Also -------- statsmodels.tools.categorical Examples -------- >>> x = np.array(['F', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'M', 'M'], dtype='|S1') >>> dummy_1d(x, varname='gender') (array([[1, 0], [1, 0], [0, 1], [0, 1], [1, 0], [1, 0], [0, 1], [0, 1], [1, 0], [1, 0], [0, 1], [0, 1]]), ['gender_F', 'gender_M'])
dummy_1d
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def dummy_product(d1, d2, method='full'): '''dummy variable from product of two dummy variables Parameters ---------- d1, d2 : ndarray two dummy variables, assumes full set for methods 'drop-last' and 'drop-first' method : {'full', 'drop-last', 'drop-first'} 'full' returns the full product, encoding of intersection of categories. The drop methods provide a difference dummy encoding: (constant, main effects, interaction effects). The first or last columns of the dummy variable (i.e. levels) are dropped to get full rank dummy matrix. Returns ------- dummy : ndarray dummy variable for product, see method ''' if method == 'full': dd = (d1[:,:,None]*d2[:,None,:]).reshape(d1.shape[0],-1) elif method == 'drop-last': #same as SAS transreg d12rl = dummy_product(d1[:,:-1], d2[:,:-1]) dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,:-1], d2[:,:-1],d12rl)) #Note: dtype int should preserve dtype of d1 and d2 elif method == 'drop-first': d12r = dummy_product(d1[:,1:], d2[:,1:]) dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,1:], d2[:,1:],d12r)) else: raise ValueError('method not recognized') return dd
dummy variable from product of two dummy variables Parameters ---------- d1, d2 : ndarray two dummy variables, assumes full set for methods 'drop-last' and 'drop-first' method : {'full', 'drop-last', 'drop-first'} 'full' returns the full product, encoding of intersection of categories. The drop methods provide a difference dummy encoding: (constant, main effects, interaction effects). The first or last columns of the dummy variable (i.e. levels) are dropped to get full rank dummy matrix. Returns ------- dummy : ndarray dummy variable for product, see method
dummy_product
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def dummy_limits(d): '''start and endpoints of groups in a sorted dummy variable array helper function for nested categories Examples -------- >>> d1 = np.array([[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]]) >>> dummy_limits(d1) (array([0, 4, 8]), array([ 4, 8, 12])) get group slices from an array >>> [np.arange(d1.shape[0])[b:e] for b,e in zip(*dummy_limits(d1))] [array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])] >>> [np.arange(d1.shape[0])[b:e] for b,e in zip(*dummy_limits(d1))] [array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])] ''' nobs, nvars = d.shape start1, col1 = np.nonzero(np.diff(d,axis=0)==1) end1, col1_ = np.nonzero(np.diff(d,axis=0)==-1) cc = np.arange(nvars) #print(cc, np.r_[[0], col1], np.r_[col1_, [nvars-1]] if ((not (np.r_[[0], col1] == cc).all()) or (not (np.r_[col1_, [nvars-1]] == cc).all())): raise ValueError('dummy variable is not sorted') start = np.r_[[0], start1+1] end = np.r_[end1+1, [nobs]] return start, end
start and endpoints of groups in a sorted dummy variable array helper function for nested categories Examples -------- >>> d1 = np.array([[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]]) >>> dummy_limits(d1) (array([0, 4, 8]), array([ 4, 8, 12])) get group slices from an array >>> [np.arange(d1.shape[0])[b:e] for b,e in zip(*dummy_limits(d1))] [array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])] >>> [np.arange(d1.shape[0])[b:e] for b,e in zip(*dummy_limits(d1))] [array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])]
dummy_limits
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def dummy_nested(d1, d2, method='full'): '''unfinished and incomplete mainly copy past dummy_product dummy variable from product of two dummy variables Parameters ---------- d1, d2 : ndarray two dummy variables, d2 is assumed to be nested in d1 Assumes full set for methods 'drop-last' and 'drop-first'. method : {'full', 'drop-last', 'drop-first'} 'full' returns the full product, which in this case is d2. The drop methods provide an effects encoding: (constant, main effects, subgroup effects). The first or last columns of the dummy variable (i.e. levels) are dropped to get full rank encoding. Returns ------- dummy : ndarray dummy variable for product, see method ''' if method == 'full': return d2 start1, end1 = dummy_limits(d1) start2, end2 = dummy_limits(d2) first = np.in1d(start2, start1) last = np.in1d(end2, end1) equal = (first == last) col_dropf = ~first*~equal col_dropl = ~last*~equal if method == 'drop-last': dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,:-1], d2[:,col_dropl])) #Note: dtype int should preserve dtype of d1 and d2 elif method == 'drop-first': dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,1:], d2[:,col_dropf])) else: raise ValueError('method not recognized') return dd, col_dropf, col_dropl
unfinished and incomplete mainly copy past dummy_product dummy variable from product of two dummy variables Parameters ---------- d1, d2 : ndarray two dummy variables, d2 is assumed to be nested in d1 Assumes full set for methods 'drop-last' and 'drop-first'. method : {'full', 'drop-last', 'drop-first'} 'full' returns the full product, which in this case is d2. The drop methods provide an effects encoding: (constant, main effects, subgroup effects). The first or last columns of the dummy variable (i.e. levels) are dropped to get full rank encoding. Returns ------- dummy : ndarray dummy variable for product, see method
dummy_nested
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def __init__(self, d1, d2): '''C such that d1 C = d2, with d1 = X, d2 = Z should be (x, z) in arguments ? ''' self.transf_matrix = np.linalg.lstsq(d1, d2, rcond=-1)[0] self.invtransf_matrix = np.linalg.lstsq(d2, d1, rcond=-1)[0]
C such that d1 C = d2, with d1 = X, d2 = Z should be (x, z) in arguments ?
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def dot_left(self, a): ''' b = C a ''' return np.dot(self.transf_matrix, a)
b = C a
dot_left
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def dot_right(self, x): ''' z = x C ''' return np.dot(x, self.transf_matrix)
z = x C
dot_right
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def inv_dot_left(self, b): ''' a = C^{-1} b ''' return np.dot(self.invtransf_matrix, b)
a = C^{-1} b
inv_dot_left
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def inv_dot_right(self, z): ''' x = z C^{-1} ''' return np.dot(z, self.invtransf_matrix)
x = z C^{-1}
inv_dot_right
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def groupmean_d(x, d): '''groupmeans using dummy variables Parameters ---------- x : array_like, ndim data array, tested for 1,2 and 3 dimensions d : ndarray, 1d dummy variable, needs to have the same length as x in axis 0. Returns ------- groupmeans : ndarray, ndim-1 means for each group along axis 0, the levels of the groups are the last axis Notes ----- This will be memory intensive if there are many levels in the categorical variable, i.e. many columns in the dummy variable. In this case it is recommended to use a more efficient version. ''' x = np.asarray(x) ## if x.ndim == 1: ## nvars = 1 ## else: nvars = x.ndim + 1 sli = [slice(None)] + [None]*(nvars-2) + [slice(None)] return (x[...,None] * d[sli]).sum(0)*1./d.sum(0)
groupmeans using dummy variables Parameters ---------- x : array_like, ndim data array, tested for 1,2 and 3 dimensions d : ndarray, 1d dummy variable, needs to have the same length as x in axis 0. Returns ------- groupmeans : ndarray, ndim-1 means for each group along axis 0, the levels of the groups are the last axis Notes ----- This will be memory intensive if there are many levels in the categorical variable, i.e. many columns in the dummy variable. In this case it is recommended to use a more efficient version.
groupmean_d
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def r_nointer(self): '''contrast/restriction matrix for no interaction ''' nia = self.n_interaction R_nointer = np.hstack((np.zeros((nia, self.nvars-nia)), np.eye(nia))) #inter_direct = resols_full_dropf.tval[-nia:] R_nointer_transf = self.transform.inv_dot_right(R_nointer) self.R_nointer_transf = R_nointer_transf return R_nointer_transf
contrast/restriction matrix for no interaction
r_nointer
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def ttest_interaction(self): '''ttests for no-interaction terms are zero ''' #use self.r_nointer instead nia = self.n_interaction R_nointer = np.hstack((np.zeros((nia, self.nvars-nia)), np.eye(nia))) #inter_direct = resols_full_dropf.tval[-nia:] R_nointer_transf = self.transform.inv_dot_right(R_nointer) self.R_nointer_transf = R_nointer_transf t_res = self.resols.t_test(R_nointer_transf) return t_res
ttests for no-interaction terms are zero
ttest_interaction
python
statsmodels/statsmodels
statsmodels/sandbox/stats/contrast_tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/contrast_tools.py
BSD-3-Clause
def scoreatpercentile(data, percentile): """Return the score at the given percentile of the data. Example: >>> data = randn(100) >>> scoreatpercentile(data, 50) will return the median of sample `data`. """ per = np.array(percentile) cdf = empiricalcdf(data) interpolator = interpolate.interp1d(np.sort(cdf), np.sort(data)) return interpolator(per/100.)
Return the score at the given percentile of the data. Example: >>> data = randn(100) >>> scoreatpercentile(data, 50) will return the median of sample `data`.
scoreatpercentile
python
statsmodels/statsmodels
statsmodels/sandbox/stats/stats_dhuard.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/stats_dhuard.py
BSD-3-Clause
def percentileofscore(data, score): """Return the percentile-position of score relative to data. score: Array of scores at which the percentile is computed. Return percentiles (0-100). Example r = randn(50) x = linspace(-2,2,100) percentileofscore(r,x) Raise an error if the score is outside the range of data. """ cdf = empiricalcdf(data) interpolator = interpolate.interp1d(np.sort(data), np.sort(cdf)) return interpolator(score)*100.
Return the percentile-position of score relative to data. score: Array of scores at which the percentile is computed. Return percentiles (0-100). Example r = randn(50) x = linspace(-2,2,100) percentileofscore(r,x) Raise an error if the score is outside the range of data.
percentileofscore
python
statsmodels/statsmodels
statsmodels/sandbox/stats/stats_dhuard.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/stats_dhuard.py
BSD-3-Clause
def empiricalcdf(data, method='Hazen'): """Return the empirical cdf. Methods available: Hazen: (i-0.5)/N Weibull: i/(N+1) Chegodayev: (i-.3)/(N+.4) Cunnane: (i-.4)/(N+.2) Gringorten: (i-.44)/(N+.12) California: (i-1)/N Where i goes from 1 to N. """ i = np.argsort(np.argsort(data)) + 1. N = len(data) method = method.lower() if method == 'hazen': cdf = (i-0.5)/N elif method == 'weibull': cdf = i/(N+1.) elif method == 'california': cdf = (i-1.)/N elif method == 'chegodayev': cdf = (i-.3)/(N+.4) elif method == 'cunnane': cdf = (i-.4)/(N+.2) elif method == 'gringorten': cdf = (i-.44)/(N+.12) else: raise ValueError('Unknown method. Choose among Weibull, Hazen,' 'Chegodayev, Cunnane, Gringorten and California.') return cdf
Return the empirical cdf. Methods available: Hazen: (i-0.5)/N Weibull: i/(N+1) Chegodayev: (i-.3)/(N+.4) Cunnane: (i-.4)/(N+.2) Gringorten: (i-.44)/(N+.12) California: (i-1)/N Where i goes from 1 to N.
empiricalcdf
python
statsmodels/statsmodels
statsmodels/sandbox/stats/stats_dhuard.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/stats_dhuard.py
BSD-3-Clause
def cdf_emp(self, score): ''' this is score in dh ''' return self.cdfintp(score)
this is score in dh
cdf_emp
python
statsmodels/statsmodels
statsmodels/sandbox/stats/stats_dhuard.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/stats_dhuard.py
BSD-3-Clause
def optimize_binning(self, method='Freedman'): """Find the optimal number of bins and update the bin countaccordingly. Available methods : Freedman Scott """ nobs = len(self.data) if method=='Freedman': IQR = self.ppf_emp(0.75) - self.ppf_emp(0.25) # Interquantile range(75% -25%) width = 2* IQR* nobs**(-1./3) elif method=='Scott': width = 3.49 * np.std(self.data) * nobs**(-1./3) self.nbin = (np.ptp(self.binlimit)/width) return self.nbin
Find the optimal number of bins and update the bin countaccordingly. Available methods : Freedman Scott
optimize_binning
python
statsmodels/statsmodels
statsmodels/sandbox/stats/stats_dhuard.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/stats_dhuard.py
BSD-3-Clause
def get_tukeyQcrit(k, df, alpha=0.05): """ return critical values for Tukey's HSD (Q) Parameters ---------- k : int in {2, ..., 10} number of tests df : int degrees of freedom of error term alpha : {0.05, 0.01} type 1 error, 1-confidence level not enough error checking for limitations """ if alpha == 0.05: intp = interpolate.interp1d(crows, cv005[:, k - 2]) elif alpha == 0.01: intp = interpolate.interp1d(crows, cv001[:, k - 2]) else: raise ValueError("only implemented for alpha equal to 0.01 and 0.05") return intp(df)
return critical values for Tukey's HSD (Q) Parameters ---------- k : int in {2, ..., 10} number of tests df : int degrees of freedom of error term alpha : {0.05, 0.01} type 1 error, 1-confidence level not enough error checking for limitations
get_tukeyQcrit
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def get_tukey_pvalue(k, df, q): """ return adjusted p-values for Tukey's HSD Parameters ---------- k : int in {2, ..., 10} number of tests df : int degrees of freedom of error term q : scalar, array_like; q >= 0 quantile value of Studentized Range """ return studentized_range.sf(q, k, df)
return adjusted p-values for Tukey's HSD Parameters ---------- k : int in {2, ..., 10} number of tests df : int degrees of freedom of error term q : scalar, array_like; q >= 0 quantile value of Studentized Range
get_tukey_pvalue
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def Tukeythreegene2(genes): # Performing the Tukey HSD post-hoc test for three genes """gend is a list, ie [first, second, third]""" # qwb = xlrd.open_workbook('F:/Lab/bioinformatics/qcrittable.xls') # opening the workbook containing the q crit table # qwb.sheet_names() # qcrittable = qwb.sheet_by_name(u'Sheet1') means = [] stds = [] for gene in genes: means.append(np.mean(gene)) std.append(np.std(gene)) # noqa:F821 See GH#5756 # firstmean = np.mean(first) #means of the three arrays # secondmean = np.mean(second) # thirdmean = np.mean(third) # firststd = np.std(first) #standard deviations of the three arrays # secondstd = np.std(second) # thirdstd = np.std(third) stds2 = [] for std in stds: stds2.append(math.pow(std, 2))
gend is a list, ie [first, second, third]
Tukeythreegene2
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def maxzero(x): """find all up zero crossings and return the index of the highest Not used anymore >>> np.random.seed(12345) >>> x = np.random.randn(8) >>> x array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057, 1.39340583, 0.09290788, 0.28174615]) >>> maxzero(x) (4, array([1, 4])) no up-zero-crossing at end >>> np.random.seed(0) >>> x = np.random.randn(8) >>> x array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788, 0.95008842, -0.15135721]) >>> maxzero(x) (None, array([6])) """ x = np.asarray(x) cond1 = x[:-1] < 0 cond2 = x[1:] > 0 # allzeros = np.nonzero(np.sign(x[:-1])*np.sign(x[1:]) <= 0)[0] + 1 allzeros = np.nonzero((cond1 & cond2) | (x[1:] == 0))[0] + 1 if x[-1] >= 0: maxz = max(allzeros) else: maxz = None return maxz, allzeros
find all up zero crossings and return the index of the highest Not used anymore >>> np.random.seed(12345) >>> x = np.random.randn(8) >>> x array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057, 1.39340583, 0.09290788, 0.28174615]) >>> maxzero(x) (4, array([1, 4])) no up-zero-crossing at end >>> np.random.seed(0) >>> x = np.random.randn(8) >>> x array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788, 0.95008842, -0.15135721]) >>> maxzero(x) (None, array([6]))
maxzero
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def maxzerodown(x): """find all up zero crossings and return the index of the highest Not used anymore >>> np.random.seed(12345) >>> x = np.random.randn(8) >>> x array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057, 1.39340583, 0.09290788, 0.28174615]) >>> maxzero(x) (4, array([1, 4])) no up-zero-crossing at end >>> np.random.seed(0) >>> x = np.random.randn(8) >>> x array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788, 0.95008842, -0.15135721]) >>> maxzero(x) (None, array([6])) """ x = np.asarray(x) cond1 = x[:-1] > 0 cond2 = x[1:] < 0 # allzeros = np.nonzero(np.sign(x[:-1])*np.sign(x[1:]) <= 0)[0] + 1 allzeros = np.nonzero((cond1 & cond2) | (x[1:] == 0))[0] + 1 if x[-1] <= 0: maxz = max(allzeros) else: maxz = None return maxz, allzeros
find all up zero crossings and return the index of the highest Not used anymore >>> np.random.seed(12345) >>> x = np.random.randn(8) >>> x array([-0.20470766, 0.47894334, -0.51943872, -0.5557303 , 1.96578057, 1.39340583, 0.09290788, 0.28174615]) >>> maxzero(x) (4, array([1, 4])) no up-zero-crossing at end >>> np.random.seed(0) >>> x = np.random.randn(8) >>> x array([ 1.76405235, 0.40015721, 0.97873798, 2.2408932 , 1.86755799, -0.97727788, 0.95008842, -0.15135721]) >>> maxzero(x) (None, array([6]))
maxzerodown
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def rejectionline(n, alpha=0.5): """reference line for rejection in multiple tests Not used anymore from: section 3.2, page 60 """ t = np.arange(n) / float(n) frej = t / (t * (1 - alpha) + alpha) return frej
reference line for rejection in multiple tests Not used anymore from: section 3.2, page 60
rejectionline
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def fdrcorrection_bak(pvals, alpha=0.05, method="indep"): """Reject False discovery rate correction for pvalues Old version, to be deleted missing: methods that estimate fraction of true hypotheses """ from statsmodels.stats.multitest import _ecdf as ecdf pvals = np.asarray(pvals) pvals_sortind = np.argsort(pvals) pvals_sorted = pvals[pvals_sortind] pecdf = ecdf(pvals_sorted) if method in ["i", "indep", "p", "poscorr"]: rline = pvals_sorted / alpha elif method in ["n", "negcorr"]: cm = np.sum(1.0 / np.arange(1, len(pvals))) rline = pvals_sorted / alpha * cm elif method in ["g", "onegcorr"]: # what's this ? german diss rline = pvals_sorted / (pvals_sorted * (1 - alpha) + alpha) elif method in ["oth", "o2negcorr"]: # other invalid, cut-paste cm = np.sum(np.arange(len(pvals))) rline = pvals_sorted / alpha / cm else: raise ValueError("method not available") reject = pecdf >= rline if reject.any(): rejectmax = max(np.nonzero(reject)[0]) else: rejectmax = 0 reject[:rejectmax] = True return reject[pvals_sortind.argsort()]
Reject False discovery rate correction for pvalues Old version, to be deleted missing: methods that estimate fraction of true hypotheses
fdrcorrection_bak
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def mcfdr(nrepl=100, nobs=50, ntests=10, ntrue=6, mu=0.5, alpha=0.05, rho=0.0): """MonteCarlo to test fdrcorrection""" from statsmodels.stats.multitest import fdrcorrection as fdrcorrection0 # Unused result, commented out # ntests - ntrue locs = np.array([0.0] * ntrue + [mu] * (ntests - ntrue)) results = [] for i in range(nrepl): # rvs = locs + stats.norm.rvs(size=(nobs, ntests)) rvs = locs + randmvn(rho, size=(nobs, ntests)) tt, tpval = stats.ttest_1samp(rvs, 0) res = fdrcorrection_bak(np.abs(tpval), alpha=alpha, method="i") res0 = fdrcorrection0(np.abs(tpval), alpha=alpha) # res and res0 give the same results results.append( [np.sum(res[:ntrue]), np.sum(res[ntrue:])] + [np.sum(res0[:ntrue]), np.sum(res0[ntrue:])] + res.tolist() + np.sort(tpval).tolist() + [np.sum(tpval[:ntrue] < alpha), np.sum(tpval[ntrue:] < alpha)] + [ np.sum(tpval[:ntrue] < alpha / ntests), np.sum(tpval[ntrue:] < alpha / ntests), ] ) return np.array(results)
MonteCarlo to test fdrcorrection
mcfdr
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def randmvn(rho, size=(1, 2), standardize=False): """create random draws from equi-correlated multivariate normal distribution Parameters ---------- rho : float correlation coefficient size : tuple of int size is interpreted (nobs, nvars) where each row Returns ------- rvs : ndarray nobs by nvars where each row is a independent random draw of nvars- dimensional correlated rvs """ nobs, nvars = size if 0 < rho and rho < 1: rvs = np.random.randn(nobs, nvars + 1) rvs2 = rvs[:, :-1] * np.sqrt(1 - rho) + rvs[:, -1:] * np.sqrt(rho) elif rho == 0: rvs2 = np.random.randn(nobs, nvars) elif rho < 0: if rho < -1.0 / (nvars - 1): raise ValueError("rho has to be larger than -1./(nvars-1)") elif rho == -1.0 / (nvars - 1): rho = -1.0 / (nvars - 1 + 1e-10) # barely positive definite # use Cholesky A = rho * np.ones((nvars, nvars)) + (1 - rho) * np.eye(nvars) rvs2 = np.dot(np.random.randn(nobs, nvars), np.linalg.cholesky(A).T) if standardize: rvs2 = stats.zscore(rvs2) return rvs2
create random draws from equi-correlated multivariate normal distribution Parameters ---------- rho : float correlation coefficient size : tuple of int size is interpreted (nobs, nvars) where each row Returns ------- rvs : ndarray nobs by nvars where each row is a independent random draw of nvars- dimensional correlated rvs
randmvn
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def tiecorrect(xranks): """ should be equivalent of scipy.stats.tiecorrect """ # casting to int rounds down, but not relevant for this case rankbincount = np.bincount(np.asarray(xranks, dtype=int)) nties = rankbincount[rankbincount > 1] ntot = float(len(xranks)) tiecorrection = 1 - (nties**3 - nties).sum() / (ntot**3 - ntot) return tiecorrection
should be equivalent of scipy.stats.tiecorrect
tiecorrect
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def __init__(self, x, useranks=False, uni=None, intlab=None): """descriptive statistics by groups Parameters ---------- x : ndarray, 2d first column data, second column group labels useranks : bool if true, then use ranks as data corresponding to the scipy.stats.rankdata definition (start at 1, ties get mean) uni, intlab : arrays (optional) to avoid call to unique, these can be given as inputs """ self.x = np.asarray(x) if intlab is None: uni, intlab = np.unique(x[:, 1], return_inverse=True) elif uni is None: uni = np.unique(x[:, 1]) self.useranks = useranks self.uni = uni self.intlab = intlab self.groupnobs = np.bincount(intlab) # temporary until separated and made all lazy self.runbasic(useranks=useranks)
descriptive statistics by groups Parameters ---------- x : ndarray, 2d first column data, second column group labels useranks : bool if true, then use ranks as data corresponding to the scipy.stats.rankdata definition (start at 1, ties get mean) uni, intlab : arrays (optional) to avoid call to unique, these can be given as inputs
__init__
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def runbasic_old(self, useranks=False): """runbasic_old""" # check: refactoring screwed up case useranks=True # groupxsum = np.bincount(intlab, weights=X[:,0]) # groupxmean = groupxsum * 1.0 / groupnobs x = self.x if useranks: self.xx = x[:, 1].argsort().argsort() + 1 # rankraw else: self.xx = x[:, 0] self.groupsum = groupranksum = np.bincount(self.intlab, weights=self.xx) # print('groupranksum', groupranksum, groupranksum.shape, self.groupnobs.shape # start at 1 for stats.rankdata : self.groupmean = grouprankmean = groupranksum * 1.0 / self.groupnobs # + 1 self.groupmeanfilter = grouprankmean[self.intlab]
runbasic_old
runbasic_old
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def runbasic(self, useranks=False): """runbasic""" # check: refactoring screwed up case useranks=True # groupxsum = np.bincount(intlab, weights=X[:,0]) # groupxmean = groupxsum * 1.0 / groupnobs x = self.x if useranks: xuni, xintlab = np.unique(x[:, 0], return_inverse=True) ranksraw = x[:, 0].argsort().argsort() + 1 # rankraw self.xx = GroupsStats( np.column_stack([ranksraw, xintlab]), useranks=False ).groupmeanfilter else: self.xx = x[:, 0] self.groupsum = groupranksum = np.bincount(self.intlab, weights=self.xx) # print('groupranksum', groupranksum, groupranksum.shape, self.groupnobs.shape # start at 1 for stats.rankdata : self.groupmean = grouprankmean = groupranksum * 1.0 / self.groupnobs # + 1 self.groupmeanfilter = grouprankmean[self.intlab]
runbasic
runbasic
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def groupdemean(self): """groupdemean""" return self.xx - self.groupmeanfilter
groupdemean
groupdemean
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def groupsswithin(self): """groupsswithin""" xtmp = self.groupdemean() return np.bincount(self.intlab, weights=xtmp**2)
groupsswithin
groupsswithin
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def groupvarwithin(self): """groupvarwithin""" return self.groupsswithin() / (self.groupnobs - 1) # .sum()
groupvarwithin
groupvarwithin
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def summary(self): """Summary table that can be printed""" return self._results_table
Summary table that can be printed
summary
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def summary_frame(self): """Summary DataFrame The group columns are labeled as "group_t" and "group_c" with mean difference defined as treatment minus control. This should be less confusing than numeric labels group1 and group2. Returns ------- pandas.DataFrame Notes ----- The number of columns will likely increase in a future version of statsmodels. Do not use numeric indices for the DataFrame in order to be robust to the addition of columns. """ frame = pd.DataFrame({ "group_t": self.group_t, "group_c": self.group_c, "meandiff": self.meandiffs, "p-adj": self.pvalues, "lower": self.confint[:, 0], "upper": self.confint[:, 1], "reject": self.reject, }) return frame
Summary DataFrame The group columns are labeled as "group_t" and "group_c" with mean difference defined as treatment minus control. This should be less confusing than numeric labels group1 and group2. Returns ------- pandas.DataFrame Notes ----- The number of columns will likely increase in a future version of statsmodels. Do not use numeric indices for the DataFrame in order to be robust to the addition of columns.
summary_frame
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def _simultaneous_ci(self): """Compute simultaneous confidence intervals for comparison of means.""" q_crit_hsd = self._get_q_crit(hsd=True) self.halfwidths = simultaneous_ci( q_crit_hsd, self.variance, self._multicomp.groupstats.groupnobs, self._multicomp.pairindices, )
Compute simultaneous confidence intervals for comparison of means.
_simultaneous_ci
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def plot_simultaneous( self, comparison_name=None, ax=None, figsize=(10, 6), xlabel=None, ylabel=None ): """Plot a universal confidence interval of each group mean Visualize significant differences in a plot with one confidence interval per group instead of all pairwise confidence intervals. Parameters ---------- comparison_name : str, optional if provided, plot_intervals will color code all groups that are significantly different from the comparison_name red, and will color code insignificant groups gray. Otherwise, all intervals will just be plotted in black. ax : matplotlib axis, optional An axis handle on which to attach the plot. figsize : tuple, optional tuple for the size of the figure generated xlabel : str, optional Name to be displayed on x axis ylabel : str, optional Name to be displayed on y axis Returns ------- Figure handle to figure object containing interval plots Notes ----- Multiple comparison tests are nice, but lack a good way to be visualized. If you have, say, 6 groups, showing a graph of the means between each group will require 15 confidence intervals. Instead, we can visualize inter-group differences with a single interval for each group mean. Hochberg et al. [1] first proposed this idea and used Tukey's Q critical value to compute the interval widths. Unlike plotting the differences in the means and their respective confidence intervals, any two pairs can be compared for significance by looking for overlap. The derivation in Hochberg and Tamhane is under the equal variance assumption. We use the same computation in the case of unequal variances, however, with replacement of the common pooled variance by the unequal estimates of the whithin group variances. This provides a plot that looks more informative and plausible in the case where there are large differences in variances. In the equal sample size and equal variance case, the confidence intervals computed by the two methods, equal and unequal variance, are very close to each other in larger samples. References ---------- .. [*] Hochberg, Y., and A. C. Tamhane. Multiple Comparison Procedures. Hoboken, NJ: John Wiley & Sons, 1987. Examples -------- >>> from statsmodels.examples.try_tukey_hsd import cylinders, cyl_labels >>> from statsmodels.stats.multicomp import MultiComparison >>> cardata = MultiComparison(cylinders, cyl_labels) >>> results = cardata.tukeyhsd() >>> results.plot_simultaneous() <matplotlib.figure.Figure at 0x...> This example shows an example plot comparing significant differences in group means. Significant differences at the alpha=0.05 level can be identified by intervals that do not overlap (i.e. USA vs Japan, USA vs Germany). >>> results.plot_simultaneous(comparison_name="USA") <matplotlib.figure.Figure at 0x...> Optionally provide one of the group names to color code the plot to highlight group means different from comparison_name. """ fig, ax1 = utils.create_mpl_ax(ax) if figsize is not None: fig.set_size_inches(figsize) if getattr(self, "halfwidths", None) is None: self._simultaneous_ci() means = self._multicomp.groupstats.groupmean sigidx = [] nsigidx = [] minrange = [means[i] - self.halfwidths[i] for i in range(len(means))] maxrange = [means[i] + self.halfwidths[i] for i in range(len(means))] if comparison_name is None: ax1.errorbar( means, lrange(len(means)), xerr=self.halfwidths, marker="o", linestyle="None", color="k", ecolor="k", ) else: if comparison_name not in self.groupsunique: raise ValueError("comparison_name not found in group names.") midx = np.where(self.groupsunique == comparison_name)[0][0] for i in range(len(means)): if self.groupsunique[i] == comparison_name: continue if ( min(maxrange[i], maxrange[midx]) - max(minrange[i], minrange[midx]) < 0 ): sigidx.append(i) else: nsigidx.append(i) # Plot the main comparison ax1.errorbar( means[midx], midx, xerr=self.halfwidths[midx], marker="o", linestyle="None", color="b", ecolor="b", ) ax1.plot( [minrange[midx]] * 2, [-1, self._multicomp.ngroups], linestyle="--", color="0.7", ) ax1.plot( [maxrange[midx]] * 2, [-1, self._multicomp.ngroups], linestyle="--", color="0.7", ) # Plot those that are significantly different if len(sigidx) > 0: ax1.errorbar( means[sigidx], sigidx, xerr=self.halfwidths[sigidx], marker="o", linestyle="None", color="r", ecolor="r", ) # Plot those that are not significantly different if len(nsigidx) > 0: ax1.errorbar( means[nsigidx], nsigidx, xerr=self.halfwidths[nsigidx], marker="o", linestyle="None", color="0.5", ecolor="0.5", ) ax1.set_title("Multiple Comparisons Between All Pairs (Tukey)") r = np.max(maxrange) - np.min(minrange) ax1.set_ylim([-1, self._multicomp.ngroups]) ax1.set_xlim([np.min(minrange) - r / 10.0, np.max(maxrange) + r / 10.0]) ylbls = [""] + self.groupsunique.astype(str).tolist() + [""] ax1.set_yticks(np.arange(-1, len(means) + 1)) ax1.set_yticklabels(ylbls) ax1.set_xlabel(xlabel if xlabel is not None else "") ax1.set_ylabel(ylabel if ylabel is not None else "") return fig
Plot a universal confidence interval of each group mean Visualize significant differences in a plot with one confidence interval per group instead of all pairwise confidence intervals. Parameters ---------- comparison_name : str, optional if provided, plot_intervals will color code all groups that are significantly different from the comparison_name red, and will color code insignificant groups gray. Otherwise, all intervals will just be plotted in black. ax : matplotlib axis, optional An axis handle on which to attach the plot. figsize : tuple, optional tuple for the size of the figure generated xlabel : str, optional Name to be displayed on x axis ylabel : str, optional Name to be displayed on y axis Returns ------- Figure handle to figure object containing interval plots Notes ----- Multiple comparison tests are nice, but lack a good way to be visualized. If you have, say, 6 groups, showing a graph of the means between each group will require 15 confidence intervals. Instead, we can visualize inter-group differences with a single interval for each group mean. Hochberg et al. [1] first proposed this idea and used Tukey's Q critical value to compute the interval widths. Unlike plotting the differences in the means and their respective confidence intervals, any two pairs can be compared for significance by looking for overlap. The derivation in Hochberg and Tamhane is under the equal variance assumption. We use the same computation in the case of unequal variances, however, with replacement of the common pooled variance by the unequal estimates of the whithin group variances. This provides a plot that looks more informative and plausible in the case where there are large differences in variances. In the equal sample size and equal variance case, the confidence intervals computed by the two methods, equal and unequal variance, are very close to each other in larger samples. References ---------- .. [*] Hochberg, Y., and A. C. Tamhane. Multiple Comparison Procedures. Hoboken, NJ: John Wiley & Sons, 1987. Examples -------- >>> from statsmodels.examples.try_tukey_hsd import cylinders, cyl_labels >>> from statsmodels.stats.multicomp import MultiComparison >>> cardata = MultiComparison(cylinders, cyl_labels) >>> results = cardata.tukeyhsd() >>> results.plot_simultaneous() <matplotlib.figure.Figure at 0x...> This example shows an example plot comparing significant differences in group means. Significant differences at the alpha=0.05 level can be identified by intervals that do not overlap (i.e. USA vs Japan, USA vs Germany). >>> results.plot_simultaneous(comparison_name="USA") <matplotlib.figure.Figure at 0x...> Optionally provide one of the group names to color code the plot to highlight group means different from comparison_name.
plot_simultaneous
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def getranks(self): """convert data to rankdata and attach This creates rankdata as it is used for non-parametric tests, where in the case of ties the average rank is assigned. """ # bug: the next should use self.groupintlab instead of self.groups # update: looks fixed # self.ranks = GroupsStats(np.column_stack([self.data, self.groups]), self.ranks = GroupsStats( np.column_stack([self.data, self.groupintlab]), useranks=True ) self.rankdata = self.ranks.groupmeanfilter
convert data to rankdata and attach This creates rankdata as it is used for non-parametric tests, where in the case of ties the average rank is assigned.
getranks
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def kruskal(self, pairs=None, multimethod="T"): """ pairwise comparison for kruskal-wallis test This is just a reimplementation of scipy.stats.kruskal and does not yet use a multiple comparison correction. """ self.getranks() tot = self.nobs meanranks = self.ranks.groupmean groupnobs = self.ranks.groupnobs # simultaneous/separate treatment of multiple tests f = (tot * (tot + 1.0) / 12.0) / stats.tiecorrect(self.rankdata) # (xranks) print("MultiComparison.kruskal") for i, j in zip(*self.pairindices): # pdiff = np.abs(mrs[i] - mrs[j]) pdiff = np.abs(meanranks[i] - meanranks[j]) se = np.sqrt( f * np.sum(1.0 / groupnobs[[i, j]]) ) # np.array([8,8]))) #Fixme groupnobs[[i,j]] )) Q = pdiff / se # TODO : print(statments, fix print(i, j, pdiff, se, pdiff / se, pdiff / se > 2.6310) print(stats.norm.sf(Q) * 2) return stats.norm.sf(Q) * 2
pairwise comparison for kruskal-wallis test This is just a reimplementation of scipy.stats.kruskal and does not yet use a multiple comparison correction.
kruskal
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def allpairtest(self, testfunc, alpha=0.05, method="bonf", pvalidx=1): """run a pairwise test on all pairs with multiple test correction The statistical test given in testfunc is calculated for all pairs and the p-values are adjusted by methods in multipletests. The p-value correction is generic and based only on the p-values, and does not take any special structure of the hypotheses into account. Parameters ---------- testfunc : function A test function for two (independent) samples. It is assumed that the return value on position pvalidx is the p-value. alpha : float familywise error rate method : str This specifies the method for the p-value correction. Any method of multipletests is possible. pvalidx : int (default: 1) position of the p-value in the return of testfunc Returns ------- sumtab : SimpleTable instance summary table for printing errors: TODO: check if this is still wrong, I think it's fixed. results from multipletests are in different order pval_corrected can be larger than 1 ??? """ from statsmodels.stats.multitest import multipletests res = [] for i, j in zip(*self.pairindices): res.append(testfunc(self.datali[i], self.datali[j])) res = np.array(res) reject, pvals_corrected, alphacSidak, alphacBonf = multipletests( res[:, pvalidx], alpha=alpha, method=method ) # print(np.column_stack([res[:,0],res[:,1], reject, pvals_corrected]) i1, i2 = self.pairindices if pvals_corrected is None: resarr = np.array( lzip( self.groupsunique[i1], self.groupsunique[i2], np.round(res[:, 0], 4), np.round(res[:, 1], 4), reject, ), dtype=[ ("group1", object), ("group2", object), ("stat", float), ("pval", float), ("reject", np.bool_), ], ) else: resarr = np.array( lzip( self.groupsunique[i1], self.groupsunique[i2], np.round(res[:, 0], 4), np.round(res[:, 1], 4), np.round(pvals_corrected, 4), reject, ), dtype=[ ("group1", object), ("group2", object), ("stat", float), ("pval", float), ("pval_corr", float), ("reject", np.bool_), ], ) results_table = SimpleTable(resarr, headers=resarr.dtype.names) results_table.title = "Test Multiple Comparison %s \n%s%4.2f method=%s" % ( testfunc.__name__, "FWER=", alpha, method, ) + "\nalphacSidak=%4.2f, alphacBonf=%5.3f" % (alphacSidak, alphacBonf) return ( results_table, (res, reject, pvals_corrected, alphacSidak, alphacBonf), resarr, )
run a pairwise test on all pairs with multiple test correction The statistical test given in testfunc is calculated for all pairs and the p-values are adjusted by methods in multipletests. The p-value correction is generic and based only on the p-values, and does not take any special structure of the hypotheses into account. Parameters ---------- testfunc : function A test function for two (independent) samples. It is assumed that the return value on position pvalidx is the p-value. alpha : float familywise error rate method : str This specifies the method for the p-value correction. Any method of multipletests is possible. pvalidx : int (default: 1) position of the p-value in the return of testfunc Returns ------- sumtab : SimpleTable instance summary table for printing errors: TODO: check if this is still wrong, I think it's fixed. results from multipletests are in different order pval_corrected can be larger than 1 ???
allpairtest
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def tukeyhsd(self, alpha=0.05, use_var='equal'): """ Tukey's range test to compare means of all pairs of groups Parameters ---------- alpha : float, optional Value of FWER at which to calculate HSD. use_var : {"unequal", "equal"} If ``use_var`` is "equal", then the Tukey-hsd pvalues are returned. Tukey-hsd assumes that (within) variances are the same across groups. If ``use_var`` is "unequal", then the Games-Howell pvalues are returned. This uses Welch's t-test for unequal variances with Satterthwait's corrected degrees of freedom for each pairwise comparison. Returns ------- results : TukeyHSDResults instance A results class containing relevant data and some post-hoc calculations Notes ----- .. versionadded:: 0.15 ` The `use_var` keyword and option for Games-Howell test. """ self.groupstats = GroupsStats( np.column_stack([self.data, self.groupintlab]), useranks=False ) gmeans = self.groupstats.groupmean gnobs = self.groupstats.groupnobs if use_var == 'unequal': var_ = self.groupstats.groupvarwithin() elif use_var == 'equal': var_ = np.var(self.groupstats.groupdemean(), ddof=len(gmeans)) else: raise ValueError('use_var should be "unequal" or "equal"') # res contains: 0:(idx1, idx2), 1:reject, 2:meandiffs, 3: std_pairs, # 4:confint, 5:q_crit, 6:df_total, 7:reject2, 8: pvals res = tukeyhsd(gmeans, gnobs, var_, df=None, alpha=alpha, q_crit=None) resarr = np.array( lzip( self.groupsunique[res[0][0]], self.groupsunique[res[0][1]], np.round(res[2], 4), np.round(res[8], 4), np.round(res[4][:, 0], 4), np.round(res[4][:, 1], 4), res[1], ), dtype=[ ("group1", object), ("group2", object), ("meandiff", float), ("p-adj", float), ("lower", float), ("upper", float), ("reject", np.bool_), ], ) results_table = SimpleTable(resarr, headers=resarr.dtype.names) results_table.title = ( "Multiple Comparison of Means - Tukey HSD, " + "FWER=%4.2f" % alpha ) return TukeyHSDResults( self, # mc_object, attached as _multicomp results_table, res[5], # q_crit, positional reject=res[1], meandiffs=res[2], std_pairs=res[3], confint=res[4], df_total=res[6], reject2=res[7], variance=var_, pvalues=res[8], alpha=alpha, group_t=self.groupsunique[res[0][1]], group_c=self.groupsunique[res[0][0]], )
Tukey's range test to compare means of all pairs of groups Parameters ---------- alpha : float, optional Value of FWER at which to calculate HSD. use_var : {"unequal", "equal"} If ``use_var`` is "equal", then the Tukey-hsd pvalues are returned. Tukey-hsd assumes that (within) variances are the same across groups. If ``use_var`` is "unequal", then the Games-Howell pvalues are returned. This uses Welch's t-test for unequal variances with Satterthwait's corrected degrees of freedom for each pairwise comparison. Returns ------- results : TukeyHSDResults instance A results class containing relevant data and some post-hoc calculations Notes ----- .. versionadded:: 0.15 ` The `use_var` keyword and option for Games-Howell test.
tukeyhsd
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def rankdata(x): """rankdata, equivalent to scipy.stats.rankdata just a different implementation, I have not yet compared speed """ uni, intlab = np.unique(x[:, 0], return_inverse=True) groupnobs = np.bincount(intlab) # Unused result, commented out # groupxsum = np.bincount(intlab, weights=X[:, 0]) # groupxsum * 1.0 / groupnobs rankraw = x[:, 0].argsort().argsort() groupranksum = np.bincount(intlab, weights=rankraw) # start at 1 for stats.rankdata : grouprankmean = groupranksum * 1.0 / groupnobs + 1 return grouprankmean[intlab]
rankdata, equivalent to scipy.stats.rankdata just a different implementation, I have not yet compared speed
rankdata
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def compare_ordered(vals, alpha): """simple ordered sequential comparison of means vals : array_like means or rankmeans for independent groups incomplete, no return, not used yet """ vals = np.asarray(vals) sortind = np.argsort(vals) sortind.argsort() ntests = len(vals) # alphacSidak = 1 - np.power((1. - alphaf), 1./ntests) # alphacBonf = alphaf / float(ntests) v1, v2 = np.triu_indices(ntests, 1) # v1,v2 have wrong sequence for i in range(4): for j in range(4, i, -1): print(i, j)
simple ordered sequential comparison of means vals : array_like means or rankmeans for independent groups incomplete, no return, not used yet
compare_ordered
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def varcorrection_unbalanced(nobs_all, srange=False): """correction factor for variance with unequal sample sizes this is just a harmonic mean Parameters ---------- nobs_all : array_like The number of observations for each sample srange : bool if true, then the correction is divided by the number of samples for the variance of the studentized range statistic Returns ------- correction : float Correction factor for variance. Notes ----- variance correction factor is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1. This needs to be multiplied by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. """ nobs_all = np.asarray(nobs_all) if not srange: return (1.0 / nobs_all).sum() else: return (1.0 / nobs_all).sum() / len(nobs_all)
correction factor for variance with unequal sample sizes this is just a harmonic mean Parameters ---------- nobs_all : array_like The number of observations for each sample srange : bool if true, then the correction is divided by the number of samples for the variance of the studentized range statistic Returns ------- correction : float Correction factor for variance. Notes ----- variance correction factor is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1. This needs to be multiplied by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken.
varcorrection_unbalanced
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def varcorrection_pairs_unbalanced(nobs_all, srange=False): """correction factor for variance with unequal sample sizes for all pairs this is just a harmonic mean Parameters ---------- nobs_all : array_like The number of observations for each sample srange : bool if true, then the correction is divided by 2 for the variance of the studentized range statistic Returns ------- correction : ndarray Correction factor for variance. Notes ----- variance correction factor is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. For the studentized range statistic, the resulting factor has to be divided by 2. """ # TODO: test and replace with broadcasting n1, n2 = np.meshgrid(nobs_all, nobs_all) if not srange: return 1.0 / n1 + 1.0 / n2 else: return (1.0 / n1 + 1.0 / n2) / 2.0
correction factor for variance with unequal sample sizes for all pairs this is just a harmonic mean Parameters ---------- nobs_all : array_like The number of observations for each sample srange : bool if true, then the correction is divided by 2 for the variance of the studentized range statistic Returns ------- correction : ndarray Correction factor for variance. Notes ----- variance correction factor is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. For the studentized range statistic, the resulting factor has to be divided by 2.
varcorrection_pairs_unbalanced
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def varcorrection_unequal(var_all, nobs_all, df_all): """return joint variance from samples with unequal variances and unequal sample sizes something is wrong Parameters ---------- var_all : array_like The variance for each sample nobs_all : array_like The number of observations for each sample df_all : array_like degrees of freedom for each sample Returns ------- varjoint : float joint variance. dfjoint : float joint Satterthwait's degrees of freedom Notes ----- (copy, paste not correct) variance is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1/n. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. This is for variance of mean difference not of studentized range. """ var_all = np.asarray(var_all) var_over_n = var_all * 1.0 / nobs_all # avoid integer division varjoint = var_over_n.sum() dfjoint = varjoint**2 / (var_over_n**2 * df_all).sum() return varjoint, dfjoint
return joint variance from samples with unequal variances and unequal sample sizes something is wrong Parameters ---------- var_all : array_like The variance for each sample nobs_all : array_like The number of observations for each sample df_all : array_like degrees of freedom for each sample Returns ------- varjoint : float joint variance. dfjoint : float joint Satterthwait's degrees of freedom Notes ----- (copy, paste not correct) variance is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1/n. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. This is for variance of mean difference not of studentized range.
varcorrection_unequal
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def varcorrection_pairs_unequal(var_all, nobs_all, df_all): """return joint variance from samples with unequal variances and unequal sample sizes for all pairs something is wrong Parameters ---------- var_all : array_like The variance for each sample nobs_all : array_like The number of observations for each sample df_all : array_like degrees of freedom for each sample Returns ------- varjoint : ndarray joint variance. dfjoint : ndarray joint Satterthwait's degrees of freedom Notes ----- (copy, paste not correct) variance is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken. """ # TODO: test and replace with broadcasting v1, v2 = np.meshgrid(var_all, var_all) n1, n2 = np.meshgrid(nobs_all, nobs_all) df1, df2 = np.meshgrid(df_all, df_all) varjoint = v1 / n1 + v2 / n2 dfjoint = varjoint**2 / ((v1 / n1) ** 2 / df1 + (v2 / n2) ** 2 / df2) return varjoint, dfjoint
return joint variance from samples with unequal variances and unequal sample sizes for all pairs something is wrong Parameters ---------- var_all : array_like The variance for each sample nobs_all : array_like The number of observations for each sample df_all : array_like degrees of freedom for each sample Returns ------- varjoint : ndarray joint variance. dfjoint : ndarray joint Satterthwait's degrees of freedom Notes ----- (copy, paste not correct) variance is 1/k * sum_i 1/n_i where k is the number of samples and summation is over i=0,...,k-1. If all n_i are the same, then the correction factor is 1. This needs to be multiplies by the joint variance estimate, means square error, MSE. To obtain the correction factor for the standard deviation, square root needs to be taken.
varcorrection_pairs_unequal
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def tukeyhsd(mean_all, nobs_all, var_all, df=None, alpha=0.05, q_crit=None): """simultaneous Tukey HSD check: instead of sorting, I use absolute value of pairwise differences in means. That's irrelevant for the test, but maybe reporting actual differences would be better. CHANGED: meandiffs are with sign, studentized range uses abs q_crit added for testing TODO: error in variance calculation when nobs_all is scalar, missing 1/n """ mean_all = np.asarray(mean_all) # check if or when other ones need to be arrays n_means = len(mean_all) if df is None: df = nobs_all - 1 if np.size(df) == 1: # assumes balanced samples with df = n - 1, n_i = n df_total = n_means * df df = np.ones(n_means) * df else: df_total = np.sum(df) df_pairs_ = None if (np.size(nobs_all) == 1) and (np.size(var_all) == 1): # balanced sample sizes and homogenous variance var_pairs = 1.0 * var_all / nobs_all * np.ones((n_means, n_means)) elif np.size(var_all) == 1: # unequal sample sizes and homogenous variance var_pairs = var_all * varcorrection_pairs_unbalanced(nobs_all, srange=True) elif np.size(var_all) > 1: var_pairs, df_pairs_ = varcorrection_pairs_unequal(var_all, nobs_all, df) var_pairs /= 2. # check division by two for studentized range else: raise ValueError("not supposed to be here") # meandiffs_ = mean_all[:,None] - mean_all meandiffs_ = mean_all - mean_all[:, None] # reverse sign, check with R example std_pairs_ = np.sqrt(var_pairs) # select all pairs from upper triangle of matrix idx1, idx2 = np.triu_indices(n_means, 1) meandiffs = meandiffs_[idx1, idx2] std_pairs = std_pairs_[idx1, idx2] if df_pairs_ is not None: df_total = df_pairs_[idx1, idx2] st_range = np.abs(meandiffs) / std_pairs # studentized range statistic # df_total_ = np.maximum(df_total, 5) # TODO: smallest df in table if q_crit is None: q_crit = get_tukeyQcrit2(n_means, df_total, alpha=alpha) pvalues = get_tukey_pvalue(n_means, df_total, st_range) # we need pvalues to be atleast_1d for iteration. see #6132 pvalues = np.atleast_1d(pvalues) reject = st_range > q_crit crit_int = std_pairs * q_crit reject2 = np.abs(meandiffs) > crit_int confint = np.column_stack((meandiffs - crit_int, meandiffs + crit_int)) return ( (idx1, idx2), reject, meandiffs, std_pairs, confint, q_crit, df_total, reject2, pvalues, )
simultaneous Tukey HSD check: instead of sorting, I use absolute value of pairwise differences in means. That's irrelevant for the test, but maybe reporting actual differences would be better. CHANGED: meandiffs are with sign, studentized range uses abs q_crit added for testing TODO: error in variance calculation when nobs_all is scalar, missing 1/n
tukeyhsd
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def simultaneous_ci(q_crit, var, groupnobs, pairindices=None): """Compute simultaneous confidence intervals for comparison of means. q_crit value is generated from tukey hsd test. Variance is considered across all groups. Returned halfwidths can be thought of as uncertainty intervals around each group mean. They allow for simultaneous comparison of pairwise significance among any pairs (by checking for overlap) Parameters ---------- q_crit : float The Q critical value studentized range statistic from Tukey's HSD var : float The group variance groupnobs : array_like object Number of observations contained in each group. pairindices : tuple of lists, optional Indices corresponding to the upper triangle of matrix. Computed here if not supplied Returns ------- halfwidths : ndarray Half the width of each confidence interval for each group given in groupnobs See Also -------- MultiComparison : statistics class providing significance tests tukeyhsd : among other things, computes q_crit value References ---------- .. [*] Hochberg, Y., and A. C. Tamhane. Multiple Comparison Procedures. Hoboken, NJ: John Wiley & Sons, 1987.) """ # Set initial variables ng = len(groupnobs) if pairindices is None: pairindices = np.triu_indices(ng, 1) # Compute dij for all pairwise comparisons ala hochberg p. 95 gvar = var / groupnobs d12 = np.sqrt(gvar[pairindices[0]] + gvar[pairindices[1]]) # Create the full d matrix given all known dij vals d = np.zeros((ng, ng)) d[pairindices] = d12 d = d + d.conj().T # Compute the two global sums from hochberg eq 3.32 sum1 = np.sum(d12) sum2 = np.sum(d, axis=0) if ng > 2: w = ((ng - 1.0) * sum2 - sum1) / ((ng - 1.0) * (ng - 2.0)) else: w = sum1 * np.ones((2, 1)) / 2.0 return (q_crit / np.sqrt(2)) * w
Compute simultaneous confidence intervals for comparison of means. q_crit value is generated from tukey hsd test. Variance is considered across all groups. Returned halfwidths can be thought of as uncertainty intervals around each group mean. They allow for simultaneous comparison of pairwise significance among any pairs (by checking for overlap) Parameters ---------- q_crit : float The Q critical value studentized range statistic from Tukey's HSD var : float The group variance groupnobs : array_like object Number of observations contained in each group. pairindices : tuple of lists, optional Indices corresponding to the upper triangle of matrix. Computed here if not supplied Returns ------- halfwidths : ndarray Half the width of each confidence interval for each group given in groupnobs See Also -------- MultiComparison : statistics class providing significance tests tukeyhsd : among other things, computes q_crit value References ---------- .. [*] Hochberg, Y., and A. C. Tamhane. Multiple Comparison Procedures. Hoboken, NJ: John Wiley & Sons, 1987.)
simultaneous_ci
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def distance_st_range(mean_all, nobs_all, var_all, df=None, triu=False): """pairwise distance matrix, outsourced from tukeyhsd CHANGED: meandiffs are with sign, studentized range uses abs q_crit added for testing TODO: error in variance calculation when nobs_all is scalar, missing 1/n """ mean_all = np.asarray(mean_all) # check if or when other ones need to be arrays n_means = len(mean_all) if df is None: df = nobs_all - 1 if (np.size(nobs_all) == 1) and (np.size(var_all) == 1): # balanced sample sizes and homogenous variance var_pairs = 1.0 * var_all / nobs_all * np.ones((n_means, n_means)) elif np.size(var_all) == 1: # unequal sample sizes and homogenous variance var_pairs = var_all * varcorrection_pairs_unbalanced(nobs_all, srange=True) elif np.size(var_all) > 1: var_pairs, df_sum = varcorrection_pairs_unequal(var_all, nobs_all, df) var_pairs /= 2. # check division by two for studentized range else: raise ValueError("not supposed to be here") # meandiffs_ = mean_all[:,None] - mean_all meandiffs = mean_all - mean_all[:, None] # reverse sign, check with R example std_pairs = np.sqrt(var_pairs) idx1, idx2 = np.triu_indices(n_means, 1) if triu: # select all pairs from upper triangle of matrix meandiffs = meandiffs_[idx1, idx2] # noqa: F821 See GH#5756 std_pairs = std_pairs_[idx1, idx2] # noqa: F821 See GH#5756 st_range = np.abs(meandiffs) / std_pairs # studentized range statistic return st_range, meandiffs, std_pairs, (idx1, idx2) # return square arrays
pairwise distance matrix, outsourced from tukeyhsd CHANGED: meandiffs are with sign, studentized range uses abs q_crit added for testing TODO: error in variance calculation when nobs_all is scalar, missing 1/n
distance_st_range
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def tukey_pvalues(std_range, nm, df): """compute tukey p-values by numerical integration of multivariate-t distribution """ # corrected but very slow with warnings about integration # need to increase maxiter or similar # nm = len(std_range) contr = contrast_allpairs(nm) corr = np.dot(contr, contr.T) / 2.0 tstat = std_range / np.sqrt(2) * np.ones(corr.shape[0]) # need len of all pairs return multicontrast_pvalues(tstat, corr, df=df)
compute tukey p-values by numerical integration of multivariate-t distribution
tukey_pvalues
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def multicontrast_pvalues(tstat, tcorr, df=None, dist="t", alternative="two-sided"): """pvalues for simultaneous tests currently only for t distribution, normal distribution not added yet alternative is ignored """ from statsmodels.sandbox.distributions.multivariate import mvstdtprob if (df is None) and (dist == "t"): raise ValueError("df has to be specified for the t-distribution") tstat = np.asarray(tstat) ntests = len(tstat) cc = np.abs(tstat) pval_global = 1 - mvstdtprob(-cc, cc, tcorr, df) pvals = [] for ti in cc: ti * np.ones(ntests) pvals.append(1 - mvstdtprob(-cc, cc, tcorr, df)) return pval_global, np.asarray(pvals)
pvalues for simultaneous tests currently only for t distribution, normal distribution not added yet alternative is ignored
multicontrast_pvalues
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause
def get_crit(self, alpha): """ get_tukeyQcrit currently tukey Q, add others """ q_crit = get_tukeyQcrit(self.n_vals, self.df, alpha=alpha) return q_crit * np.ones(self.n_vals)
get_tukeyQcrit currently tukey Q, add others
get_crit
python
statsmodels/statsmodels
statsmodels/sandbox/stats/multicomp.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/sandbox/stats/multicomp.py
BSD-3-Clause