id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
225,600 | dswah/pyGAM | pygam/links.py | LogitLink.gradient | def gradient(self, mu, dist):
"""
derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n
"""
return dist.levels/(mu*(dist.levels - mu)) | python | def gradient(self, mu, dist):
"""
derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n
"""
return dist.levels/(mu*(dist.levels - mu)) | [
"def",
"gradient",
"(",
"self",
",",
"mu",
",",
"dist",
")",
":",
"return",
"dist",
".",
"levels",
"/",
"(",
"mu",
"*",
"(",
"dist",
".",
"levels",
"-",
"mu",
")",
")"
] | derivative of the link function wrt mu
Parameters
----------
mu : array-like of legth n
dist : Distribution instance
Returns
-------
grad : np.array of length n | [
"derivative",
"of",
"the",
"link",
"function",
"wrt",
"mu"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/links.py#L136-L149 |
225,601 | dswah/pyGAM | pygam/penalties.py | derivative | def derivative(n, coef, derivative=2, periodic=False):
"""
Builds a penalty matrix for P-Splines with continuous features.
Penalizes the squared differences between basis coefficients.
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
derivative: int, default: 2
which derivative do we penalize.
derivative is 1, we penalize 1st order derivatives,
derivative is 2, we penalize 2nd order derivatives, etc
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
if n == 1:
# no derivative for constant functions
return sp.sparse.csc_matrix(0.)
D = sparse_diff(sp.sparse.identity(n + 2*derivative*periodic).tocsc(), n=derivative).tolil()
if periodic:
# wrap penalty
cols = D[:, :derivative]
D[:, -2 * derivative:-derivative] += cols * (-1) ** derivative
# do symmetric operation on lower half of matrix
n_rows = int((n + 2 * derivative)/2)
D[-n_rows:] = D[:n_rows][::-1, ::-1]
# keep only the center of the augmented matrix
D = D[derivative:-derivative, derivative:-derivative]
return D.dot(D.T).tocsc() | python | def derivative(n, coef, derivative=2, periodic=False):
"""
Builds a penalty matrix for P-Splines with continuous features.
Penalizes the squared differences between basis coefficients.
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
derivative: int, default: 2
which derivative do we penalize.
derivative is 1, we penalize 1st order derivatives,
derivative is 2, we penalize 2nd order derivatives, etc
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
if n == 1:
# no derivative for constant functions
return sp.sparse.csc_matrix(0.)
D = sparse_diff(sp.sparse.identity(n + 2*derivative*periodic).tocsc(), n=derivative).tolil()
if periodic:
# wrap penalty
cols = D[:, :derivative]
D[:, -2 * derivative:-derivative] += cols * (-1) ** derivative
# do symmetric operation on lower half of matrix
n_rows = int((n + 2 * derivative)/2)
D[-n_rows:] = D[:n_rows][::-1, ::-1]
# keep only the center of the augmented matrix
D = D[derivative:-derivative, derivative:-derivative]
return D.dot(D.T).tocsc() | [
"def",
"derivative",
"(",
"n",
",",
"coef",
",",
"derivative",
"=",
"2",
",",
"periodic",
"=",
"False",
")",
":",
"if",
"n",
"==",
"1",
":",
"# no derivative for constant functions",
"return",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"0.",
")",
"D",
... | Builds a penalty matrix for P-Splines with continuous features.
Penalizes the squared differences between basis coefficients.
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
derivative: int, default: 2
which derivative do we penalize.
derivative is 1, we penalize 1st order derivatives,
derivative is 2, we penalize 2nd order derivatives, etc
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n) | [
"Builds",
"a",
"penalty",
"matrix",
"for",
"P",
"-",
"Splines",
"with",
"continuous",
"features",
".",
"Penalizes",
"the",
"squared",
"differences",
"between",
"basis",
"coefficients",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/penalties.py#L9-L47 |
225,602 | dswah/pyGAM | pygam/penalties.py | monotonicity_ | def monotonicity_(n, coef, increasing=True):
"""
Builds a penalty matrix for P-Splines with continuous features.
Penalizes violation of monotonicity in the feature function.
Parameters
----------
n : int
number of splines
coef : array-like
coefficients of the feature function
increasing : bool, default: True
whether to enforce monotic increasing, or decreasing functions
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
if n != len(coef.ravel()):
raise ValueError('dimension mismatch: expected n equals len(coef), '\
'but found n = {}, coef.shape = {}.'\
.format(n, coef.shape))
if n==1:
# no monotonic penalty for constant functions
return sp.sparse.csc_matrix(0.)
if increasing:
# only penalize the case where coef_i-1 > coef_i
mask = sp.sparse.diags((np.diff(coef.ravel()) < 0).astype(float))
else:
# only penalize the case where coef_i-1 < coef_i
mask = sp.sparse.diags((np.diff(coef.ravel()) > 0).astype(float))
derivative = 1
D = sparse_diff(sp.sparse.identity(n).tocsc(), n=derivative) * mask
return D.dot(D.T).tocsc() | python | def monotonicity_(n, coef, increasing=True):
"""
Builds a penalty matrix for P-Splines with continuous features.
Penalizes violation of monotonicity in the feature function.
Parameters
----------
n : int
number of splines
coef : array-like
coefficients of the feature function
increasing : bool, default: True
whether to enforce monotic increasing, or decreasing functions
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
if n != len(coef.ravel()):
raise ValueError('dimension mismatch: expected n equals len(coef), '\
'but found n = {}, coef.shape = {}.'\
.format(n, coef.shape))
if n==1:
# no monotonic penalty for constant functions
return sp.sparse.csc_matrix(0.)
if increasing:
# only penalize the case where coef_i-1 > coef_i
mask = sp.sparse.diags((np.diff(coef.ravel()) < 0).astype(float))
else:
# only penalize the case where coef_i-1 < coef_i
mask = sp.sparse.diags((np.diff(coef.ravel()) > 0).astype(float))
derivative = 1
D = sparse_diff(sp.sparse.identity(n).tocsc(), n=derivative) * mask
return D.dot(D.T).tocsc() | [
"def",
"monotonicity_",
"(",
"n",
",",
"coef",
",",
"increasing",
"=",
"True",
")",
":",
"if",
"n",
"!=",
"len",
"(",
"coef",
".",
"ravel",
"(",
")",
")",
":",
"raise",
"ValueError",
"(",
"'dimension mismatch: expected n equals len(coef), '",
"'but found n = {... | Builds a penalty matrix for P-Splines with continuous features.
Penalizes violation of monotonicity in the feature function.
Parameters
----------
n : int
number of splines
coef : array-like
coefficients of the feature function
increasing : bool, default: True
whether to enforce monotic increasing, or decreasing functions
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n) | [
"Builds",
"a",
"penalty",
"matrix",
"for",
"P",
"-",
"Splines",
"with",
"continuous",
"features",
".",
"Penalizes",
"violation",
"of",
"monotonicity",
"in",
"the",
"feature",
"function",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/penalties.py#L71-L106 |
225,603 | dswah/pyGAM | pygam/penalties.py | none | def none(n, coef):
"""
Build a matrix of zeros for features that should go unpenalized
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
return sp.sparse.csc_matrix(np.zeros((n, n))) | python | def none(n, coef):
"""
Build a matrix of zeros for features that should go unpenalized
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n)
"""
return sp.sparse.csc_matrix(np.zeros((n, n))) | [
"def",
"none",
"(",
"n",
",",
"coef",
")",
":",
"return",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"n",
")",
")",
")"
] | Build a matrix of zeros for features that should go unpenalized
Parameters
----------
n : int
number of splines
coef : unused
for compatibility with constraints
Returns
-------
penalty matrix : sparse csc matrix of shape (n,n) | [
"Build",
"a",
"matrix",
"of",
"zeros",
"for",
"features",
"that",
"should",
"go",
"unpenalized"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/penalties.py#L245-L260 |
225,604 | dswah/pyGAM | pygam/penalties.py | wrap_penalty | def wrap_penalty(p, fit_linear, linear_penalty=0.):
"""
tool to account for unity penalty on the linear term of any feature.
example:
p = wrap_penalty(derivative, fit_linear=True)(n, coef)
Parameters
----------
p : callable.
penalty-matrix-generating function.
fit_linear : boolean.
whether the current feature has a linear term or not.
linear_penalty : float, default: 0.
penalty on the linear term
Returns
-------
wrapped_p : callable
modified penalty-matrix-generating function
"""
def wrapped_p(n, *args):
if fit_linear:
if n == 1:
return sp.sparse.block_diag([linear_penalty], format='csc')
return sp.sparse.block_diag([linear_penalty,
p(n-1, *args)], format='csc')
else:
return p(n, *args)
return wrapped_p | python | def wrap_penalty(p, fit_linear, linear_penalty=0.):
"""
tool to account for unity penalty on the linear term of any feature.
example:
p = wrap_penalty(derivative, fit_linear=True)(n, coef)
Parameters
----------
p : callable.
penalty-matrix-generating function.
fit_linear : boolean.
whether the current feature has a linear term or not.
linear_penalty : float, default: 0.
penalty on the linear term
Returns
-------
wrapped_p : callable
modified penalty-matrix-generating function
"""
def wrapped_p(n, *args):
if fit_linear:
if n == 1:
return sp.sparse.block_diag([linear_penalty], format='csc')
return sp.sparse.block_diag([linear_penalty,
p(n-1, *args)], format='csc')
else:
return p(n, *args)
return wrapped_p | [
"def",
"wrap_penalty",
"(",
"p",
",",
"fit_linear",
",",
"linear_penalty",
"=",
"0.",
")",
":",
"def",
"wrapped_p",
"(",
"n",
",",
"*",
"args",
")",
":",
"if",
"fit_linear",
":",
"if",
"n",
"==",
"1",
":",
"return",
"sp",
".",
"sparse",
".",
"block... | tool to account for unity penalty on the linear term of any feature.
example:
p = wrap_penalty(derivative, fit_linear=True)(n, coef)
Parameters
----------
p : callable.
penalty-matrix-generating function.
fit_linear : boolean.
whether the current feature has a linear term or not.
linear_penalty : float, default: 0.
penalty on the linear term
Returns
-------
wrapped_p : callable
modified penalty-matrix-generating function | [
"tool",
"to",
"account",
"for",
"unity",
"penalty",
"on",
"the",
"linear",
"term",
"of",
"any",
"feature",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/penalties.py#L262-L291 |
225,605 | dswah/pyGAM | pygam/penalties.py | sparse_diff | def sparse_diff(array, n=1, axis=-1):
"""
A ported sparse version of np.diff.
Uses recursion to compute higher order differences
Parameters
----------
array : sparse array
n : int, default: 1
differencing order
axis : int, default: -1
axis along which differences are computed
Returns
-------
diff_array : sparse array
same shape as input array,
but 'axis' dimension is smaller by 'n'.
"""
if (n < 0) or (int(n) != n):
raise ValueError('Expected order is non-negative integer, '\
'but found: {}'.format(n))
if not sp.sparse.issparse(array):
warnings.warn('Array is not sparse. Consider using numpy.diff')
if n == 0:
return array
nd = array.ndim
slice1 = [slice(None)]*nd
slice2 = [slice(None)]*nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
A = sparse_diff(array, n-1, axis=axis)
return A[slice1] - A[slice2] | python | def sparse_diff(array, n=1, axis=-1):
"""
A ported sparse version of np.diff.
Uses recursion to compute higher order differences
Parameters
----------
array : sparse array
n : int, default: 1
differencing order
axis : int, default: -1
axis along which differences are computed
Returns
-------
diff_array : sparse array
same shape as input array,
but 'axis' dimension is smaller by 'n'.
"""
if (n < 0) or (int(n) != n):
raise ValueError('Expected order is non-negative integer, '\
'but found: {}'.format(n))
if not sp.sparse.issparse(array):
warnings.warn('Array is not sparse. Consider using numpy.diff')
if n == 0:
return array
nd = array.ndim
slice1 = [slice(None)]*nd
slice2 = [slice(None)]*nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
A = sparse_diff(array, n-1, axis=axis)
return A[slice1] - A[slice2] | [
"def",
"sparse_diff",
"(",
"array",
",",
"n",
"=",
"1",
",",
"axis",
"=",
"-",
"1",
")",
":",
"if",
"(",
"n",
"<",
"0",
")",
"or",
"(",
"int",
"(",
"n",
")",
"!=",
"n",
")",
":",
"raise",
"ValueError",
"(",
"'Expected order is non-negative integer,... | A ported sparse version of np.diff.
Uses recursion to compute higher order differences
Parameters
----------
array : sparse array
n : int, default: 1
differencing order
axis : int, default: -1
axis along which differences are computed
Returns
-------
diff_array : sparse array
same shape as input array,
but 'axis' dimension is smaller by 'n'. | [
"A",
"ported",
"sparse",
"version",
"of",
"np",
".",
"diff",
".",
"Uses",
"recursion",
"to",
"compute",
"higher",
"order",
"differences"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/penalties.py#L293-L330 |
225,606 | dswah/pyGAM | pygam/pygam.py | GAM._linear_predictor | def _linear_predictor(self, X=None, modelmat=None, b=None, term=-1):
"""linear predictor
compute the linear predictor portion of the model
ie multiply the model matrix by the spline basis coefficients
Parameters
---------
at least 1 of (X, modelmat)
and
at least 1 of (b, feature)
X : array-like of shape (n_samples, m_features) or None, optional
containing the input dataset
if None, will attempt to use modelmat
modelmat : array-like or None, optional
contains the spline basis for each feature evaluated at the input
values for each feature, ie model matrix
if None, will attempt to construct the model matrix from X
b : array-like or None, optional
contains the spline coefficients
if None, will use current model coefficients
feature : int, optional
feature for which to compute the linear prediction
if -1, will compute for all features
Returns
-------
lp : np.array of shape (n_samples,)
"""
if modelmat is None:
modelmat = self._modelmat(X, term=term)
if b is None:
b = self.coef_[self.terms.get_coef_indices(term)]
return modelmat.dot(b).flatten() | python | def _linear_predictor(self, X=None, modelmat=None, b=None, term=-1):
"""linear predictor
compute the linear predictor portion of the model
ie multiply the model matrix by the spline basis coefficients
Parameters
---------
at least 1 of (X, modelmat)
and
at least 1 of (b, feature)
X : array-like of shape (n_samples, m_features) or None, optional
containing the input dataset
if None, will attempt to use modelmat
modelmat : array-like or None, optional
contains the spline basis for each feature evaluated at the input
values for each feature, ie model matrix
if None, will attempt to construct the model matrix from X
b : array-like or None, optional
contains the spline coefficients
if None, will use current model coefficients
feature : int, optional
feature for which to compute the linear prediction
if -1, will compute for all features
Returns
-------
lp : np.array of shape (n_samples,)
"""
if modelmat is None:
modelmat = self._modelmat(X, term=term)
if b is None:
b = self.coef_[self.terms.get_coef_indices(term)]
return modelmat.dot(b).flatten() | [
"def",
"_linear_predictor",
"(",
"self",
",",
"X",
"=",
"None",
",",
"modelmat",
"=",
"None",
",",
"b",
"=",
"None",
",",
"term",
"=",
"-",
"1",
")",
":",
"if",
"modelmat",
"is",
"None",
":",
"modelmat",
"=",
"self",
".",
"_modelmat",
"(",
"X",
"... | linear predictor
compute the linear predictor portion of the model
ie multiply the model matrix by the spline basis coefficients
Parameters
---------
at least 1 of (X, modelmat)
and
at least 1 of (b, feature)
X : array-like of shape (n_samples, m_features) or None, optional
containing the input dataset
if None, will attempt to use modelmat
modelmat : array-like or None, optional
contains the spline basis for each feature evaluated at the input
values for each feature, ie model matrix
if None, will attempt to construct the model matrix from X
b : array-like or None, optional
contains the spline coefficients
if None, will use current model coefficients
feature : int, optional
feature for which to compute the linear prediction
if -1, will compute for all features
Returns
-------
lp : np.array of shape (n_samples,) | [
"linear",
"predictor",
"compute",
"the",
"linear",
"predictor",
"portion",
"of",
"the",
"model",
"ie",
"multiply",
"the",
"model",
"matrix",
"by",
"the",
"spline",
"basis",
"coefficients"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L357-L393 |
225,607 | dswah/pyGAM | pygam/pygam.py | GAM.predict_mu | def predict_mu(self, X):
"""
preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
containing expected values under the model
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
lp = self._linear_predictor(X)
return self.link.mu(lp, self.distribution) | python | def predict_mu(self, X):
"""
preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
containing expected values under the model
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
lp = self._linear_predictor(X)
return self.link.mu(lp, self.distribution) | [
"def",
"predict_mu",
"(",
"self",
",",
"X",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"X",
"=",
"check_X",
"(",
"X",
",",
"n_feats",
"=",
"self",
".",
"statistics... | preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
containing expected values under the model | [
"preduct",
"expected",
"value",
"of",
"target",
"given",
"model",
"and",
"input",
"X"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L395-L417 |
225,608 | dswah/pyGAM | pygam/pygam.py | GAM._modelmat | def _modelmat(self, X, term=-1):
"""
Builds a model matrix, B, out of the spline basis for each feature
B = [B_0, B_1, ..., B_p]
Parameters
---------
X : array-like of shape (n_samples, m_features)
containing the input dataset
term : int, optional
term index for which to compute the model matrix
if -1, will create the model matrix for all features
Returns
-------
modelmat : sparse matrix of len n_samples
containing model matrix of the spline basis for selected features
"""
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
return self.terms.build_columns(X, term=term) | python | def _modelmat(self, X, term=-1):
"""
Builds a model matrix, B, out of the spline basis for each feature
B = [B_0, B_1, ..., B_p]
Parameters
---------
X : array-like of shape (n_samples, m_features)
containing the input dataset
term : int, optional
term index for which to compute the model matrix
if -1, will create the model matrix for all features
Returns
-------
modelmat : sparse matrix of len n_samples
containing model matrix of the spline basis for selected features
"""
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
return self.terms.build_columns(X, term=term) | [
"def",
"_modelmat",
"(",
"self",
",",
"X",
",",
"term",
"=",
"-",
"1",
")",
":",
"X",
"=",
"check_X",
"(",
"X",
",",
"n_feats",
"=",
"self",
".",
"statistics_",
"[",
"'m_features'",
"]",
",",
"edge_knots",
"=",
"self",
".",
"edge_knots_",
",",
"dty... | Builds a model matrix, B, out of the spline basis for each feature
B = [B_0, B_1, ..., B_p]
Parameters
---------
X : array-like of shape (n_samples, m_features)
containing the input dataset
term : int, optional
term index for which to compute the model matrix
if -1, will create the model matrix for all features
Returns
-------
modelmat : sparse matrix of len n_samples
containing model matrix of the spline basis for selected features | [
"Builds",
"a",
"model",
"matrix",
"B",
"out",
"of",
"the",
"spline",
"basis",
"for",
"each",
"feature"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L436-L459 |
225,609 | dswah/pyGAM | pygam/pygam.py | GAM._cholesky | def _cholesky(self, A, **kwargs):
"""
method to handle potential problems with the cholesky decomposition.
will try to increase L2 regularization of the penalty matrix to
do away with non-positive-definite errors
Parameters
----------
A : np.array
Returns
-------
np.array
"""
# create appropriate-size diagonal matrix
if sp.sparse.issparse(A):
diag = sp.sparse.eye(A.shape[0])
else:
diag = np.eye(A.shape[0])
constraint_l2 = self._constraint_l2
while constraint_l2 <= self._constraint_l2_max:
try:
L = cholesky(A, **kwargs)
self._constraint_l2 = constraint_l2
return L
except NotPositiveDefiniteError:
if self.verbose:
warnings.warn('Matrix is not positive definite. \n'\
'Increasing l2 reg by factor of 10.',
stacklevel=2)
A -= constraint_l2 * diag
constraint_l2 *= 10
A += constraint_l2 * diag
raise NotPositiveDefiniteError('Matrix is not positive \n'
'definite.') | python | def _cholesky(self, A, **kwargs):
"""
method to handle potential problems with the cholesky decomposition.
will try to increase L2 regularization of the penalty matrix to
do away with non-positive-definite errors
Parameters
----------
A : np.array
Returns
-------
np.array
"""
# create appropriate-size diagonal matrix
if sp.sparse.issparse(A):
diag = sp.sparse.eye(A.shape[0])
else:
diag = np.eye(A.shape[0])
constraint_l2 = self._constraint_l2
while constraint_l2 <= self._constraint_l2_max:
try:
L = cholesky(A, **kwargs)
self._constraint_l2 = constraint_l2
return L
except NotPositiveDefiniteError:
if self.verbose:
warnings.warn('Matrix is not positive definite. \n'\
'Increasing l2 reg by factor of 10.',
stacklevel=2)
A -= constraint_l2 * diag
constraint_l2 *= 10
A += constraint_l2 * diag
raise NotPositiveDefiniteError('Matrix is not positive \n'
'definite.') | [
"def",
"_cholesky",
"(",
"self",
",",
"A",
",",
"*",
"*",
"kwargs",
")",
":",
"# create appropriate-size diagonal matrix",
"if",
"sp",
".",
"sparse",
".",
"issparse",
"(",
"A",
")",
":",
"diag",
"=",
"sp",
".",
"sparse",
".",
"eye",
"(",
"A",
".",
"s... | method to handle potential problems with the cholesky decomposition.
will try to increase L2 regularization of the penalty matrix to
do away with non-positive-definite errors
Parameters
----------
A : np.array
Returns
-------
np.array | [
"method",
"to",
"handle",
"potential",
"problems",
"with",
"the",
"cholesky",
"decomposition",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L461-L498 |
225,610 | dswah/pyGAM | pygam/pygam.py | GAM._pseudo_data | def _pseudo_data(self, y, lp, mu):
"""
compute the pseudo data for a PIRLS iterations
Parameters
---------
y : array-like of shape (n,)
containing target data
lp : array-like of shape (n,)
containing linear predictions by the model
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
Returns
-------
pseudo_data : np.array of shape (n,)
"""
return lp + (y - mu) * self.link.gradient(mu, self.distribution) | python | def _pseudo_data(self, y, lp, mu):
"""
compute the pseudo data for a PIRLS iterations
Parameters
---------
y : array-like of shape (n,)
containing target data
lp : array-like of shape (n,)
containing linear predictions by the model
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
Returns
-------
pseudo_data : np.array of shape (n,)
"""
return lp + (y - mu) * self.link.gradient(mu, self.distribution) | [
"def",
"_pseudo_data",
"(",
"self",
",",
"y",
",",
"lp",
",",
"mu",
")",
":",
"return",
"lp",
"+",
"(",
"y",
"-",
"mu",
")",
"*",
"self",
".",
"link",
".",
"gradient",
"(",
"mu",
",",
"self",
".",
"distribution",
")"
] | compute the pseudo data for a PIRLS iterations
Parameters
---------
y : array-like of shape (n,)
containing target data
lp : array-like of shape (n,)
containing linear predictions by the model
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
Returns
-------
pseudo_data : np.array of shape (n,) | [
"compute",
"the",
"pseudo",
"data",
"for",
"a",
"PIRLS",
"iterations"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L542-L559 |
225,611 | dswah/pyGAM | pygam/pygam.py | GAM._initial_estimate | def _initial_estimate(self, y, modelmat):
"""
Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
---------
y : array-like of shape (n,)
containing target data
modelmat : sparse matrix of shape (n, m)
containing model matrix of the spline basis
Returns
-------
coef : array of shape (m,) containing the initial estimate for the model
coefficients
Notes
-----
This method implements the suggestions in
Wood, section 2.2.2 Geometry and IRLS convergence, pg 80
"""
# do a simple initialization for LinearGAMs
if isinstance(self, LinearGAM):
n, m = modelmat.shape
return np.ones(m) * np.sqrt(EPS)
# transform the problem to the linear scale
y = deepcopy(y).astype('float64')
y[y == 0] += .01 # edge case for log link, inverse link, and logit link
y[y == 1] -= .01 # edge case for logit link
y_ = self.link.link(y, self.distribution)
y_ = make_2d(y_, verbose=False)
assert np.isfinite(y_).all(), "transformed response values should be well-behaved."
# solve the linear problem
return np.linalg.solve(load_diagonal(modelmat.T.dot(modelmat).A),
modelmat.T.dot(y_)) | python | def _initial_estimate(self, y, modelmat):
"""
Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
---------
y : array-like of shape (n,)
containing target data
modelmat : sparse matrix of shape (n, m)
containing model matrix of the spline basis
Returns
-------
coef : array of shape (m,) containing the initial estimate for the model
coefficients
Notes
-----
This method implements the suggestions in
Wood, section 2.2.2 Geometry and IRLS convergence, pg 80
"""
# do a simple initialization for LinearGAMs
if isinstance(self, LinearGAM):
n, m = modelmat.shape
return np.ones(m) * np.sqrt(EPS)
# transform the problem to the linear scale
y = deepcopy(y).astype('float64')
y[y == 0] += .01 # edge case for log link, inverse link, and logit link
y[y == 1] -= .01 # edge case for logit link
y_ = self.link.link(y, self.distribution)
y_ = make_2d(y_, verbose=False)
assert np.isfinite(y_).all(), "transformed response values should be well-behaved."
# solve the linear problem
return np.linalg.solve(load_diagonal(modelmat.T.dot(modelmat).A),
modelmat.T.dot(y_)) | [
"def",
"_initial_estimate",
"(",
"self",
",",
"y",
",",
"modelmat",
")",
":",
"# do a simple initialization for LinearGAMs",
"if",
"isinstance",
"(",
"self",
",",
"LinearGAM",
")",
":",
"n",
",",
"m",
"=",
"modelmat",
".",
"shape",
"return",
"np",
".",
"ones... | Makes an inital estimate for the model coefficients.
For a LinearGAM we simply initialize to small coefficients.
For other GAMs we transform the problem to the linear space
and solve an unpenalized version.
Parameters
---------
y : array-like of shape (n,)
containing target data
modelmat : sparse matrix of shape (n, m)
containing model matrix of the spline basis
Returns
-------
coef : array of shape (m,) containing the initial estimate for the model
coefficients
Notes
-----
This method implements the suggestions in
Wood, section 2.2.2 Geometry and IRLS convergence, pg 80 | [
"Makes",
"an",
"inital",
"estimate",
"for",
"the",
"model",
"coefficients",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L621-L664 |
225,612 | dswah/pyGAM | pygam/pygam.py | GAM._on_loop_start | def _on_loop_start(self, variables):
"""
performs on-loop-start actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None
"""
for callback in self.callbacks:
if hasattr(callback, 'on_loop_start'):
self.logs_[str(callback)].append(callback.on_loop_start(**variables)) | python | def _on_loop_start(self, variables):
"""
performs on-loop-start actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None
"""
for callback in self.callbacks:
if hasattr(callback, 'on_loop_start'):
self.logs_[str(callback)].append(callback.on_loop_start(**variables)) | [
"def",
"_on_loop_start",
"(",
"self",
",",
"variables",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"if",
"hasattr",
"(",
"callback",
",",
"'on_loop_start'",
")",
":",
"self",
".",
"logs_",
"[",
"str",
"(",
"callback",
")",
"]",
"... | performs on-loop-start actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None | [
"performs",
"on",
"-",
"loop",
"-",
"start",
"actions",
"like",
"callbacks"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L834-L850 |
225,613 | dswah/pyGAM | pygam/pygam.py | GAM._on_loop_end | def _on_loop_end(self, variables):
"""
performs on-loop-end actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None
"""
for callback in self.callbacks:
if hasattr(callback, 'on_loop_end'):
self.logs_[str(callback)].append(callback.on_loop_end(**variables)) | python | def _on_loop_end(self, variables):
"""
performs on-loop-end actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None
"""
for callback in self.callbacks:
if hasattr(callback, 'on_loop_end'):
self.logs_[str(callback)].append(callback.on_loop_end(**variables)) | [
"def",
"_on_loop_end",
"(",
"self",
",",
"variables",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"if",
"hasattr",
"(",
"callback",
",",
"'on_loop_end'",
")",
":",
"self",
".",
"logs_",
"[",
"str",
"(",
"callback",
")",
"]",
".",
... | performs on-loop-end actions like callbacks
variables contains local namespace variables.
Parameters
---------
variables : dict of available variables
Returns
-------
None | [
"performs",
"on",
"-",
"loop",
"-",
"end",
"actions",
"like",
"callbacks"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L852-L868 |
225,614 | dswah/pyGAM | pygam/pygam.py | GAM.deviance_residuals | def deviance_residuals(self, X, y, weights=None, scaled=False):
"""
method to compute the deviance residuals of the model
these are analogous to the residuals of an OLS.
Parameters
----------
X : array-like
Input data array of shape (n_saples, m_features)
y : array-like
Output data vector of shape (n_samples,)
weights : array-like shape (n_samples,) or None, optional
Sample weights.
if None, defaults to array of ones
scaled : bool, optional
whether to scale the deviance by the (estimated) distribution scale
Returns
-------
deviance_residuals : np.array
with shape (n_samples,)
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
y = check_y(y, self.link, self.distribution, verbose=self.verbose)
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
check_X_y(X, y)
if weights is not None:
weights = np.array(weights).astype('f').ravel()
weights = check_array(weights, name='sample weights',
ndim=1, verbose=self.verbose)
check_lengths(y, weights)
else:
weights = np.ones_like(y).astype('float64')
mu = self.predict_mu(X)
sign = np.sign(y-mu)
return sign * self.distribution.deviance(y, mu,
weights=weights,
scaled=scaled) ** 0.5 | python | def deviance_residuals(self, X, y, weights=None, scaled=False):
"""
method to compute the deviance residuals of the model
these are analogous to the residuals of an OLS.
Parameters
----------
X : array-like
Input data array of shape (n_saples, m_features)
y : array-like
Output data vector of shape (n_samples,)
weights : array-like shape (n_samples,) or None, optional
Sample weights.
if None, defaults to array of ones
scaled : bool, optional
whether to scale the deviance by the (estimated) distribution scale
Returns
-------
deviance_residuals : np.array
with shape (n_samples,)
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
y = check_y(y, self.link, self.distribution, verbose=self.verbose)
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
check_X_y(X, y)
if weights is not None:
weights = np.array(weights).astype('f').ravel()
weights = check_array(weights, name='sample weights',
ndim=1, verbose=self.verbose)
check_lengths(y, weights)
else:
weights = np.ones_like(y).astype('float64')
mu = self.predict_mu(X)
sign = np.sign(y-mu)
return sign * self.distribution.deviance(y, mu,
weights=weights,
scaled=scaled) ** 0.5 | [
"def",
"deviance_residuals",
"(",
"self",
",",
"X",
",",
"y",
",",
"weights",
"=",
"None",
",",
"scaled",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
... | method to compute the deviance residuals of the model
these are analogous to the residuals of an OLS.
Parameters
----------
X : array-like
Input data array of shape (n_saples, m_features)
y : array-like
Output data vector of shape (n_samples,)
weights : array-like shape (n_samples,) or None, optional
Sample weights.
if None, defaults to array of ones
scaled : bool, optional
whether to scale the deviance by the (estimated) distribution scale
Returns
-------
deviance_residuals : np.array
with shape (n_samples,) | [
"method",
"to",
"compute",
"the",
"deviance",
"residuals",
"of",
"the",
"model"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L927-L971 |
225,615 | dswah/pyGAM | pygam/pygam.py | GAM._estimate_model_statistics | def _estimate_model_statistics(self, y, modelmat, inner=None, BW=None,
B=None, weights=None, U1=None):
"""
method to compute all of the model statistics
results are stored in the 'statistics_' attribute of the model, as a
dictionary keyed by:
- edof: estimated degrees freedom
- scale: distribution scale, if applicable
- cov: coefficient covariances
- se: standarrd errors
- AIC: Akaike Information Criterion
- AICc: corrected Akaike Information Criterion
- pseudo_r2: dict of Pseudo R-squared metrics
- GCV: generailized cross-validation
or
- UBRE: Un-Biased Risk Estimator
- n_samples: number of samples used in estimation
Parameters
----------
y : array-like
output data vector of shape (n_samples,)
modelmat : array-like, default: None
contains the spline basis for each feature evaluated at the input
inner : array of intermediate computations from naive optimization
BW : array of intermediate computations from either optimization
B : array of intermediate computations from stable optimization
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
U1 : cropped U matrix from SVD.
Returns
-------
None
"""
lp = self._linear_predictor(modelmat=modelmat)
mu = self.link.mu(lp, self.distribution)
self.statistics_['edof_per_coef'] = np.diagonal(U1.dot(U1.T))
self.statistics_['edof'] = self.statistics_['edof_per_coef'].sum()
if not self.distribution._known_scale:
self.distribution.scale = self.distribution.phi(y=y, mu=mu, edof=self.statistics_['edof'], weights=weights)
self.statistics_['scale'] = self.distribution.scale
self.statistics_['cov'] = (B.dot(B.T)) * self.distribution.scale # parameter covariances. no need to remove a W because we are using W^2. Wood pg 184
self.statistics_['se'] = self.statistics_['cov'].diagonal()**0.5
self.statistics_['AIC'] = self._estimate_AIC(y=y, mu=mu, weights=weights)
self.statistics_['AICc'] = self._estimate_AICc(y=y, mu=mu, weights=weights)
self.statistics_['pseudo_r2'] = self._estimate_r2(y=y, mu=mu, weights=weights)
self.statistics_['GCV'], self.statistics_['UBRE'] = self._estimate_GCV_UBRE(modelmat=modelmat, y=y, weights=weights)
self.statistics_['loglikelihood'] = self._loglikelihood(y, mu, weights=weights)
self.statistics_['deviance'] = self.distribution.deviance(y=y, mu=mu, weights=weights).sum()
self.statistics_['p_values'] = self._estimate_p_values() | python | def _estimate_model_statistics(self, y, modelmat, inner=None, BW=None,
B=None, weights=None, U1=None):
"""
method to compute all of the model statistics
results are stored in the 'statistics_' attribute of the model, as a
dictionary keyed by:
- edof: estimated degrees freedom
- scale: distribution scale, if applicable
- cov: coefficient covariances
- se: standarrd errors
- AIC: Akaike Information Criterion
- AICc: corrected Akaike Information Criterion
- pseudo_r2: dict of Pseudo R-squared metrics
- GCV: generailized cross-validation
or
- UBRE: Un-Biased Risk Estimator
- n_samples: number of samples used in estimation
Parameters
----------
y : array-like
output data vector of shape (n_samples,)
modelmat : array-like, default: None
contains the spline basis for each feature evaluated at the input
inner : array of intermediate computations from naive optimization
BW : array of intermediate computations from either optimization
B : array of intermediate computations from stable optimization
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
U1 : cropped U matrix from SVD.
Returns
-------
None
"""
lp = self._linear_predictor(modelmat=modelmat)
mu = self.link.mu(lp, self.distribution)
self.statistics_['edof_per_coef'] = np.diagonal(U1.dot(U1.T))
self.statistics_['edof'] = self.statistics_['edof_per_coef'].sum()
if not self.distribution._known_scale:
self.distribution.scale = self.distribution.phi(y=y, mu=mu, edof=self.statistics_['edof'], weights=weights)
self.statistics_['scale'] = self.distribution.scale
self.statistics_['cov'] = (B.dot(B.T)) * self.distribution.scale # parameter covariances. no need to remove a W because we are using W^2. Wood pg 184
self.statistics_['se'] = self.statistics_['cov'].diagonal()**0.5
self.statistics_['AIC'] = self._estimate_AIC(y=y, mu=mu, weights=weights)
self.statistics_['AICc'] = self._estimate_AICc(y=y, mu=mu, weights=weights)
self.statistics_['pseudo_r2'] = self._estimate_r2(y=y, mu=mu, weights=weights)
self.statistics_['GCV'], self.statistics_['UBRE'] = self._estimate_GCV_UBRE(modelmat=modelmat, y=y, weights=weights)
self.statistics_['loglikelihood'] = self._loglikelihood(y, mu, weights=weights)
self.statistics_['deviance'] = self.distribution.deviance(y=y, mu=mu, weights=weights).sum()
self.statistics_['p_values'] = self._estimate_p_values() | [
"def",
"_estimate_model_statistics",
"(",
"self",
",",
"y",
",",
"modelmat",
",",
"inner",
"=",
"None",
",",
"BW",
"=",
"None",
",",
"B",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"U1",
"=",
"None",
")",
":",
"lp",
"=",
"self",
".",
"_linear_p... | method to compute all of the model statistics
results are stored in the 'statistics_' attribute of the model, as a
dictionary keyed by:
- edof: estimated degrees freedom
- scale: distribution scale, if applicable
- cov: coefficient covariances
- se: standarrd errors
- AIC: Akaike Information Criterion
- AICc: corrected Akaike Information Criterion
- pseudo_r2: dict of Pseudo R-squared metrics
- GCV: generailized cross-validation
or
- UBRE: Un-Biased Risk Estimator
- n_samples: number of samples used in estimation
Parameters
----------
y : array-like
output data vector of shape (n_samples,)
modelmat : array-like, default: None
contains the spline basis for each feature evaluated at the input
inner : array of intermediate computations from naive optimization
BW : array of intermediate computations from either optimization
B : array of intermediate computations from stable optimization
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
U1 : cropped U matrix from SVD.
Returns
-------
None | [
"method",
"to",
"compute",
"all",
"of",
"the",
"model",
"statistics"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L973-L1025 |
225,616 | dswah/pyGAM | pygam/pygam.py | GAM._estimate_AIC | def _estimate_AIC(self, y, mu, weights=None):
"""
estimate the Akaike Information Criterion
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,),
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None
"""
estimated_scale = not(self.distribution._known_scale) # if we estimate the scale, that adds 2 dof
return -2*self._loglikelihood(y=y, mu=mu, weights=weights) + \
2*self.statistics_['edof'] + 2*estimated_scale | python | def _estimate_AIC(self, y, mu, weights=None):
"""
estimate the Akaike Information Criterion
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,),
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None
"""
estimated_scale = not(self.distribution._known_scale) # if we estimate the scale, that adds 2 dof
return -2*self._loglikelihood(y=y, mu=mu, weights=weights) + \
2*self.statistics_['edof'] + 2*estimated_scale | [
"def",
"_estimate_AIC",
"(",
"self",
",",
"y",
",",
"mu",
",",
"weights",
"=",
"None",
")",
":",
"estimated_scale",
"=",
"not",
"(",
"self",
".",
"distribution",
".",
"_known_scale",
")",
"# if we estimate the scale, that adds 2 dof",
"return",
"-",
"2",
"*",
... | estimate the Akaike Information Criterion
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,),
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None | [
"estimate",
"the",
"Akaike",
"Information",
"Criterion"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1027-L1047 |
225,617 | dswah/pyGAM | pygam/pygam.py | GAM._estimate_AICc | def _estimate_AICc(self, y, mu, weights=None):
"""
estimate the corrected Akaike Information Criterion
relies on the estimated degrees of freedom, which must be computed
before.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None
"""
edof = self.statistics_['edof']
if self.statistics_['AIC'] is None:
self.statistics_['AIC'] = self._estimate_AIC(y, mu, weights)
return self.statistics_['AIC'] + 2*(edof + 1)*(edof + 2)/(y.shape[0] - edof -2) | python | def _estimate_AICc(self, y, mu, weights=None):
"""
estimate the corrected Akaike Information Criterion
relies on the estimated degrees of freedom, which must be computed
before.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None
"""
edof = self.statistics_['edof']
if self.statistics_['AIC'] is None:
self.statistics_['AIC'] = self._estimate_AIC(y, mu, weights)
return self.statistics_['AIC'] + 2*(edof + 1)*(edof + 2)/(y.shape[0] - edof -2) | [
"def",
"_estimate_AICc",
"(",
"self",
",",
"y",
",",
"mu",
",",
"weights",
"=",
"None",
")",
":",
"edof",
"=",
"self",
".",
"statistics_",
"[",
"'edof'",
"]",
"if",
"self",
".",
"statistics_",
"[",
"'AIC'",
"]",
"is",
"None",
":",
"self",
".",
"sta... | estimate the corrected Akaike Information Criterion
relies on the estimated degrees of freedom, which must be computed
before.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None | [
"estimate",
"the",
"corrected",
"Akaike",
"Information",
"Criterion"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1049-L1073 |
225,618 | dswah/pyGAM | pygam/pygam.py | GAM._estimate_r2 | def _estimate_r2(self, X=None, y=None, mu=None, weights=None):
"""
estimate some pseudo R^2 values
currently only computes explained deviance.
results are stored
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None
"""
if mu is None:
mu = self.predict_mu(X=X)
if weights is None:
weights = np.ones_like(y).astype('float64')
null_mu = y.mean() * np.ones_like(y).astype('float64')
null_d = self.distribution.deviance(y=y, mu=null_mu, weights=weights)
full_d = self.distribution.deviance(y=y, mu=mu, weights=weights)
null_ll = self._loglikelihood(y=y, mu=null_mu, weights=weights)
full_ll = self._loglikelihood(y=y, mu=mu, weights=weights)
r2 = OrderedDict()
r2['explained_deviance'] = 1. - full_d.sum()/null_d.sum()
r2['McFadden'] = full_ll/null_ll
r2['McFadden_adj'] = 1. - (full_ll - self.statistics_['edof'])/null_ll
return r2 | python | def _estimate_r2(self, X=None, y=None, mu=None, weights=None):
"""
estimate some pseudo R^2 values
currently only computes explained deviance.
results are stored
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None
"""
if mu is None:
mu = self.predict_mu(X=X)
if weights is None:
weights = np.ones_like(y).astype('float64')
null_mu = y.mean() * np.ones_like(y).astype('float64')
null_d = self.distribution.deviance(y=y, mu=null_mu, weights=weights)
full_d = self.distribution.deviance(y=y, mu=mu, weights=weights)
null_ll = self._loglikelihood(y=y, mu=null_mu, weights=weights)
full_ll = self._loglikelihood(y=y, mu=mu, weights=weights)
r2 = OrderedDict()
r2['explained_deviance'] = 1. - full_d.sum()/null_d.sum()
r2['McFadden'] = full_ll/null_ll
r2['McFadden_adj'] = 1. - (full_ll - self.statistics_['edof'])/null_ll
return r2 | [
"def",
"_estimate_r2",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"mu",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"if",
"mu",
"is",
"None",
":",
"mu",
"=",
"self",
".",
"predict_mu",
"(",
"X",
"=",
"X",
")",
"if... | estimate some pseudo R^2 values
currently only computes explained deviance.
results are stored
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
mu : array-like of shape (n_samples,)
expected value of the targets given the model and inputs
weights : array-like shape (n_samples,) or None, optional
containing sample weights
if None, defaults to array of ones
Returns
-------
None | [
"estimate",
"some",
"pseudo",
"R^2",
"values"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1075-L1115 |
225,619 | dswah/pyGAM | pygam/pygam.py | GAM._estimate_GCV_UBRE | def _estimate_GCV_UBRE(self, X=None, y=None, modelmat=None, gamma=1.4,
add_scale=True, weights=None):
"""
Generalized Cross Validation and Un-Biased Risk Estimator.
UBRE is used when the scale parameter is known,
like Poisson and Binomial families.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
modelmat : array-like, default: None
contains the spline basis for each feature evaluated at the input
gamma : float, default: 1.4
serves as a weighting to increase the impact of the influence matrix
on the score
add_scale : boolean, default: True
UBRE score can be negative because the distribution scale
is subtracted. to keep things positive we can add the scale back.
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
score : float
Either GCV or UBRE, depending on if the scale parameter is known.
Notes
-----
Sometimes the GCV or UBRE selected model is deemed to be too wiggly,
and a smoother model is desired. One way to achieve this, in a
systematic way, is to increase the amount that each model effective
degree of freedom counts, in the GCV or UBRE score, by a factor γ ≥ 1
see Wood 2006 pg. 177-182, 220 for more details.
"""
if gamma < 1:
raise ValueError('gamma scaling should be greater than 1, '\
'but found gamma = {}',format(gamma))
if modelmat is None:
modelmat = self._modelmat(X)
if weights is None:
weights = np.ones_like(y).astype('float64')
lp = self._linear_predictor(modelmat=modelmat)
mu = self.link.mu(lp, self.distribution)
n = y.shape[0]
edof = self.statistics_['edof']
GCV = None
UBRE = None
dev = self.distribution.deviance(mu=mu, y=y, scaled=False, weights=weights).sum()
if self.distribution._known_scale:
# scale is known, use UBRE
scale = self.distribution.scale
UBRE = 1./n * dev - (~add_scale)*(scale) + 2.*gamma/n * edof * scale
else:
# scale unkown, use GCV
GCV = (n * dev) / (n - gamma * edof)**2
return (GCV, UBRE) | python | def _estimate_GCV_UBRE(self, X=None, y=None, modelmat=None, gamma=1.4,
add_scale=True, weights=None):
"""
Generalized Cross Validation and Un-Biased Risk Estimator.
UBRE is used when the scale parameter is known,
like Poisson and Binomial families.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
modelmat : array-like, default: None
contains the spline basis for each feature evaluated at the input
gamma : float, default: 1.4
serves as a weighting to increase the impact of the influence matrix
on the score
add_scale : boolean, default: True
UBRE score can be negative because the distribution scale
is subtracted. to keep things positive we can add the scale back.
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
score : float
Either GCV or UBRE, depending on if the scale parameter is known.
Notes
-----
Sometimes the GCV or UBRE selected model is deemed to be too wiggly,
and a smoother model is desired. One way to achieve this, in a
systematic way, is to increase the amount that each model effective
degree of freedom counts, in the GCV or UBRE score, by a factor γ ≥ 1
see Wood 2006 pg. 177-182, 220 for more details.
"""
if gamma < 1:
raise ValueError('gamma scaling should be greater than 1, '\
'but found gamma = {}',format(gamma))
if modelmat is None:
modelmat = self._modelmat(X)
if weights is None:
weights = np.ones_like(y).astype('float64')
lp = self._linear_predictor(modelmat=modelmat)
mu = self.link.mu(lp, self.distribution)
n = y.shape[0]
edof = self.statistics_['edof']
GCV = None
UBRE = None
dev = self.distribution.deviance(mu=mu, y=y, scaled=False, weights=weights).sum()
if self.distribution._known_scale:
# scale is known, use UBRE
scale = self.distribution.scale
UBRE = 1./n * dev - (~add_scale)*(scale) + 2.*gamma/n * edof * scale
else:
# scale unkown, use GCV
GCV = (n * dev) / (n - gamma * edof)**2
return (GCV, UBRE) | [
"def",
"_estimate_GCV_UBRE",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"modelmat",
"=",
"None",
",",
"gamma",
"=",
"1.4",
",",
"add_scale",
"=",
"True",
",",
"weights",
"=",
"None",
")",
":",
"if",
"gamma",
"<",
"1",
":",
"r... | Generalized Cross Validation and Un-Biased Risk Estimator.
UBRE is used when the scale parameter is known,
like Poisson and Binomial families.
Parameters
----------
y : array-like of shape (n_samples,)
output data vector
modelmat : array-like, default: None
contains the spline basis for each feature evaluated at the input
gamma : float, default: 1.4
serves as a weighting to increase the impact of the influence matrix
on the score
add_scale : boolean, default: True
UBRE score can be negative because the distribution scale
is subtracted. to keep things positive we can add the scale back.
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
score : float
Either GCV or UBRE, depending on if the scale parameter is known.
Notes
-----
Sometimes the GCV or UBRE selected model is deemed to be too wiggly,
and a smoother model is desired. One way to achieve this, in a
systematic way, is to increase the amount that each model effective
degree of freedom counts, in the GCV or UBRE score, by a factor γ ≥ 1
see Wood 2006 pg. 177-182, 220 for more details. | [
"Generalized",
"Cross",
"Validation",
"and",
"Un",
"-",
"Biased",
"Risk",
"Estimator",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1117-L1182 |
225,620 | dswah/pyGAM | pygam/pygam.py | GAM._estimate_p_values | def _estimate_p_values(self):
"""estimate the p-values for all features
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
p_values = []
for term_i in range(len(self.terms)):
p_values.append(self._compute_p_value(term_i))
return p_values | python | def _estimate_p_values(self):
"""estimate the p-values for all features
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
p_values = []
for term_i in range(len(self.terms)):
p_values.append(self._compute_p_value(term_i))
return p_values | [
"def",
"_estimate_p_values",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"p_values",
"=",
"[",
"]",
"for",
"term_i",
"in",
"range",
"(",
"len",
"(",
"sel... | estimate the p-values for all features | [
"estimate",
"the",
"p",
"-",
"values",
"for",
"all",
"features"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1184-L1194 |
225,621 | dswah/pyGAM | pygam/pygam.py | GAM._compute_p_value | def _compute_p_value(self, term_i):
"""compute the p-value of the desired feature
Arguments
---------
term_i : int
term to select from the data
Returns
-------
p_value : float
Notes
-----
Wood 2006, section 4.8.5:
The p-values, calculated in this manner, behave correctly for un-penalized models,
or models with known smoothing parameters, but when smoothing parameters have
been estimated, the p-values are typically lower than they should be, meaning that
the tests reject the null too readily.
(...)
In practical terms, if these p-values suggest that a term is not needed in a model,
then this is probably true, but if a term is deemed ‘significant’ it is important to be
aware that this significance may be overstated.
based on equations from Wood 2006 section 4.8.5 page 191
and errata https://people.maths.bris.ac.uk/~sw15190/igam/iGAMerrata-12.pdf
the errata shows a correction for the f-statisitc.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
idxs = self.terms.get_coef_indices(term_i)
cov = self.statistics_['cov'][idxs][:, idxs]
coef = self.coef_[idxs]
# center non-intercept term functions
if isinstance(self.terms[term_i], SplineTerm):
coef -= coef.mean()
inv_cov, rank = sp.linalg.pinv(cov, return_rank=True)
score = coef.T.dot(inv_cov).dot(coef)
# compute p-values
if self.distribution._known_scale:
# for known scale use chi-squared statistic
return 1 - sp.stats.chi2.cdf(x=score, df=rank)
else:
# if scale has been estimated, prefer to use f-statisitc
score = score / rank
return 1 - sp.stats.f.cdf(score, rank, self.statistics_['n_samples'] - self.statistics_['edof']) | python | def _compute_p_value(self, term_i):
"""compute the p-value of the desired feature
Arguments
---------
term_i : int
term to select from the data
Returns
-------
p_value : float
Notes
-----
Wood 2006, section 4.8.5:
The p-values, calculated in this manner, behave correctly for un-penalized models,
or models with known smoothing parameters, but when smoothing parameters have
been estimated, the p-values are typically lower than they should be, meaning that
the tests reject the null too readily.
(...)
In practical terms, if these p-values suggest that a term is not needed in a model,
then this is probably true, but if a term is deemed ‘significant’ it is important to be
aware that this significance may be overstated.
based on equations from Wood 2006 section 4.8.5 page 191
and errata https://people.maths.bris.ac.uk/~sw15190/igam/iGAMerrata-12.pdf
the errata shows a correction for the f-statisitc.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
idxs = self.terms.get_coef_indices(term_i)
cov = self.statistics_['cov'][idxs][:, idxs]
coef = self.coef_[idxs]
# center non-intercept term functions
if isinstance(self.terms[term_i], SplineTerm):
coef -= coef.mean()
inv_cov, rank = sp.linalg.pinv(cov, return_rank=True)
score = coef.T.dot(inv_cov).dot(coef)
# compute p-values
if self.distribution._known_scale:
# for known scale use chi-squared statistic
return 1 - sp.stats.chi2.cdf(x=score, df=rank)
else:
# if scale has been estimated, prefer to use f-statisitc
score = score / rank
return 1 - sp.stats.f.cdf(score, rank, self.statistics_['n_samples'] - self.statistics_['edof']) | [
"def",
"_compute_p_value",
"(",
"self",
",",
"term_i",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"idxs",
"=",
"self",
".",
"terms",
".",
"get_coef_indices",
"(",
"ter... | compute the p-value of the desired feature
Arguments
---------
term_i : int
term to select from the data
Returns
-------
p_value : float
Notes
-----
Wood 2006, section 4.8.5:
The p-values, calculated in this manner, behave correctly for un-penalized models,
or models with known smoothing parameters, but when smoothing parameters have
been estimated, the p-values are typically lower than they should be, meaning that
the tests reject the null too readily.
(...)
In practical terms, if these p-values suggest that a term is not needed in a model,
then this is probably true, but if a term is deemed ‘significant’ it is important to be
aware that this significance may be overstated.
based on equations from Wood 2006 section 4.8.5 page 191
and errata https://people.maths.bris.ac.uk/~sw15190/igam/iGAMerrata-12.pdf
the errata shows a correction for the f-statisitc. | [
"compute",
"the",
"p",
"-",
"value",
"of",
"the",
"desired",
"feature"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1196-L1248 |
225,622 | dswah/pyGAM | pygam/pygam.py | GAM.confidence_intervals | def confidence_intervals(self, X, width=.95, quantiles=None):
"""estimate confidence intervals for the model.
Parameters
----------
X : array-like of shape (n_samples, m_features)
Input data matrix
width : float on [0,1], optional
quantiles : array-like of floats in (0, 1), optional
Instead of specifying the prediciton width, one can specify the
quantiles. So ``width=.95`` is equivalent to ``quantiles=[.025, .975]``
Returns
-------
intervals: np.array of shape (n_samples, 2 or len(quantiles))
Notes
-----
Wood 2006, section 4.9
Confidence intervals based on section 4.8 rely on large sample results to deal with
non-Gaussian distributions, and treat the smoothing parameters as fixed, when in
reality they are estimated from the data.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
return self._get_quantiles(X, width, quantiles, prediction=False) | python | def confidence_intervals(self, X, width=.95, quantiles=None):
"""estimate confidence intervals for the model.
Parameters
----------
X : array-like of shape (n_samples, m_features)
Input data matrix
width : float on [0,1], optional
quantiles : array-like of floats in (0, 1), optional
Instead of specifying the prediciton width, one can specify the
quantiles. So ``width=.95`` is equivalent to ``quantiles=[.025, .975]``
Returns
-------
intervals: np.array of shape (n_samples, 2 or len(quantiles))
Notes
-----
Wood 2006, section 4.9
Confidence intervals based on section 4.8 rely on large sample results to deal with
non-Gaussian distributions, and treat the smoothing parameters as fixed, when in
reality they are estimated from the data.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
return self._get_quantiles(X, width, quantiles, prediction=False) | [
"def",
"confidence_intervals",
"(",
"self",
",",
"X",
",",
"width",
"=",
".95",
",",
"quantiles",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"X",
"=",
... | estimate confidence intervals for the model.
Parameters
----------
X : array-like of shape (n_samples, m_features)
Input data matrix
width : float on [0,1], optional
quantiles : array-like of floats in (0, 1), optional
Instead of specifying the prediciton width, one can specify the
quantiles. So ``width=.95`` is equivalent to ``quantiles=[.025, .975]``
Returns
-------
intervals: np.array of shape (n_samples, 2 or len(quantiles))
Notes
-----
Wood 2006, section 4.9
Confidence intervals based on section 4.8 rely on large sample results to deal with
non-Gaussian distributions, and treat the smoothing parameters as fixed, when in
reality they are estimated from the data. | [
"estimate",
"confidence",
"intervals",
"for",
"the",
"model",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1250-L1281 |
225,623 | dswah/pyGAM | pygam/pygam.py | GAM._get_quantiles | def _get_quantiles(self, X, width, quantiles, modelmat=None, lp=None,
prediction=False, xform=True, term=-1):
"""
estimate prediction intervals for LinearGAM
Parameters
----------
X : array
input data of shape (n_samples, m_features)
width : float on (0, 1)
quantiles : array-like of floats on (0, 1)
instead of specifying the prediciton width, one can specify the
quantiles. so width=.95 is equivalent to quantiles=[.025, .975]
modelmat : array of shape or None, default: None
lp : array or None, default: None
prediction : bool, default: True.
whether to compute prediction intervals (True)
or confidence intervals (False)
xform : bool, default: True,
whether to apply the inverse link function and return values
on the scale of the distribution mean (True),
or to keep on the linear predictor scale (False)
term : int, default: -1
Returns
-------
intervals: np.array of shape (n_samples, 2 or len(quantiles))
Notes
-----
when the scale parameter is known, then we can proceed with a large
sample approximation to the distribution of the model coefficients
where B_hat ~ Normal(B, cov)
when the scale parameter is unknown, then we have to account for
the distribution of the estimated scale parameter, which is Chi-squared.
since we scale our estimate of B_hat by the sqrt of estimated scale,
we get a t distribution: Normal / sqrt(Chi-squared) ~ t
see Simon Wood section 1.3.2, 1.3.3, 1.5.5, 2.1.5
"""
if quantiles is not None:
quantiles = np.atleast_1d(quantiles)
else:
alpha = (1 - width)/2.
quantiles = [alpha, 1 - alpha]
for quantile in quantiles:
if (quantile >= 1) or (quantile <= 0):
raise ValueError('quantiles must be in (0, 1), but found {}'\
.format(quantiles))
if modelmat is None:
modelmat = self._modelmat(X, term=term)
if lp is None:
lp = self._linear_predictor(modelmat=modelmat, term=term)
idxs = self.terms.get_coef_indices(term)
cov = self.statistics_['cov'][idxs][:, idxs]
var = (modelmat.dot(cov) * modelmat.A).sum(axis=1)
if prediction:
var += self.distribution.scale
lines = []
for quantile in quantiles:
if self.distribution._known_scale:
q = sp.stats.norm.ppf(quantile)
else:
q = sp.stats.t.ppf(quantile, df=self.statistics_['n_samples'] -
self.statistics_['edof'])
lines.append(lp + q * var**0.5)
lines = np.vstack(lines).T
if xform:
lines = self.link.mu(lines, self.distribution)
return lines | python | def _get_quantiles(self, X, width, quantiles, modelmat=None, lp=None,
prediction=False, xform=True, term=-1):
"""
estimate prediction intervals for LinearGAM
Parameters
----------
X : array
input data of shape (n_samples, m_features)
width : float on (0, 1)
quantiles : array-like of floats on (0, 1)
instead of specifying the prediciton width, one can specify the
quantiles. so width=.95 is equivalent to quantiles=[.025, .975]
modelmat : array of shape or None, default: None
lp : array or None, default: None
prediction : bool, default: True.
whether to compute prediction intervals (True)
or confidence intervals (False)
xform : bool, default: True,
whether to apply the inverse link function and return values
on the scale of the distribution mean (True),
or to keep on the linear predictor scale (False)
term : int, default: -1
Returns
-------
intervals: np.array of shape (n_samples, 2 or len(quantiles))
Notes
-----
when the scale parameter is known, then we can proceed with a large
sample approximation to the distribution of the model coefficients
where B_hat ~ Normal(B, cov)
when the scale parameter is unknown, then we have to account for
the distribution of the estimated scale parameter, which is Chi-squared.
since we scale our estimate of B_hat by the sqrt of estimated scale,
we get a t distribution: Normal / sqrt(Chi-squared) ~ t
see Simon Wood section 1.3.2, 1.3.3, 1.5.5, 2.1.5
"""
if quantiles is not None:
quantiles = np.atleast_1d(quantiles)
else:
alpha = (1 - width)/2.
quantiles = [alpha, 1 - alpha]
for quantile in quantiles:
if (quantile >= 1) or (quantile <= 0):
raise ValueError('quantiles must be in (0, 1), but found {}'\
.format(quantiles))
if modelmat is None:
modelmat = self._modelmat(X, term=term)
if lp is None:
lp = self._linear_predictor(modelmat=modelmat, term=term)
idxs = self.terms.get_coef_indices(term)
cov = self.statistics_['cov'][idxs][:, idxs]
var = (modelmat.dot(cov) * modelmat.A).sum(axis=1)
if prediction:
var += self.distribution.scale
lines = []
for quantile in quantiles:
if self.distribution._known_scale:
q = sp.stats.norm.ppf(quantile)
else:
q = sp.stats.t.ppf(quantile, df=self.statistics_['n_samples'] -
self.statistics_['edof'])
lines.append(lp + q * var**0.5)
lines = np.vstack(lines).T
if xform:
lines = self.link.mu(lines, self.distribution)
return lines | [
"def",
"_get_quantiles",
"(",
"self",
",",
"X",
",",
"width",
",",
"quantiles",
",",
"modelmat",
"=",
"None",
",",
"lp",
"=",
"None",
",",
"prediction",
"=",
"False",
",",
"xform",
"=",
"True",
",",
"term",
"=",
"-",
"1",
")",
":",
"if",
"quantiles... | estimate prediction intervals for LinearGAM
Parameters
----------
X : array
input data of shape (n_samples, m_features)
width : float on (0, 1)
quantiles : array-like of floats on (0, 1)
instead of specifying the prediciton width, one can specify the
quantiles. so width=.95 is equivalent to quantiles=[.025, .975]
modelmat : array of shape or None, default: None
lp : array or None, default: None
prediction : bool, default: True.
whether to compute prediction intervals (True)
or confidence intervals (False)
xform : bool, default: True,
whether to apply the inverse link function and return values
on the scale of the distribution mean (True),
or to keep on the linear predictor scale (False)
term : int, default: -1
Returns
-------
intervals: np.array of shape (n_samples, 2 or len(quantiles))
Notes
-----
when the scale parameter is known, then we can proceed with a large
sample approximation to the distribution of the model coefficients
where B_hat ~ Normal(B, cov)
when the scale parameter is unknown, then we have to account for
the distribution of the estimated scale parameter, which is Chi-squared.
since we scale our estimate of B_hat by the sqrt of estimated scale,
we get a t distribution: Normal / sqrt(Chi-squared) ~ t
see Simon Wood section 1.3.2, 1.3.3, 1.5.5, 2.1.5 | [
"estimate",
"prediction",
"intervals",
"for",
"LinearGAM"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1283-L1359 |
225,624 | dswah/pyGAM | pygam/pygam.py | GAM._flatten_mesh | def _flatten_mesh(self, Xs, term):
"""flatten the mesh and distribute into a feature matrix"""
n = Xs[0].size
if self.terms[term].istensor:
terms = self.terms[term]
else:
terms = [self.terms[term]]
X = np.zeros((n, self.statistics_['m_features']))
for term_, x in zip(terms, Xs):
X[:, term_.feature] = x.ravel()
return X | python | def _flatten_mesh(self, Xs, term):
"""flatten the mesh and distribute into a feature matrix"""
n = Xs[0].size
if self.terms[term].istensor:
terms = self.terms[term]
else:
terms = [self.terms[term]]
X = np.zeros((n, self.statistics_['m_features']))
for term_, x in zip(terms, Xs):
X[:, term_.feature] = x.ravel()
return X | [
"def",
"_flatten_mesh",
"(",
"self",
",",
"Xs",
",",
"term",
")",
":",
"n",
"=",
"Xs",
"[",
"0",
"]",
".",
"size",
"if",
"self",
".",
"terms",
"[",
"term",
"]",
".",
"istensor",
":",
"terms",
"=",
"self",
".",
"terms",
"[",
"term",
"]",
"else",... | flatten the mesh and distribute into a feature matrix | [
"flatten",
"the",
"mesh",
"and",
"distribute",
"into",
"a",
"feature",
"matrix"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1361-L1373 |
225,625 | dswah/pyGAM | pygam/pygam.py | GAM.generate_X_grid | def generate_X_grid(self, term, n=100, meshgrid=False):
"""create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
where deg is the degree of the interaction of the term
Parameters
----------
term : int,
Which term to process.
n : int, optional
number of data points to create
meshgrid : bool, optional
Whether to return a meshgrid (useful for 3d plotting)
or a feature matrix (useful for inference like partial predictions)
Returns
-------
if meshgrid is False:
np.array of shape (n, n_features)
where m is the number of
(sub)terms in the requested (tensor)term.
else:
tuple of len m,
where m is the number of (sub)terms in the requested
(tensor)term.
each element in the tuple contains a np.ndarray of size (n)^m
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
# cant do Intercept
if self.terms[term].isintercept:
raise ValueError('cannot create grid for intercept term')
# process each subterm in a TensorTerm
if self.terms[term].istensor:
Xs = []
for term_ in self.terms[term]:
Xs.append(np.linspace(term_.edge_knots_[0],
term_.edge_knots_[1],
num=n))
Xs = np.meshgrid(*Xs, indexing='ij')
if meshgrid:
return tuple(Xs)
else:
return self._flatten_mesh(Xs, term=term)
# all other Terms
elif hasattr(self.terms[term], 'edge_knots_'):
x = np.linspace(self.terms[term].edge_knots_[0],
self.terms[term].edge_knots_[1],
num=n)
if meshgrid:
return (x,)
# fill in feature matrix with only relevant features for this term
X = np.zeros((n, self.statistics_['m_features']))
X[:, self.terms[term].feature] = x
if getattr(self.terms[term], 'by', None) is not None:
X[:, self.terms[term].by] = 1.
return X
# dont know what to do here
else:
raise TypeError('Unexpected term type: {}'.format(self.terms[term])) | python | def generate_X_grid(self, term, n=100, meshgrid=False):
"""create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
where deg is the degree of the interaction of the term
Parameters
----------
term : int,
Which term to process.
n : int, optional
number of data points to create
meshgrid : bool, optional
Whether to return a meshgrid (useful for 3d plotting)
or a feature matrix (useful for inference like partial predictions)
Returns
-------
if meshgrid is False:
np.array of shape (n, n_features)
where m is the number of
(sub)terms in the requested (tensor)term.
else:
tuple of len m,
where m is the number of (sub)terms in the requested
(tensor)term.
each element in the tuple contains a np.ndarray of size (n)^m
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
# cant do Intercept
if self.terms[term].isintercept:
raise ValueError('cannot create grid for intercept term')
# process each subterm in a TensorTerm
if self.terms[term].istensor:
Xs = []
for term_ in self.terms[term]:
Xs.append(np.linspace(term_.edge_knots_[0],
term_.edge_knots_[1],
num=n))
Xs = np.meshgrid(*Xs, indexing='ij')
if meshgrid:
return tuple(Xs)
else:
return self._flatten_mesh(Xs, term=term)
# all other Terms
elif hasattr(self.terms[term], 'edge_knots_'):
x = np.linspace(self.terms[term].edge_knots_[0],
self.terms[term].edge_knots_[1],
num=n)
if meshgrid:
return (x,)
# fill in feature matrix with only relevant features for this term
X = np.zeros((n, self.statistics_['m_features']))
X[:, self.terms[term].feature] = x
if getattr(self.terms[term], 'by', None) is not None:
X[:, self.terms[term].by] = 1.
return X
# dont know what to do here
else:
raise TypeError('Unexpected term type: {}'.format(self.terms[term])) | [
"def",
"generate_X_grid",
"(",
"self",
",",
"term",
",",
"n",
"=",
"100",
",",
"meshgrid",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"# cant do Intercep... | create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
where deg is the degree of the interaction of the term
Parameters
----------
term : int,
Which term to process.
n : int, optional
number of data points to create
meshgrid : bool, optional
Whether to return a meshgrid (useful for 3d plotting)
or a feature matrix (useful for inference like partial predictions)
Returns
-------
if meshgrid is False:
np.array of shape (n, n_features)
where m is the number of
(sub)terms in the requested (tensor)term.
else:
tuple of len m,
where m is the number of (sub)terms in the requested
(tensor)term.
each element in the tuple contains a np.ndarray of size (n)^m
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term. | [
"create",
"a",
"nice",
"grid",
"of",
"X",
"data"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1375-L1456 |
225,626 | dswah/pyGAM | pygam/pygam.py | GAM.partial_dependence | def partial_dependence(self, term, X=None, width=None, quantiles=None,
meshgrid=False):
"""
Computes the term functions for the GAM
and possibly their confidence intervals.
if both width=None and quantiles=None,
then no confidence intervals are computed
Parameters
----------
term : int, optional
Term for which to compute the partial dependence functions.
X : array-like with input data, optional
if `meshgrid=False`, then `X` should be an array-like
of shape (n_samples, m_features).
if `meshgrid=True`, then `X` should be a tuple containing
an array for each feature in the term.
if None, an equally spaced grid of points is generated.
width : float on (0, 1), optional
Width of the confidence interval.
quantiles : array-like of floats on (0, 1), optional
instead of specifying the prediciton width, one can specify the
quantiles. so width=.95 is equivalent to quantiles=[.025, .975].
if None, defaults to width.
meshgrid : bool, whether to return and accept meshgrids.
Useful for creating outputs that are suitable for
3D plotting.
Note, for simple terms with no interactions, the output
of this function will be the same for ``meshgrid=True`` and
``meshgrid=False``, but the inputs will need to be different.
Returns
-------
pdeps : np.array of shape (n_samples,)
conf_intervals : list of length len(term)
containing np.arrays of shape (n_samples, 2 or len(quantiles))
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
See Also
--------
generate_X_grid : for help creating meshgrids.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
if not isinstance(term, int):
raise ValueError('term must be an integer, but found term: {}'.format(term))
# ensure term exists
if (term >= len(self.terms)) or (term < -1):
raise ValueError('Term {} out of range for model with {} terms'\
.format(term, len(self.terms)))
# cant do Intercept
if self.terms[term].isintercept:
raise ValueError('cannot create grid for intercept term')
if X is None:
X = self.generate_X_grid(term=term, meshgrid=meshgrid)
if meshgrid:
if not isinstance(X, tuple):
raise ValueError('X must be a tuple of grids if `meshgrid=True`, '\
'but found X: {}'.format(X))
shape = X[0].shape
X = self._flatten_mesh(X, term=term)
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
modelmat = self._modelmat(X, term=term)
pdep = self._linear_predictor(modelmat=modelmat, term=term)
out = [pdep]
compute_quantiles = (width is not None) or (quantiles is not None)
if compute_quantiles:
conf_intervals = self._get_quantiles(X, width=width,
quantiles=quantiles,
modelmat=modelmat,
lp=pdep,
term=term,
xform=False)
out += [conf_intervals]
if meshgrid:
for i, array in enumerate(out):
# add extra dimensions arising from multiple confidence intervals
if array.ndim > 1:
depth = array.shape[-1]
shape += (depth,)
out[i] = np.reshape(array, shape)
if compute_quantiles:
return out
return out[0] | python | def partial_dependence(self, term, X=None, width=None, quantiles=None,
meshgrid=False):
"""
Computes the term functions for the GAM
and possibly their confidence intervals.
if both width=None and quantiles=None,
then no confidence intervals are computed
Parameters
----------
term : int, optional
Term for which to compute the partial dependence functions.
X : array-like with input data, optional
if `meshgrid=False`, then `X` should be an array-like
of shape (n_samples, m_features).
if `meshgrid=True`, then `X` should be a tuple containing
an array for each feature in the term.
if None, an equally spaced grid of points is generated.
width : float on (0, 1), optional
Width of the confidence interval.
quantiles : array-like of floats on (0, 1), optional
instead of specifying the prediciton width, one can specify the
quantiles. so width=.95 is equivalent to quantiles=[.025, .975].
if None, defaults to width.
meshgrid : bool, whether to return and accept meshgrids.
Useful for creating outputs that are suitable for
3D plotting.
Note, for simple terms with no interactions, the output
of this function will be the same for ``meshgrid=True`` and
``meshgrid=False``, but the inputs will need to be different.
Returns
-------
pdeps : np.array of shape (n_samples,)
conf_intervals : list of length len(term)
containing np.arrays of shape (n_samples, 2 or len(quantiles))
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
See Also
--------
generate_X_grid : for help creating meshgrids.
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
if not isinstance(term, int):
raise ValueError('term must be an integer, but found term: {}'.format(term))
# ensure term exists
if (term >= len(self.terms)) or (term < -1):
raise ValueError('Term {} out of range for model with {} terms'\
.format(term, len(self.terms)))
# cant do Intercept
if self.terms[term].isintercept:
raise ValueError('cannot create grid for intercept term')
if X is None:
X = self.generate_X_grid(term=term, meshgrid=meshgrid)
if meshgrid:
if not isinstance(X, tuple):
raise ValueError('X must be a tuple of grids if `meshgrid=True`, '\
'but found X: {}'.format(X))
shape = X[0].shape
X = self._flatten_mesh(X, term=term)
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
modelmat = self._modelmat(X, term=term)
pdep = self._linear_predictor(modelmat=modelmat, term=term)
out = [pdep]
compute_quantiles = (width is not None) or (quantiles is not None)
if compute_quantiles:
conf_intervals = self._get_quantiles(X, width=width,
quantiles=quantiles,
modelmat=modelmat,
lp=pdep,
term=term,
xform=False)
out += [conf_intervals]
if meshgrid:
for i, array in enumerate(out):
# add extra dimensions arising from multiple confidence intervals
if array.ndim > 1:
depth = array.shape[-1]
shape += (depth,)
out[i] = np.reshape(array, shape)
if compute_quantiles:
return out
return out[0] | [
"def",
"partial_dependence",
"(",
"self",
",",
"term",
",",
"X",
"=",
"None",
",",
"width",
"=",
"None",
",",
"quantiles",
"=",
"None",
",",
"meshgrid",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"("... | Computes the term functions for the GAM
and possibly their confidence intervals.
if both width=None and quantiles=None,
then no confidence intervals are computed
Parameters
----------
term : int, optional
Term for which to compute the partial dependence functions.
X : array-like with input data, optional
if `meshgrid=False`, then `X` should be an array-like
of shape (n_samples, m_features).
if `meshgrid=True`, then `X` should be a tuple containing
an array for each feature in the term.
if None, an equally spaced grid of points is generated.
width : float on (0, 1), optional
Width of the confidence interval.
quantiles : array-like of floats on (0, 1), optional
instead of specifying the prediciton width, one can specify the
quantiles. so width=.95 is equivalent to quantiles=[.025, .975].
if None, defaults to width.
meshgrid : bool, whether to return and accept meshgrids.
Useful for creating outputs that are suitable for
3D plotting.
Note, for simple terms with no interactions, the output
of this function will be the same for ``meshgrid=True`` and
``meshgrid=False``, but the inputs will need to be different.
Returns
-------
pdeps : np.array of shape (n_samples,)
conf_intervals : list of length len(term)
containing np.arrays of shape (n_samples, 2 or len(quantiles))
Raises
------
ValueError :
If the term requested is an intercept
since it does not make sense to process the intercept term.
See Also
--------
generate_X_grid : for help creating meshgrids. | [
"Computes",
"the",
"term",
"functions",
"for",
"the",
"GAM",
"and",
"possibly",
"their",
"confidence",
"intervals",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1458-L1570 |
225,627 | dswah/pyGAM | pygam/pygam.py | GAM.sample | def sample(self, X, y, quantity='y', sample_at_X=None,
weights=None, n_draws=100, n_bootstraps=5, objective='auto'):
"""Simulate from the posterior of the coefficients and smoothing params.
Samples are drawn from the posterior of the coefficients and smoothing
parameters given the response in an approximate way. The GAM must
already be fitted before calling this method; if the model has not
been fitted, then an exception is raised. Moreover, it is recommended
that the model and its hyperparameters be chosen with `gridsearch`
(with the parameter `keep_best=True`) before calling `sample`, so that
the result of that gridsearch can be used to generate useful response
data and so that the model's coefficients (and their covariance matrix)
can be used as the first bootstrap sample.
These samples are drawn as follows. Details are in the reference below.
1. ``n_bootstraps`` many "bootstrap samples" of the response (``y``) are
simulated by drawing random samples from the model's distribution
evaluated at the expected values (``mu``) for each sample in ``X``.
2. A copy of the model is fitted to each of those bootstrap samples of
the response. The result is an approximation of the distribution over
the smoothing parameter ``lam`` given the response data ``y``.
3. Samples of the coefficients are simulated from a multivariate normal
using the bootstrap samples of the coefficients and their covariance
matrices.
Notes
-----
A ``gridsearch`` is done ``n_bootstraps`` many times, so keep
``n_bootstraps`` small. Make ``n_bootstraps < n_draws`` to take advantage
of the expensive bootstrap samples of the smoothing parameters.
Parameters
-----------
X : array of shape (n_samples, m_features)
empirical input data
y : array of shape (n_samples,)
empirical response vector
quantity : {'y', 'coef', 'mu'}, default: 'y'
What quantity to return pseudorandom samples of.
If `sample_at_X` is not None and `quantity` is either `'y'` or
`'mu'`, then samples are drawn at the values of `X` specified in
`sample_at_X`.
sample_at_X : array of shape (n_samples_to_simulate, m_features) or
None, optional
Input data at which to draw new samples.
Only applies for `quantity` equal to `'y'` or to `'mu`'.
If `None`, then `sample_at_X` is replaced by `X`.
weights : np.array of shape (n_samples,)
sample weights
n_draws : positive int, optional (default=100)
The number of samples to draw from the posterior distribution of
the coefficients and smoothing parameters
n_bootstraps : positive int, optional (default=5)
The number of bootstrap samples to draw from simulations of the
response (from the already fitted model) to estimate the
distribution of the smoothing parameters given the response data.
If `n_bootstraps` is 1, then only the already fitted model's
smoothing parameter is used, and the distribution over the
smoothing parameters is not estimated using bootstrap sampling.
objective : string, optional (default='auto'
metric to optimize in grid search. must be in
['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with
unknown scale and UBRE for models with known scale.
Returns
-------
draws : 2D array of length n_draws
Simulations of the given `quantity` using samples from the
posterior distribution of the coefficients and smoothing parameter
given the response data. Each row is a pseudorandom sample.
If `quantity == 'coef'`, then the number of columns of `draws` is
the number of coefficients (`len(self.coef_)`).
Otherwise, the number of columns of `draws` is the number of
rows of `sample_at_X` if `sample_at_X` is not `None` or else
the number of rows of `X`.
References
----------
Simon N. Wood, 2006. Generalized Additive Models: an introduction with
R. Section 4.9.3 (pages 198–199) and Section 5.4.2 (page 256–257).
"""
if quantity not in {'mu', 'coef', 'y'}:
raise ValueError("`quantity` must be one of 'mu', 'coef', 'y';"
" got {}".format(quantity))
coef_draws = self._sample_coef(
X, y, weights=weights, n_draws=n_draws,
n_bootstraps=n_bootstraps, objective=objective)
if quantity == 'coef':
return coef_draws
if sample_at_X is None:
sample_at_X = X
linear_predictor = self._modelmat(sample_at_X).dot(coef_draws.T)
mu_shape_n_draws_by_n_samples = self.link.mu(
linear_predictor, self.distribution).T
if quantity == 'mu':
return mu_shape_n_draws_by_n_samples
else:
return self.distribution.sample(mu_shape_n_draws_by_n_samples) | python | def sample(self, X, y, quantity='y', sample_at_X=None,
weights=None, n_draws=100, n_bootstraps=5, objective='auto'):
"""Simulate from the posterior of the coefficients and smoothing params.
Samples are drawn from the posterior of the coefficients and smoothing
parameters given the response in an approximate way. The GAM must
already be fitted before calling this method; if the model has not
been fitted, then an exception is raised. Moreover, it is recommended
that the model and its hyperparameters be chosen with `gridsearch`
(with the parameter `keep_best=True`) before calling `sample`, so that
the result of that gridsearch can be used to generate useful response
data and so that the model's coefficients (and their covariance matrix)
can be used as the first bootstrap sample.
These samples are drawn as follows. Details are in the reference below.
1. ``n_bootstraps`` many "bootstrap samples" of the response (``y``) are
simulated by drawing random samples from the model's distribution
evaluated at the expected values (``mu``) for each sample in ``X``.
2. A copy of the model is fitted to each of those bootstrap samples of
the response. The result is an approximation of the distribution over
the smoothing parameter ``lam`` given the response data ``y``.
3. Samples of the coefficients are simulated from a multivariate normal
using the bootstrap samples of the coefficients and their covariance
matrices.
Notes
-----
A ``gridsearch`` is done ``n_bootstraps`` many times, so keep
``n_bootstraps`` small. Make ``n_bootstraps < n_draws`` to take advantage
of the expensive bootstrap samples of the smoothing parameters.
Parameters
-----------
X : array of shape (n_samples, m_features)
empirical input data
y : array of shape (n_samples,)
empirical response vector
quantity : {'y', 'coef', 'mu'}, default: 'y'
What quantity to return pseudorandom samples of.
If `sample_at_X` is not None and `quantity` is either `'y'` or
`'mu'`, then samples are drawn at the values of `X` specified in
`sample_at_X`.
sample_at_X : array of shape (n_samples_to_simulate, m_features) or
None, optional
Input data at which to draw new samples.
Only applies for `quantity` equal to `'y'` or to `'mu`'.
If `None`, then `sample_at_X` is replaced by `X`.
weights : np.array of shape (n_samples,)
sample weights
n_draws : positive int, optional (default=100)
The number of samples to draw from the posterior distribution of
the coefficients and smoothing parameters
n_bootstraps : positive int, optional (default=5)
The number of bootstrap samples to draw from simulations of the
response (from the already fitted model) to estimate the
distribution of the smoothing parameters given the response data.
If `n_bootstraps` is 1, then only the already fitted model's
smoothing parameter is used, and the distribution over the
smoothing parameters is not estimated using bootstrap sampling.
objective : string, optional (default='auto'
metric to optimize in grid search. must be in
['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with
unknown scale and UBRE for models with known scale.
Returns
-------
draws : 2D array of length n_draws
Simulations of the given `quantity` using samples from the
posterior distribution of the coefficients and smoothing parameter
given the response data. Each row is a pseudorandom sample.
If `quantity == 'coef'`, then the number of columns of `draws` is
the number of coefficients (`len(self.coef_)`).
Otherwise, the number of columns of `draws` is the number of
rows of `sample_at_X` if `sample_at_X` is not `None` or else
the number of rows of `X`.
References
----------
Simon N. Wood, 2006. Generalized Additive Models: an introduction with
R. Section 4.9.3 (pages 198–199) and Section 5.4.2 (page 256–257).
"""
if quantity not in {'mu', 'coef', 'y'}:
raise ValueError("`quantity` must be one of 'mu', 'coef', 'y';"
" got {}".format(quantity))
coef_draws = self._sample_coef(
X, y, weights=weights, n_draws=n_draws,
n_bootstraps=n_bootstraps, objective=objective)
if quantity == 'coef':
return coef_draws
if sample_at_X is None:
sample_at_X = X
linear_predictor = self._modelmat(sample_at_X).dot(coef_draws.T)
mu_shape_n_draws_by_n_samples = self.link.mu(
linear_predictor, self.distribution).T
if quantity == 'mu':
return mu_shape_n_draws_by_n_samples
else:
return self.distribution.sample(mu_shape_n_draws_by_n_samples) | [
"def",
"sample",
"(",
"self",
",",
"X",
",",
"y",
",",
"quantity",
"=",
"'y'",
",",
"sample_at_X",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"n_draws",
"=",
"100",
",",
"n_bootstraps",
"=",
"5",
",",
"objective",
"=",
"'auto'",
")",
":",
"if",... | Simulate from the posterior of the coefficients and smoothing params.
Samples are drawn from the posterior of the coefficients and smoothing
parameters given the response in an approximate way. The GAM must
already be fitted before calling this method; if the model has not
been fitted, then an exception is raised. Moreover, it is recommended
that the model and its hyperparameters be chosen with `gridsearch`
(with the parameter `keep_best=True`) before calling `sample`, so that
the result of that gridsearch can be used to generate useful response
data and so that the model's coefficients (and their covariance matrix)
can be used as the first bootstrap sample.
These samples are drawn as follows. Details are in the reference below.
1. ``n_bootstraps`` many "bootstrap samples" of the response (``y``) are
simulated by drawing random samples from the model's distribution
evaluated at the expected values (``mu``) for each sample in ``X``.
2. A copy of the model is fitted to each of those bootstrap samples of
the response. The result is an approximation of the distribution over
the smoothing parameter ``lam`` given the response data ``y``.
3. Samples of the coefficients are simulated from a multivariate normal
using the bootstrap samples of the coefficients and their covariance
matrices.
Notes
-----
A ``gridsearch`` is done ``n_bootstraps`` many times, so keep
``n_bootstraps`` small. Make ``n_bootstraps < n_draws`` to take advantage
of the expensive bootstrap samples of the smoothing parameters.
Parameters
-----------
X : array of shape (n_samples, m_features)
empirical input data
y : array of shape (n_samples,)
empirical response vector
quantity : {'y', 'coef', 'mu'}, default: 'y'
What quantity to return pseudorandom samples of.
If `sample_at_X` is not None and `quantity` is either `'y'` or
`'mu'`, then samples are drawn at the values of `X` specified in
`sample_at_X`.
sample_at_X : array of shape (n_samples_to_simulate, m_features) or
None, optional
Input data at which to draw new samples.
Only applies for `quantity` equal to `'y'` or to `'mu`'.
If `None`, then `sample_at_X` is replaced by `X`.
weights : np.array of shape (n_samples,)
sample weights
n_draws : positive int, optional (default=100)
The number of samples to draw from the posterior distribution of
the coefficients and smoothing parameters
n_bootstraps : positive int, optional (default=5)
The number of bootstrap samples to draw from simulations of the
response (from the already fitted model) to estimate the
distribution of the smoothing parameters given the response data.
If `n_bootstraps` is 1, then only the already fitted model's
smoothing parameter is used, and the distribution over the
smoothing parameters is not estimated using bootstrap sampling.
objective : string, optional (default='auto'
metric to optimize in grid search. must be in
['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with
unknown scale and UBRE for models with known scale.
Returns
-------
draws : 2D array of length n_draws
Simulations of the given `quantity` using samples from the
posterior distribution of the coefficients and smoothing parameter
given the response data. Each row is a pseudorandom sample.
If `quantity == 'coef'`, then the number of columns of `draws` is
the number of coefficients (`len(self.coef_)`).
Otherwise, the number of columns of `draws` is the number of
rows of `sample_at_X` if `sample_at_X` is not `None` or else
the number of rows of `X`.
References
----------
Simon N. Wood, 2006. Generalized Additive Models: an introduction with
R. Section 4.9.3 (pages 198–199) and Section 5.4.2 (page 256–257). | [
"Simulate",
"from",
"the",
"posterior",
"of",
"the",
"coefficients",
"and",
"smoothing",
"params",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L1929-L2044 |
225,628 | dswah/pyGAM | pygam/pygam.py | GAM._sample_coef | def _sample_coef(self, X, y, weights=None, n_draws=100, n_bootstraps=1,
objective='auto'):
"""Simulate from the posterior of the coefficients.
NOTE: A `gridsearch` is done `n_bootstraps` many times, so keep
`n_bootstraps` small. Make `n_bootstraps < n_draws` to take advantage
of the expensive bootstrap samples of the smoothing parameters.
Parameters
-----------
X : array of shape (n_samples, m_features)
input data
y : array of shape (n_samples,)
response vector
weights : np.array of shape (n_samples,)
sample weights
n_draws : positive int, optional (default=100
The number of samples to draw from the posterior distribution of
the coefficients and smoothing parameters
n_bootstraps : positive int, optional (default=1
The number of bootstrap samples to draw from simulations of the
response (from the already fitted model) to estimate the
distribution of the smoothing parameters given the response data.
If `n_bootstraps` is 1, then only the already fitted model's
smoothing parameters is used.
objective : string, optional (default='auto'
metric to optimize in grid search. must be in
['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with
unknown scale and UBRE for models with known scale.
Returns
-------
coef_samples : array of shape (n_draws, n_samples)
Approximate simulations of the coefficients drawn from the
posterior distribution of the coefficients and smoothing
parameters given the response data
References
----------
Simon N. Wood, 2006. Generalized Additive Models: an introduction with
R. Section 4.9.3 (pages 198–199) and Section 5.4.2 (page 256–257).
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
if n_bootstraps < 1:
raise ValueError('n_bootstraps must be >= 1;'
' got {}'.format(n_bootstraps))
if n_draws < 1:
raise ValueError('n_draws must be >= 1;'
' got {}'.format(n_draws))
coef_bootstraps, cov_bootstraps = (
self._bootstrap_samples_of_smoothing(X, y, weights=weights,
n_bootstraps=n_bootstraps,
objective=objective))
coef_draws = self._simulate_coef_from_bootstraps(
n_draws, coef_bootstraps, cov_bootstraps)
return coef_draws | python | def _sample_coef(self, X, y, weights=None, n_draws=100, n_bootstraps=1,
objective='auto'):
"""Simulate from the posterior of the coefficients.
NOTE: A `gridsearch` is done `n_bootstraps` many times, so keep
`n_bootstraps` small. Make `n_bootstraps < n_draws` to take advantage
of the expensive bootstrap samples of the smoothing parameters.
Parameters
-----------
X : array of shape (n_samples, m_features)
input data
y : array of shape (n_samples,)
response vector
weights : np.array of shape (n_samples,)
sample weights
n_draws : positive int, optional (default=100
The number of samples to draw from the posterior distribution of
the coefficients and smoothing parameters
n_bootstraps : positive int, optional (default=1
The number of bootstrap samples to draw from simulations of the
response (from the already fitted model) to estimate the
distribution of the smoothing parameters given the response data.
If `n_bootstraps` is 1, then only the already fitted model's
smoothing parameters is used.
objective : string, optional (default='auto'
metric to optimize in grid search. must be in
['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with
unknown scale and UBRE for models with known scale.
Returns
-------
coef_samples : array of shape (n_draws, n_samples)
Approximate simulations of the coefficients drawn from the
posterior distribution of the coefficients and smoothing
parameters given the response data
References
----------
Simon N. Wood, 2006. Generalized Additive Models: an introduction with
R. Section 4.9.3 (pages 198–199) and Section 5.4.2 (page 256–257).
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
if n_bootstraps < 1:
raise ValueError('n_bootstraps must be >= 1;'
' got {}'.format(n_bootstraps))
if n_draws < 1:
raise ValueError('n_draws must be >= 1;'
' got {}'.format(n_draws))
coef_bootstraps, cov_bootstraps = (
self._bootstrap_samples_of_smoothing(X, y, weights=weights,
n_bootstraps=n_bootstraps,
objective=objective))
coef_draws = self._simulate_coef_from_bootstraps(
n_draws, coef_bootstraps, cov_bootstraps)
return coef_draws | [
"def",
"_sample_coef",
"(",
"self",
",",
"X",
",",
"y",
",",
"weights",
"=",
"None",
",",
"n_draws",
"=",
"100",
",",
"n_bootstraps",
"=",
"1",
",",
"objective",
"=",
"'auto'",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"Attribut... | Simulate from the posterior of the coefficients.
NOTE: A `gridsearch` is done `n_bootstraps` many times, so keep
`n_bootstraps` small. Make `n_bootstraps < n_draws` to take advantage
of the expensive bootstrap samples of the smoothing parameters.
Parameters
-----------
X : array of shape (n_samples, m_features)
input data
y : array of shape (n_samples,)
response vector
weights : np.array of shape (n_samples,)
sample weights
n_draws : positive int, optional (default=100
The number of samples to draw from the posterior distribution of
the coefficients and smoothing parameters
n_bootstraps : positive int, optional (default=1
The number of bootstrap samples to draw from simulations of the
response (from the already fitted model) to estimate the
distribution of the smoothing parameters given the response data.
If `n_bootstraps` is 1, then only the already fitted model's
smoothing parameters is used.
objective : string, optional (default='auto'
metric to optimize in grid search. must be in
['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with
unknown scale and UBRE for models with known scale.
Returns
-------
coef_samples : array of shape (n_draws, n_samples)
Approximate simulations of the coefficients drawn from the
posterior distribution of the coefficients and smoothing
parameters given the response data
References
----------
Simon N. Wood, 2006. Generalized Additive Models: an introduction with
R. Section 4.9.3 (pages 198–199) and Section 5.4.2 (page 256–257). | [
"Simulate",
"from",
"the",
"posterior",
"of",
"the",
"coefficients",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2046-L2110 |
225,629 | dswah/pyGAM | pygam/pygam.py | GAM._bootstrap_samples_of_smoothing | def _bootstrap_samples_of_smoothing(self, X, y, weights=None,
n_bootstraps=1, objective='auto'):
"""Sample the smoothing parameters using simulated response data.
For now, the grid of `lam` values is 11 random points in M-dimensional
space, where M = the number of lam values, ie len(flatten(gam.lam))
all values are in [1e-3, 1e3]
"""
mu = self.predict_mu(X) # Wood pg. 198 step 1
coef_bootstraps = [self.coef_]
cov_bootstraps = [
load_diagonal(self.statistics_['cov'])]
for _ in range(n_bootstraps - 1): # Wood pg. 198 step 2
# generate response data from fitted model (Wood pg. 198 step 3)
y_bootstrap = self.distribution.sample(mu)
# fit smoothing parameters on the bootstrap data
# (Wood pg. 198 step 4)
# TODO: Either enable randomized searches over hyperparameters
# (like in sklearn's RandomizedSearchCV), or draw enough samples of
# `lam` so that each of these bootstrap samples get different
# values of `lam`. Right now, each bootstrap sample uses the exact
# same grid of values for `lam`, so it is not worth setting
# `n_bootstraps > 1`.
gam = deepcopy(self)
gam.set_params(self.get_params())
# create a random search of 11 points in lam space
# with all values in [1e-3, 1e3]
lam_grid = np.random.randn(11, len(flatten(self.lam))) * 6 - 3
lam_grid = np.exp(lam_grid)
gam.gridsearch(X, y_bootstrap, weights=weights, lam=lam_grid,
objective=objective)
lam = gam.lam
# fit coefficients on the original data given the smoothing params
# (Wood pg. 199 step 5)
gam = deepcopy(self)
gam.set_params(self.get_params())
gam.lam = lam
gam.fit(X, y, weights=weights)
coef_bootstraps.append(gam.coef_)
cov = load_diagonal(gam.statistics_['cov'])
cov_bootstraps.append(cov)
return coef_bootstraps, cov_bootstraps | python | def _bootstrap_samples_of_smoothing(self, X, y, weights=None,
n_bootstraps=1, objective='auto'):
"""Sample the smoothing parameters using simulated response data.
For now, the grid of `lam` values is 11 random points in M-dimensional
space, where M = the number of lam values, ie len(flatten(gam.lam))
all values are in [1e-3, 1e3]
"""
mu = self.predict_mu(X) # Wood pg. 198 step 1
coef_bootstraps = [self.coef_]
cov_bootstraps = [
load_diagonal(self.statistics_['cov'])]
for _ in range(n_bootstraps - 1): # Wood pg. 198 step 2
# generate response data from fitted model (Wood pg. 198 step 3)
y_bootstrap = self.distribution.sample(mu)
# fit smoothing parameters on the bootstrap data
# (Wood pg. 198 step 4)
# TODO: Either enable randomized searches over hyperparameters
# (like in sklearn's RandomizedSearchCV), or draw enough samples of
# `lam` so that each of these bootstrap samples get different
# values of `lam`. Right now, each bootstrap sample uses the exact
# same grid of values for `lam`, so it is not worth setting
# `n_bootstraps > 1`.
gam = deepcopy(self)
gam.set_params(self.get_params())
# create a random search of 11 points in lam space
# with all values in [1e-3, 1e3]
lam_grid = np.random.randn(11, len(flatten(self.lam))) * 6 - 3
lam_grid = np.exp(lam_grid)
gam.gridsearch(X, y_bootstrap, weights=weights, lam=lam_grid,
objective=objective)
lam = gam.lam
# fit coefficients on the original data given the smoothing params
# (Wood pg. 199 step 5)
gam = deepcopy(self)
gam.set_params(self.get_params())
gam.lam = lam
gam.fit(X, y, weights=weights)
coef_bootstraps.append(gam.coef_)
cov = load_diagonal(gam.statistics_['cov'])
cov_bootstraps.append(cov)
return coef_bootstraps, cov_bootstraps | [
"def",
"_bootstrap_samples_of_smoothing",
"(",
"self",
",",
"X",
",",
"y",
",",
"weights",
"=",
"None",
",",
"n_bootstraps",
"=",
"1",
",",
"objective",
"=",
"'auto'",
")",
":",
"mu",
"=",
"self",
".",
"predict_mu",
"(",
"X",
")",
"# Wood pg. 198 step 1",
... | Sample the smoothing parameters using simulated response data.
For now, the grid of `lam` values is 11 random points in M-dimensional
space, where M = the number of lam values, ie len(flatten(gam.lam))
all values are in [1e-3, 1e3] | [
"Sample",
"the",
"smoothing",
"parameters",
"using",
"simulated",
"response",
"data",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2112-L2162 |
225,630 | dswah/pyGAM | pygam/pygam.py | GAM._simulate_coef_from_bootstraps | def _simulate_coef_from_bootstraps(
self, n_draws, coef_bootstraps, cov_bootstraps):
"""Simulate coefficients using bootstrap samples."""
# Sample indices uniformly from {0, ..., n_bootstraps - 1}
# (Wood pg. 199 step 6)
random_bootstrap_indices = np.random.choice(
np.arange(len(coef_bootstraps)), size=n_draws, replace=True)
# Simulate `n_draws` many random coefficient vectors from a
# multivariate normal distribution with mean and covariance given by
# the bootstrap samples (indexed by `random_bootstrap_indices`) of
# `coef_bootstraps` and `cov_bootstraps`. Because it's faster to draw
# many samples from a certain distribution all at once, we make a dict
# mapping bootstrap indices to draw indices and use the `size`
# parameter of `np.random.multivariate_normal` to sample the draws
# needed from that bootstrap sample all at once.
bootstrap_index_to_draw_indices = defaultdict(list)
for draw_index, bootstrap_index in enumerate(random_bootstrap_indices):
bootstrap_index_to_draw_indices[bootstrap_index].append(draw_index)
coef_draws = np.empty((n_draws, len(self.coef_)))
for bootstrap, draw_indices in bootstrap_index_to_draw_indices.items():
coef_draws[draw_indices] = np.random.multivariate_normal(
coef_bootstraps[bootstrap], cov_bootstraps[bootstrap],
size=len(draw_indices))
return coef_draws | python | def _simulate_coef_from_bootstraps(
self, n_draws, coef_bootstraps, cov_bootstraps):
"""Simulate coefficients using bootstrap samples."""
# Sample indices uniformly from {0, ..., n_bootstraps - 1}
# (Wood pg. 199 step 6)
random_bootstrap_indices = np.random.choice(
np.arange(len(coef_bootstraps)), size=n_draws, replace=True)
# Simulate `n_draws` many random coefficient vectors from a
# multivariate normal distribution with mean and covariance given by
# the bootstrap samples (indexed by `random_bootstrap_indices`) of
# `coef_bootstraps` and `cov_bootstraps`. Because it's faster to draw
# many samples from a certain distribution all at once, we make a dict
# mapping bootstrap indices to draw indices and use the `size`
# parameter of `np.random.multivariate_normal` to sample the draws
# needed from that bootstrap sample all at once.
bootstrap_index_to_draw_indices = defaultdict(list)
for draw_index, bootstrap_index in enumerate(random_bootstrap_indices):
bootstrap_index_to_draw_indices[bootstrap_index].append(draw_index)
coef_draws = np.empty((n_draws, len(self.coef_)))
for bootstrap, draw_indices in bootstrap_index_to_draw_indices.items():
coef_draws[draw_indices] = np.random.multivariate_normal(
coef_bootstraps[bootstrap], cov_bootstraps[bootstrap],
size=len(draw_indices))
return coef_draws | [
"def",
"_simulate_coef_from_bootstraps",
"(",
"self",
",",
"n_draws",
",",
"coef_bootstraps",
",",
"cov_bootstraps",
")",
":",
"# Sample indices uniformly from {0, ..., n_bootstraps - 1}",
"# (Wood pg. 199 step 6)",
"random_bootstrap_indices",
"=",
"np",
".",
"random",
".",
"... | Simulate coefficients using bootstrap samples. | [
"Simulate",
"coefficients",
"using",
"bootstrap",
"samples",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2164-L2191 |
225,631 | dswah/pyGAM | pygam/pygam.py | LogisticGAM.accuracy | def accuracy(self, X=None, y=None, mu=None):
"""
computes the accuracy of the LogisticGAM
Parameters
----------
note: X or mu must be defined. defaults to mu
X : array-like of shape (n_samples, m_features), optional (default=None)
containing input data
y : array-like of shape (n,)
containing target data
mu : array-like of shape (n_samples,), optional (default=None
expected value of the targets given the model and inputs
Returns
-------
float in [0, 1]
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
y = check_y(y, self.link, self.distribution, verbose=self.verbose)
if X is not None:
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
if mu is None:
mu = self.predict_mu(X)
check_X_y(mu, y)
return ((mu > 0.5).astype(int) == y).mean() | python | def accuracy(self, X=None, y=None, mu=None):
"""
computes the accuracy of the LogisticGAM
Parameters
----------
note: X or mu must be defined. defaults to mu
X : array-like of shape (n_samples, m_features), optional (default=None)
containing input data
y : array-like of shape (n,)
containing target data
mu : array-like of shape (n_samples,), optional (default=None
expected value of the targets given the model and inputs
Returns
-------
float in [0, 1]
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
y = check_y(y, self.link, self.distribution, verbose=self.verbose)
if X is not None:
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
if mu is None:
mu = self.predict_mu(X)
check_X_y(mu, y)
return ((mu > 0.5).astype(int) == y).mean() | [
"def",
"accuracy",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
",",
"mu",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"y",
"=",
"che... | computes the accuracy of the LogisticGAM
Parameters
----------
note: X or mu must be defined. defaults to mu
X : array-like of shape (n_samples, m_features), optional (default=None)
containing input data
y : array-like of shape (n,)
containing target data
mu : array-like of shape (n_samples,), optional (default=None
expected value of the targets given the model and inputs
Returns
-------
float in [0, 1] | [
"computes",
"the",
"accuracy",
"of",
"the",
"LogisticGAM"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2395-L2426 |
225,632 | dswah/pyGAM | pygam/pygam.py | PoissonGAM._exposure_to_weights | def _exposure_to_weights(self, y, exposure=None, weights=None):
"""simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
y : y normalized by exposure
weights : array-like shape (n_samples,)
"""
y = y.ravel()
if exposure is not None:
exposure = np.array(exposure).astype('f').ravel()
exposure = check_array(exposure, name='sample exposure',
ndim=1, verbose=self.verbose)
else:
exposure = np.ones_like(y.ravel()).astype('float64')
# check data
exposure = exposure.ravel()
check_lengths(y, exposure)
# normalize response
y = y / exposure
if weights is not None:
weights = np.array(weights).astype('f').ravel()
weights = check_array(weights, name='sample weights',
ndim=1, verbose=self.verbose)
else:
weights = np.ones_like(y).astype('float64')
check_lengths(weights, exposure)
# set exposure as the weight
# we do this because we have divided our response
# so if we make an error of 1 now, we need it to count more heavily.
weights = weights * exposure
return y, weights | python | def _exposure_to_weights(self, y, exposure=None, weights=None):
"""simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
y : y normalized by exposure
weights : array-like shape (n_samples,)
"""
y = y.ravel()
if exposure is not None:
exposure = np.array(exposure).astype('f').ravel()
exposure = check_array(exposure, name='sample exposure',
ndim=1, verbose=self.verbose)
else:
exposure = np.ones_like(y.ravel()).astype('float64')
# check data
exposure = exposure.ravel()
check_lengths(y, exposure)
# normalize response
y = y / exposure
if weights is not None:
weights = np.array(weights).astype('f').ravel()
weights = check_array(weights, name='sample weights',
ndim=1, verbose=self.verbose)
else:
weights = np.ones_like(y).astype('float64')
check_lengths(weights, exposure)
# set exposure as the weight
# we do this because we have divided our response
# so if we make an error of 1 now, we need it to count more heavily.
weights = weights * exposure
return y, weights | [
"def",
"_exposure_to_weights",
"(",
"self",
",",
"y",
",",
"exposure",
"=",
"None",
",",
"weights",
"=",
"None",
")",
":",
"y",
"=",
"y",
".",
"ravel",
"(",
")",
"if",
"exposure",
"is",
"not",
"None",
":",
"exposure",
"=",
"np",
".",
"array",
"(",
... | simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
y : y normalized by exposure
weights : array-like shape (n_samples,) | [
"simple",
"tool",
"to",
"create",
"a",
"common",
"API"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2604-L2654 |
225,633 | dswah/pyGAM | pygam/pygam.py | PoissonGAM.predict | def predict(self, X, exposure=None):
"""
preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
containing the input dataset
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
Returns
-------
y : np.array of shape (n_samples,)
containing predicted values under the model
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
if exposure is not None:
exposure = np.array(exposure).astype('f')
else:
exposure = np.ones(X.shape[0]).astype('f')
check_lengths(X, exposure)
return self.predict_mu(X) * exposure | python | def predict(self, X, exposure=None):
"""
preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
containing the input dataset
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
Returns
-------
y : np.array of shape (n_samples,)
containing predicted values under the model
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
X = check_X(X, n_feats=self.statistics_['m_features'],
edge_knots=self.edge_knots_, dtypes=self.dtype,
features=self.feature, verbose=self.verbose)
if exposure is not None:
exposure = np.array(exposure).astype('f')
else:
exposure = np.ones(X.shape[0]).astype('f')
check_lengths(X, exposure)
return self.predict_mu(X) * exposure | [
"def",
"predict",
"(",
"self",
",",
"X",
",",
"exposure",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_fitted",
":",
"raise",
"AttributeError",
"(",
"'GAM has not been fitted. Call fit first.'",
")",
"X",
"=",
"check_X",
"(",
"X",
",",
"n_feats",
... | preduct expected value of target given model and input X
often this is done via expected value of GAM given input X
Parameters
---------
X : array-like of shape (n_samples, m_features), default: None
containing the input dataset
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
Returns
-------
y : np.array of shape (n_samples,)
containing predicted values under the model | [
"preduct",
"expected",
"value",
"of",
"target",
"given",
"model",
"and",
"input",
"X",
"often",
"this",
"is",
"done",
"via",
"expected",
"value",
"of",
"GAM",
"given",
"input",
"X"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2686-L2718 |
225,634 | dswah/pyGAM | pygam/pygam.py | PoissonGAM.gridsearch | def gridsearch(self, X, y, exposure=None, weights=None,
return_scores=False, keep_best=True, objective='auto',
**param_grids):
"""
performs a grid search over a space of parameters for a given objective
NOTE:
gridsearch method is lazy and will not remove useless combinations
from the search space, eg.
>>> n_splines=np.arange(5,10), fit_splines=[True, False]
will result in 10 loops, of which 5 are equivalent because
even though fit_splines==False
it is not recommended to search over a grid that alternates
between known scales and unknown scales, as the scores of the
candidate models will not be comparable.
Parameters
----------
X : array
input data of shape (n_samples, m_features)
y : array
label data of shape (n_samples,)
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
return_scores : boolean, default False
whether to return the hyperpamaters
and score for each element in the grid
keep_best : boolean
whether to keep the best GAM as self.
default: True
objective : string, default: 'auto'
metric to optimize. must be in ['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with unknown
scale and UBRE for models with known scale.
**kwargs : dict, default {'lam': np.logspace(-3, 3, 11)}
pairs of parameters and iterables of floats, or
parameters and iterables of iterables of floats.
if iterable of iterables of floats, the outer iterable must have
length m_features.
the method will make a grid of all the combinations of the parameters
and fit a GAM to each combination.
Returns
-------
if return_values == True:
model_scores : dict
Contains each fitted model as keys and corresponding
objective scores as values
else:
self, ie possibly the newly fitted model
"""
y, weights = self._exposure_to_weights(y, exposure, weights)
return super(PoissonGAM, self).gridsearch(X, y,
weights=weights,
return_scores=return_scores,
keep_best=keep_best,
objective=objective,
**param_grids) | python | def gridsearch(self, X, y, exposure=None, weights=None,
return_scores=False, keep_best=True, objective='auto',
**param_grids):
"""
performs a grid search over a space of parameters for a given objective
NOTE:
gridsearch method is lazy and will not remove useless combinations
from the search space, eg.
>>> n_splines=np.arange(5,10), fit_splines=[True, False]
will result in 10 loops, of which 5 are equivalent because
even though fit_splines==False
it is not recommended to search over a grid that alternates
between known scales and unknown scales, as the scores of the
candidate models will not be comparable.
Parameters
----------
X : array
input data of shape (n_samples, m_features)
y : array
label data of shape (n_samples,)
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
return_scores : boolean, default False
whether to return the hyperpamaters
and score for each element in the grid
keep_best : boolean
whether to keep the best GAM as self.
default: True
objective : string, default: 'auto'
metric to optimize. must be in ['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with unknown
scale and UBRE for models with known scale.
**kwargs : dict, default {'lam': np.logspace(-3, 3, 11)}
pairs of parameters and iterables of floats, or
parameters and iterables of iterables of floats.
if iterable of iterables of floats, the outer iterable must have
length m_features.
the method will make a grid of all the combinations of the parameters
and fit a GAM to each combination.
Returns
-------
if return_values == True:
model_scores : dict
Contains each fitted model as keys and corresponding
objective scores as values
else:
self, ie possibly the newly fitted model
"""
y, weights = self._exposure_to_weights(y, exposure, weights)
return super(PoissonGAM, self).gridsearch(X, y,
weights=weights,
return_scores=return_scores,
keep_best=keep_best,
objective=objective,
**param_grids) | [
"def",
"gridsearch",
"(",
"self",
",",
"X",
",",
"y",
",",
"exposure",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"return_scores",
"=",
"False",
",",
"keep_best",
"=",
"True",
",",
"objective",
"=",
"'auto'",
",",
"*",
"*",
"param_grids",
")",
":... | performs a grid search over a space of parameters for a given objective
NOTE:
gridsearch method is lazy and will not remove useless combinations
from the search space, eg.
>>> n_splines=np.arange(5,10), fit_splines=[True, False]
will result in 10 loops, of which 5 are equivalent because
even though fit_splines==False
it is not recommended to search over a grid that alternates
between known scales and unknown scales, as the scores of the
candidate models will not be comparable.
Parameters
----------
X : array
input data of shape (n_samples, m_features)
y : array
label data of shape (n_samples,)
exposure : array-like shape (n_samples,) or None, default: None
containing exposures
if None, defaults to array of ones
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
return_scores : boolean, default False
whether to return the hyperpamaters
and score for each element in the grid
keep_best : boolean
whether to keep the best GAM as self.
default: True
objective : string, default: 'auto'
metric to optimize. must be in ['AIC', 'AICc', 'GCV', 'UBRE', 'auto']
if 'auto', then grid search will optimize GCV for models with unknown
scale and UBRE for models with known scale.
**kwargs : dict, default {'lam': np.logspace(-3, 3, 11)}
pairs of parameters and iterables of floats, or
parameters and iterables of iterables of floats.
if iterable of iterables of floats, the outer iterable must have
length m_features.
the method will make a grid of all the combinations of the parameters
and fit a GAM to each combination.
Returns
-------
if return_values == True:
model_scores : dict
Contains each fitted model as keys and corresponding
objective scores as values
else:
self, ie possibly the newly fitted model | [
"performs",
"a",
"grid",
"search",
"over",
"a",
"space",
"of",
"parameters",
"for",
"a",
"given",
"objective"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L2720-L2794 |
225,635 | dswah/pyGAM | pygam/pygam.py | ExpectileGAM._get_quantile_ratio | def _get_quantile_ratio(self, X, y):
"""find the expirical quantile of the model
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
Returns
-------
ratio : float on [0, 1]
"""
y_pred = self.predict(X)
return (y_pred > y).mean() | python | def _get_quantile_ratio(self, X, y):
"""find the expirical quantile of the model
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
Returns
-------
ratio : float on [0, 1]
"""
y_pred = self.predict(X)
return (y_pred > y).mean() | [
"def",
"_get_quantile_ratio",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"y_pred",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"return",
"(",
"y_pred",
">",
"y",
")",
".",
"mean",
"(",
")"
] | find the expirical quantile of the model
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
Returns
-------
ratio : float on [0, 1] | [
"find",
"the",
"expirical",
"quantile",
"of",
"the",
"model"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L3150-L3168 |
225,636 | dswah/pyGAM | pygam/pygam.py | ExpectileGAM.fit_quantile | def fit_quantile(self, X, y, quantile, max_iter=20, tol=0.01, weights=None):
"""fit ExpectileGAM to a desired quantile via binary search
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
quantile : float on (0, 1)
desired quantile to fit.
max_iter : int, default: 20
maximum number of binary search iterations to perform
tol : float > 0, default: 0.01
maximum distance between desired quantile and fitted quantile
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
self : fitted GAM object
"""
def _within_tol(a, b, tol):
return np.abs(a - b) <= tol
# validate arguments
if quantile <= 0 or quantile >= 1:
raise ValueError('quantile must be on (0, 1), but found {}'.format(quantile))
if tol <= 0:
raise ValueError('tol must be float > 0 {}'.format(tol))
if max_iter <= 0:
raise ValueError('max_iter must be int > 0 {}'.format(max_iter))
# perform a first fit if necessary
if not self._is_fitted:
self.fit(X, y, weights=weights)
# do binary search
max_ = 1.0
min_ = 0.0
n_iter = 0
while n_iter < max_iter:
ratio = self._get_quantile_ratio(X, y)
if _within_tol(ratio, quantile, tol):
break
if ratio < quantile:
min_ = self.expectile
else:
max_ = self.expectile
expectile = (max_ + min_) / 2.
self.set_params(expectile=expectile)
self.fit(X, y, weights=weights)
n_iter += 1
# print diagnostics
if not _within_tol(ratio, quantile, tol) and self.verbose:
warnings.warn('maximum iterations reached')
return self | python | def fit_quantile(self, X, y, quantile, max_iter=20, tol=0.01, weights=None):
"""fit ExpectileGAM to a desired quantile via binary search
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
quantile : float on (0, 1)
desired quantile to fit.
max_iter : int, default: 20
maximum number of binary search iterations to perform
tol : float > 0, default: 0.01
maximum distance between desired quantile and fitted quantile
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
self : fitted GAM object
"""
def _within_tol(a, b, tol):
return np.abs(a - b) <= tol
# validate arguments
if quantile <= 0 or quantile >= 1:
raise ValueError('quantile must be on (0, 1), but found {}'.format(quantile))
if tol <= 0:
raise ValueError('tol must be float > 0 {}'.format(tol))
if max_iter <= 0:
raise ValueError('max_iter must be int > 0 {}'.format(max_iter))
# perform a first fit if necessary
if not self._is_fitted:
self.fit(X, y, weights=weights)
# do binary search
max_ = 1.0
min_ = 0.0
n_iter = 0
while n_iter < max_iter:
ratio = self._get_quantile_ratio(X, y)
if _within_tol(ratio, quantile, tol):
break
if ratio < quantile:
min_ = self.expectile
else:
max_ = self.expectile
expectile = (max_ + min_) / 2.
self.set_params(expectile=expectile)
self.fit(X, y, weights=weights)
n_iter += 1
# print diagnostics
if not _within_tol(ratio, quantile, tol) and self.verbose:
warnings.warn('maximum iterations reached')
return self | [
"def",
"fit_quantile",
"(",
"self",
",",
"X",
",",
"y",
",",
"quantile",
",",
"max_iter",
"=",
"20",
",",
"tol",
"=",
"0.01",
",",
"weights",
"=",
"None",
")",
":",
"def",
"_within_tol",
"(",
"a",
",",
"b",
",",
"tol",
")",
":",
"return",
"np",
... | fit ExpectileGAM to a desired quantile via binary search
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
quantile : float on (0, 1)
desired quantile to fit.
max_iter : int, default: 20
maximum number of binary search iterations to perform
tol : float > 0, default: 0.01
maximum distance between desired quantile and fitted quantile
weights : array-like shape (n_samples,) or None, default: None
containing sample weights
if None, defaults to array of ones
Returns
-------
self : fitted GAM object | [
"fit",
"ExpectileGAM",
"to",
"a",
"desired",
"quantile",
"via",
"binary",
"search"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/pygam.py#L3170-L3238 |
225,637 | dswah/pyGAM | pygam/core.py | nice_repr | def nice_repr(name, param_kvs, line_width=30, line_offset=5, decimals=3, args=None, flatten_attrs=True):
"""
tool to do a nice repr of a class.
Parameters
----------
name : str
class name
param_kvs : dict
dict containing class parameters names as keys,
and the corresponding values as values
line_width : int
desired maximum line width.
default: 30
line_offset : int
desired offset for new lines
default: 5
decimals : int
number of decimal places to keep for float values
default: 3
Returns
-------
out : str
nicely formatted repr of class instance
"""
if not param_kvs and not args :
# if the object has no params it's easy
return '{}()'.format(name)
# sort keys and values
ks = list(param_kvs.keys())
vs = list(param_kvs.values())
idxs = np.argsort(ks)
param_kvs = [(ks[i],vs[i]) for i in idxs]
if args is not None:
param_kvs = [(None, arg) for arg in args] + param_kvs
param_kvs = param_kvs[::-1]
out = ''
current_line = name + '('
while len(param_kvs) > 0:
# flatten sub-term properties, but not `terms`
k, v = param_kvs.pop()
if flatten_attrs and k is not 'terms':
v = flatten(v)
# round the floats first
if issubclass(v.__class__, (float, np.ndarray)):
v = round_to_n_decimal_places(v, n=decimals)
v = str(v)
else:
v = repr(v)
# handle args
if k is None:
param = '{},'.format(v)
else:
param = '{}={},'.format(k, v)
# print
if len(current_line + param) <= line_width:
current_line += param
else:
out += current_line + '\n'
current_line = ' '*line_offset + param
if len(current_line) < line_width and len(param_kvs) > 0:
current_line += ' '
out += current_line[:-1] # remove trailing comma
out += ')'
return out | python | def nice_repr(name, param_kvs, line_width=30, line_offset=5, decimals=3, args=None, flatten_attrs=True):
"""
tool to do a nice repr of a class.
Parameters
----------
name : str
class name
param_kvs : dict
dict containing class parameters names as keys,
and the corresponding values as values
line_width : int
desired maximum line width.
default: 30
line_offset : int
desired offset for new lines
default: 5
decimals : int
number of decimal places to keep for float values
default: 3
Returns
-------
out : str
nicely formatted repr of class instance
"""
if not param_kvs and not args :
# if the object has no params it's easy
return '{}()'.format(name)
# sort keys and values
ks = list(param_kvs.keys())
vs = list(param_kvs.values())
idxs = np.argsort(ks)
param_kvs = [(ks[i],vs[i]) for i in idxs]
if args is not None:
param_kvs = [(None, arg) for arg in args] + param_kvs
param_kvs = param_kvs[::-1]
out = ''
current_line = name + '('
while len(param_kvs) > 0:
# flatten sub-term properties, but not `terms`
k, v = param_kvs.pop()
if flatten_attrs and k is not 'terms':
v = flatten(v)
# round the floats first
if issubclass(v.__class__, (float, np.ndarray)):
v = round_to_n_decimal_places(v, n=decimals)
v = str(v)
else:
v = repr(v)
# handle args
if k is None:
param = '{},'.format(v)
else:
param = '{}={},'.format(k, v)
# print
if len(current_line + param) <= line_width:
current_line += param
else:
out += current_line + '\n'
current_line = ' '*line_offset + param
if len(current_line) < line_width and len(param_kvs) > 0:
current_line += ' '
out += current_line[:-1] # remove trailing comma
out += ')'
return out | [
"def",
"nice_repr",
"(",
"name",
",",
"param_kvs",
",",
"line_width",
"=",
"30",
",",
"line_offset",
"=",
"5",
",",
"decimals",
"=",
"3",
",",
"args",
"=",
"None",
",",
"flatten_attrs",
"=",
"True",
")",
":",
"if",
"not",
"param_kvs",
"and",
"not",
"... | tool to do a nice repr of a class.
Parameters
----------
name : str
class name
param_kvs : dict
dict containing class parameters names as keys,
and the corresponding values as values
line_width : int
desired maximum line width.
default: 30
line_offset : int
desired offset for new lines
default: 5
decimals : int
number of decimal places to keep for float values
default: 3
Returns
-------
out : str
nicely formatted repr of class instance | [
"tool",
"to",
"do",
"a",
"nice",
"repr",
"of",
"a",
"class",
"."
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/core.py#L11-L85 |
225,638 | dswah/pyGAM | pygam/core.py | Core.get_params | def get_params(self, deep=False):
"""
returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict
"""
attrs = self.__dict__
for attr in self._include:
attrs[attr] = getattr(self, attr)
if deep is True:
return attrs
return dict([(k,v) for k,v in list(attrs.items()) \
if (k[0] != '_') \
and (k[-1] != '_') \
and (k not in self._exclude)]) | python | def get_params(self, deep=False):
"""
returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict
"""
attrs = self.__dict__
for attr in self._include:
attrs[attr] = getattr(self, attr)
if deep is True:
return attrs
return dict([(k,v) for k,v in list(attrs.items()) \
if (k[0] != '_') \
and (k[-1] != '_') \
and (k not in self._exclude)]) | [
"def",
"get_params",
"(",
"self",
",",
"deep",
"=",
"False",
")",
":",
"attrs",
"=",
"self",
".",
"__dict__",
"for",
"attr",
"in",
"self",
".",
"_include",
":",
"attrs",
"[",
"attr",
"]",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"if",
"deep",... | returns a dict of all of the object's user-facing parameters
Parameters
----------
deep : boolean, default: False
when True, also gets non-user-facing paramters
Returns
-------
dict | [
"returns",
"a",
"dict",
"of",
"all",
"of",
"the",
"object",
"s",
"user",
"-",
"facing",
"parameters"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/core.py#L132-L154 |
225,639 | dswah/pyGAM | pygam/core.py | Core.set_params | def set_params(self, deep=False, force=False, **parameters):
"""
sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets parameters that the object does not already
have
**parameters : paramters to set
Returns
------
self
"""
param_names = self.get_params(deep=deep).keys()
for parameter, value in parameters.items():
if (parameter in param_names
or force
or (hasattr(self, parameter) and parameter == parameter.strip('_'))):
setattr(self, parameter, value)
return self | python | def set_params(self, deep=False, force=False, **parameters):
"""
sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets parameters that the object does not already
have
**parameters : paramters to set
Returns
------
self
"""
param_names = self.get_params(deep=deep).keys()
for parameter, value in parameters.items():
if (parameter in param_names
or force
or (hasattr(self, parameter) and parameter == parameter.strip('_'))):
setattr(self, parameter, value)
return self | [
"def",
"set_params",
"(",
"self",
",",
"deep",
"=",
"False",
",",
"force",
"=",
"False",
",",
"*",
"*",
"parameters",
")",
":",
"param_names",
"=",
"self",
".",
"get_params",
"(",
"deep",
"=",
"deep",
")",
".",
"keys",
"(",
")",
"for",
"parameter",
... | sets an object's paramters
Parameters
----------
deep : boolean, default: False
when True, also sets non-user-facing paramters
force : boolean, default: False
when True, also sets parameters that the object does not already
have
**parameters : paramters to set
Returns
------
self | [
"sets",
"an",
"object",
"s",
"paramters"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/core.py#L156-L179 |
225,640 | dswah/pyGAM | pygam/terms.py | Term.build_from_info | def build_from_info(cls, info):
"""build a Term instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
Term instance
"""
info = deepcopy(info)
if 'term_type' in info:
cls_ = TERMS[info.pop('term_type')]
if issubclass(cls_, MetaTermMixin):
return cls_.build_from_info(info)
else:
cls_ = cls
return cls_(**info) | python | def build_from_info(cls, info):
"""build a Term instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
Term instance
"""
info = deepcopy(info)
if 'term_type' in info:
cls_ = TERMS[info.pop('term_type')]
if issubclass(cls_, MetaTermMixin):
return cls_.build_from_info(info)
else:
cls_ = cls
return cls_(**info) | [
"def",
"build_from_info",
"(",
"cls",
",",
"info",
")",
":",
"info",
"=",
"deepcopy",
"(",
"info",
")",
"if",
"'term_type'",
"in",
"info",
":",
"cls_",
"=",
"TERMS",
"[",
"info",
".",
"pop",
"(",
"'term_type'",
")",
"]",
"if",
"issubclass",
"(",
"cls... | build a Term instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
Term instance | [
"build",
"a",
"Term",
"instance",
"from",
"a",
"dict"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L216-L238 |
225,641 | dswah/pyGAM | pygam/terms.py | MetaTermMixin._has_terms | def _has_terms(self):
"""bool, whether the instance has any sub-terms
"""
loc = self._super_get('_term_location')
return self._super_has(loc) \
and isiterable(self._super_get(loc)) \
and len(self._super_get(loc)) > 0 \
and all([isinstance(term, Term) for term in self._super_get(loc)]) | python | def _has_terms(self):
"""bool, whether the instance has any sub-terms
"""
loc = self._super_get('_term_location')
return self._super_has(loc) \
and isiterable(self._super_get(loc)) \
and len(self._super_get(loc)) > 0 \
and all([isinstance(term, Term) for term in self._super_get(loc)]) | [
"def",
"_has_terms",
"(",
"self",
")",
":",
"loc",
"=",
"self",
".",
"_super_get",
"(",
"'_term_location'",
")",
"return",
"self",
".",
"_super_has",
"(",
"loc",
")",
"and",
"isiterable",
"(",
"self",
".",
"_super_get",
"(",
"loc",
")",
")",
"and",
"le... | bool, whether the instance has any sub-terms | [
"bool",
"whether",
"the",
"instance",
"has",
"any",
"sub",
"-",
"terms"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L957-L964 |
225,642 | dswah/pyGAM | pygam/terms.py | TensorTerm.build_from_info | def build_from_info(cls, info):
"""build a TensorTerm instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TensorTerm instance
"""
terms = []
for term_info in info['terms']:
terms.append(SplineTerm.build_from_info(term_info))
return cls(*terms) | python | def build_from_info(cls, info):
"""build a TensorTerm instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TensorTerm instance
"""
terms = []
for term_info in info['terms']:
terms.append(SplineTerm.build_from_info(term_info))
return cls(*terms) | [
"def",
"build_from_info",
"(",
"cls",
",",
"info",
")",
":",
"terms",
"=",
"[",
"]",
"for",
"term_info",
"in",
"info",
"[",
"'terms'",
"]",
":",
"terms",
".",
"append",
"(",
"SplineTerm",
".",
"build_from_info",
"(",
"term_info",
")",
")",
"return",
"c... | build a TensorTerm instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TensorTerm instance | [
"build",
"a",
"TensorTerm",
"instance",
"from",
"a",
"dict"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1217-L1234 |
225,643 | dswah/pyGAM | pygam/terms.py | TensorTerm.hasconstraint | def hasconstraint(self):
"""bool, whether the term has any constraints
"""
constrained = False
for term in self._terms:
constrained = constrained or term.hasconstraint
return constrained | python | def hasconstraint(self):
"""bool, whether the term has any constraints
"""
constrained = False
for term in self._terms:
constrained = constrained or term.hasconstraint
return constrained | [
"def",
"hasconstraint",
"(",
"self",
")",
":",
"constrained",
"=",
"False",
"for",
"term",
"in",
"self",
".",
"_terms",
":",
"constrained",
"=",
"constrained",
"or",
"term",
".",
"hasconstraint",
"return",
"constrained"
] | bool, whether the term has any constraints | [
"bool",
"whether",
"the",
"term",
"has",
"any",
"constraints"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1237-L1243 |
225,644 | dswah/pyGAM | pygam/terms.py | TensorTerm._build_marginal_constraints | def _build_marginal_constraints(self, i, coef, constraint_lam, constraint_l2):
"""builds a constraint matrix for a marginal term in the tensor term
takes a tensor's coef vector, and slices it into pieces corresponding
to term i, then builds a constraint matrix for each piece of the coef vector,
and assembles them into a composite constraint matrix
Parameters
----------
i : int,
index of the marginal term for which to build a constraint matrix
coefs : array-like containing the coefficients of the tensor term
constraint_lam : float,
penalty to impose on the constraint.
typically this is a very large number.
constraint_l2 : float,
loading to improve the numerical conditioning of the constraint
matrix.
typically this is a very small number.
Returns
-------
C : sparse CSC matrix containing the model constraints in quadratic form
"""
composite_C = np.zeros((len(coef), len(coef)))
for slice_ in self._iterate_marginal_coef_slices(i):
# get the slice of coefficient vector
coef_slice = coef[slice_]
# build the constraint matrix for that slice
slice_C = self._terms[i].build_constraints(coef_slice, constraint_lam, constraint_l2)
# now enter it into the composite
composite_C[tuple(np.meshgrid(slice_, slice_))] = slice_C.A
return sp.sparse.csc_matrix(composite_C) | python | def _build_marginal_constraints(self, i, coef, constraint_lam, constraint_l2):
"""builds a constraint matrix for a marginal term in the tensor term
takes a tensor's coef vector, and slices it into pieces corresponding
to term i, then builds a constraint matrix for each piece of the coef vector,
and assembles them into a composite constraint matrix
Parameters
----------
i : int,
index of the marginal term for which to build a constraint matrix
coefs : array-like containing the coefficients of the tensor term
constraint_lam : float,
penalty to impose on the constraint.
typically this is a very large number.
constraint_l2 : float,
loading to improve the numerical conditioning of the constraint
matrix.
typically this is a very small number.
Returns
-------
C : sparse CSC matrix containing the model constraints in quadratic form
"""
composite_C = np.zeros((len(coef), len(coef)))
for slice_ in self._iterate_marginal_coef_slices(i):
# get the slice of coefficient vector
coef_slice = coef[slice_]
# build the constraint matrix for that slice
slice_C = self._terms[i].build_constraints(coef_slice, constraint_lam, constraint_l2)
# now enter it into the composite
composite_C[tuple(np.meshgrid(slice_, slice_))] = slice_C.A
return sp.sparse.csc_matrix(composite_C) | [
"def",
"_build_marginal_constraints",
"(",
"self",
",",
"i",
",",
"coef",
",",
"constraint_lam",
",",
"constraint_l2",
")",
":",
"composite_C",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"coef",
")",
",",
"len",
"(",
"coef",
")",
")",
")",
"for",
... | builds a constraint matrix for a marginal term in the tensor term
takes a tensor's coef vector, and slices it into pieces corresponding
to term i, then builds a constraint matrix for each piece of the coef vector,
and assembles them into a composite constraint matrix
Parameters
----------
i : int,
index of the marginal term for which to build a constraint matrix
coefs : array-like containing the coefficients of the tensor term
constraint_lam : float,
penalty to impose on the constraint.
typically this is a very large number.
constraint_l2 : float,
loading to improve the numerical conditioning of the constraint
matrix.
typically this is a very small number.
Returns
-------
C : sparse CSC matrix containing the model constraints in quadratic form | [
"builds",
"a",
"constraint",
"matrix",
"for",
"a",
"marginal",
"term",
"in",
"the",
"tensor",
"term"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1370-L1412 |
225,645 | dswah/pyGAM | pygam/terms.py | TensorTerm._iterate_marginal_coef_slices | def _iterate_marginal_coef_slices(self, i):
"""iterator of indices into tensor's coef vector for marginal term i's coefs
takes a tensor_term and returns an iterator of indices
that chop up the tensor's coef vector into slices belonging to term i
Parameters
----------
i : int,
index of marginal term
Yields
------
np.ndarray of ints
"""
dims = [term_.n_coefs for term_ in self]
# make all linear indices
idxs = np.arange(np.prod(dims))
# reshape indices to a Nd matrix
idxs = idxs.reshape(dims)
# reshape to a 2d matrix, where we can loop over rows
idxs = np.moveaxis(idxs, i, 0).reshape(idxs.shape[i], int(idxs.size/idxs.shape[i]))
# loop over rows
for slice_ in idxs.T:
yield slice_ | python | def _iterate_marginal_coef_slices(self, i):
"""iterator of indices into tensor's coef vector for marginal term i's coefs
takes a tensor_term and returns an iterator of indices
that chop up the tensor's coef vector into slices belonging to term i
Parameters
----------
i : int,
index of marginal term
Yields
------
np.ndarray of ints
"""
dims = [term_.n_coefs for term_ in self]
# make all linear indices
idxs = np.arange(np.prod(dims))
# reshape indices to a Nd matrix
idxs = idxs.reshape(dims)
# reshape to a 2d matrix, where we can loop over rows
idxs = np.moveaxis(idxs, i, 0).reshape(idxs.shape[i], int(idxs.size/idxs.shape[i]))
# loop over rows
for slice_ in idxs.T:
yield slice_ | [
"def",
"_iterate_marginal_coef_slices",
"(",
"self",
",",
"i",
")",
":",
"dims",
"=",
"[",
"term_",
".",
"n_coefs",
"for",
"term_",
"in",
"self",
"]",
"# make all linear indices",
"idxs",
"=",
"np",
".",
"arange",
"(",
"np",
".",
"prod",
"(",
"dims",
")"... | iterator of indices into tensor's coef vector for marginal term i's coefs
takes a tensor_term and returns an iterator of indices
that chop up the tensor's coef vector into slices belonging to term i
Parameters
----------
i : int,
index of marginal term
Yields
------
np.ndarray of ints | [
"iterator",
"of",
"indices",
"into",
"tensor",
"s",
"coef",
"vector",
"for",
"marginal",
"term",
"i",
"s",
"coefs"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1414-L1442 |
225,646 | dswah/pyGAM | pygam/terms.py | TermList.info | def info(self):
"""get information about the terms in the term list
Parameters
----------
Returns
-------
dict containing information to duplicate the term list
"""
info = {'term_type': 'term_list', 'verbose': self.verbose}
info.update({'terms':[term.info for term in self._terms]})
return info | python | def info(self):
"""get information about the terms in the term list
Parameters
----------
Returns
-------
dict containing information to duplicate the term list
"""
info = {'term_type': 'term_list', 'verbose': self.verbose}
info.update({'terms':[term.info for term in self._terms]})
return info | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"{",
"'term_type'",
":",
"'term_list'",
",",
"'verbose'",
":",
"self",
".",
"verbose",
"}",
"info",
".",
"update",
"(",
"{",
"'terms'",
":",
"[",
"term",
".",
"info",
"for",
"term",
"in",
"self",
"... | get information about the terms in the term list
Parameters
----------
Returns
-------
dict containing information to duplicate the term list | [
"get",
"information",
"about",
"the",
"terms",
"in",
"the",
"term",
"list"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1572-L1584 |
225,647 | dswah/pyGAM | pygam/terms.py | TermList.build_from_info | def build_from_info(cls, info):
"""build a TermList instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TermList instance
"""
info = deepcopy(info)
terms = []
for term_info in info['terms']:
terms.append(Term.build_from_info(term_info))
return cls(*terms) | python | def build_from_info(cls, info):
"""build a TermList instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TermList instance
"""
info = deepcopy(info)
terms = []
for term_info in info['terms']:
terms.append(Term.build_from_info(term_info))
return cls(*terms) | [
"def",
"build_from_info",
"(",
"cls",
",",
"info",
")",
":",
"info",
"=",
"deepcopy",
"(",
"info",
")",
"terms",
"=",
"[",
"]",
"for",
"term_info",
"in",
"info",
"[",
"'terms'",
"]",
":",
"terms",
".",
"append",
"(",
"Term",
".",
"build_from_info",
"... | build a TermList instance from a dict
Parameters
----------
cls : class
info : dict
contains all information needed to build the term
Return
------
TermList instance | [
"build",
"a",
"TermList",
"instance",
"from",
"a",
"dict"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1587-L1605 |
225,648 | dswah/pyGAM | pygam/terms.py | TermList.pop | def pop(self, i=None):
"""remove the ith term from the term list
Parameters
---------
i : int, optional
term to remove from term list
by default the last term is popped.
Returns
-------
term : Term
"""
if i == None:
i = len(self) - 1
if i >= len(self._terms) or i < 0:
raise ValueError('requested pop {}th term, but found only {} terms'\
.format(i, len(self._terms)))
term = self._terms[i]
self._terms = self._terms[:i] + self._terms[i+1:]
return term | python | def pop(self, i=None):
"""remove the ith term from the term list
Parameters
---------
i : int, optional
term to remove from term list
by default the last term is popped.
Returns
-------
term : Term
"""
if i == None:
i = len(self) - 1
if i >= len(self._terms) or i < 0:
raise ValueError('requested pop {}th term, but found only {} terms'\
.format(i, len(self._terms)))
term = self._terms[i]
self._terms = self._terms[:i] + self._terms[i+1:]
return term | [
"def",
"pop",
"(",
"self",
",",
"i",
"=",
"None",
")",
":",
"if",
"i",
"==",
"None",
":",
"i",
"=",
"len",
"(",
"self",
")",
"-",
"1",
"if",
"i",
">=",
"len",
"(",
"self",
".",
"_terms",
")",
"or",
"i",
"<",
"0",
":",
"raise",
"ValueError",... | remove the ith term from the term list
Parameters
---------
i : int, optional
term to remove from term list
by default the last term is popped.
Returns
-------
term : Term | [
"remove",
"the",
"ith",
"term",
"from",
"the",
"term",
"list"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1632-L1655 |
225,649 | dswah/pyGAM | pygam/terms.py | TermList.get_coef_indices | def get_coef_indices(self, i=-1):
"""get the indices for the coefficients of a term in the term list
Parameters
---------
i : int
by default `int=-1`, meaning that coefficient indices are returned
for all terms in the term list
Returns
-------
list of integers
"""
if i == -1:
return list(range(self.n_coefs))
if i >= len(self._terms):
raise ValueError('requested {}th term, but found only {} terms'\
.format(i, len(self._terms)))
start = 0
for term in self._terms[:i]:
start += term.n_coefs
stop = start + self._terms[i].n_coefs
return list(range(start, stop)) | python | def get_coef_indices(self, i=-1):
"""get the indices for the coefficients of a term in the term list
Parameters
---------
i : int
by default `int=-1`, meaning that coefficient indices are returned
for all terms in the term list
Returns
-------
list of integers
"""
if i == -1:
return list(range(self.n_coefs))
if i >= len(self._terms):
raise ValueError('requested {}th term, but found only {} terms'\
.format(i, len(self._terms)))
start = 0
for term in self._terms[:i]:
start += term.n_coefs
stop = start + self._terms[i].n_coefs
return list(range(start, stop)) | [
"def",
"get_coef_indices",
"(",
"self",
",",
"i",
"=",
"-",
"1",
")",
":",
"if",
"i",
"==",
"-",
"1",
":",
"return",
"list",
"(",
"range",
"(",
"self",
".",
"n_coefs",
")",
")",
"if",
"i",
">=",
"len",
"(",
"self",
".",
"_terms",
")",
":",
"r... | get the indices for the coefficients of a term in the term list
Parameters
---------
i : int
by default `int=-1`, meaning that coefficient indices are returned
for all terms in the term list
Returns
-------
list of integers | [
"get",
"the",
"indices",
"for",
"the",
"coefficients",
"of",
"a",
"term",
"in",
"the",
"term",
"list"
] | b3e5c3cd580f0a3ad69f9372861624f67760c325 | https://github.com/dswah/pyGAM/blob/b3e5c3cd580f0a3ad69f9372861624f67760c325/pygam/terms.py#L1672-L1696 |
225,650 | thoughtworksarts/EmoPy | EmoPy/src/csv_data_loader.py | CSVDataLoader.load_data | def load_data(self):
"""
Loads image and label data from specified csv file path.
:return: Dataset object containing image and label data.
"""
print('Extracting training data from csv...')
images = list()
labels = list()
emotion_index_map = dict()
with open(self.datapath) as csv_file:
reader = csv.reader(csv_file, delimiter=',', quotechar='"')
for row in reader:
label_class = row[self.csv_label_col]
if label_class not in self.target_emotion_map.keys():
continue
label_class = self.target_emotion_map[label_class]
if label_class not in emotion_index_map.keys():
emotion_index_map[label_class] = len(emotion_index_map.keys())
labels.append(label_class)
image = np.asarray([int(pixel) for pixel in row[self.csv_image_col].split(' ')], dtype=np.uint8).reshape(self.image_dimensions)
image = self._reshape(image)
images.append(image)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | python | def load_data(self):
"""
Loads image and label data from specified csv file path.
:return: Dataset object containing image and label data.
"""
print('Extracting training data from csv...')
images = list()
labels = list()
emotion_index_map = dict()
with open(self.datapath) as csv_file:
reader = csv.reader(csv_file, delimiter=',', quotechar='"')
for row in reader:
label_class = row[self.csv_label_col]
if label_class not in self.target_emotion_map.keys():
continue
label_class = self.target_emotion_map[label_class]
if label_class not in emotion_index_map.keys():
emotion_index_map[label_class] = len(emotion_index_map.keys())
labels.append(label_class)
image = np.asarray([int(pixel) for pixel in row[self.csv_image_col].split(' ')], dtype=np.uint8).reshape(self.image_dimensions)
image = self._reshape(image)
images.append(image)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | [
"def",
"load_data",
"(",
"self",
")",
":",
"print",
"(",
"'Extracting training data from csv...'",
")",
"images",
"=",
"list",
"(",
")",
"labels",
"=",
"list",
"(",
")",
"emotion_index_map",
"=",
"dict",
"(",
")",
"with",
"open",
"(",
"self",
".",
"datapat... | Loads image and label data from specified csv file path.
:return: Dataset object containing image and label data. | [
"Loads",
"image",
"and",
"label",
"data",
"from",
"specified",
"csv",
"file",
"path",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/csv_data_loader.py#L26-L54 |
225,651 | thoughtworksarts/EmoPy | EmoPy/src/data_loader.py | _DataLoader._load_dataset | def _load_dataset(self, images, labels, emotion_index_map):
"""
Loads Dataset object with images, labels, and other data.
:param images: numpy array of image data
:param labels: numpy array of one-hot vector labels
:param emotion_index_map: map linking string/integer emotion class to integer index used in labels vectors
:return: Dataset object containing image and label data.
"""
train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=self.validation_split, random_state=42, stratify=labels)
dataset = Dataset(train_images, test_images, train_labels, test_labels, emotion_index_map, self.time_delay)
return dataset | python | def _load_dataset(self, images, labels, emotion_index_map):
"""
Loads Dataset object with images, labels, and other data.
:param images: numpy array of image data
:param labels: numpy array of one-hot vector labels
:param emotion_index_map: map linking string/integer emotion class to integer index used in labels vectors
:return: Dataset object containing image and label data.
"""
train_images, test_images, train_labels, test_labels = train_test_split(images, labels, test_size=self.validation_split, random_state=42, stratify=labels)
dataset = Dataset(train_images, test_images, train_labels, test_labels, emotion_index_map, self.time_delay)
return dataset | [
"def",
"_load_dataset",
"(",
"self",
",",
"images",
",",
"labels",
",",
"emotion_index_map",
")",
":",
"train_images",
",",
"test_images",
",",
"train_labels",
",",
"test_labels",
"=",
"train_test_split",
"(",
"images",
",",
"labels",
",",
"test_size",
"=",
"s... | Loads Dataset object with images, labels, and other data.
:param images: numpy array of image data
:param labels: numpy array of one-hot vector labels
:param emotion_index_map: map linking string/integer emotion class to integer index used in labels vectors
:return: Dataset object containing image and label data. | [
"Loads",
"Dataset",
"object",
"with",
"images",
"labels",
"and",
"other",
"data",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/data_loader.py#L27-L39 |
225,652 | thoughtworksarts/EmoPy | EmoPy/src/directory_data_loader.py | DirectoryDataLoader.load_data | def load_data(self):
"""
Loads image and label data from specified directory path.
:return: Dataset object containing image and label data.
"""
images = list()
labels = list()
emotion_index_map = dict()
label_directories = [dir for dir in os.listdir(self.datapath) if not dir.startswith('.')]
for label_directory in label_directories:
if self.target_emotion_map:
if label_directory not in self.target_emotion_map.keys(): continue
self._add_new_label_to_map(label_directory, emotion_index_map)
label_directory_path = self.datapath + '/' + label_directory
if self.time_delay:
self._load_series_for_single_emotion_directory(images, label_directory, label_directory_path, labels)
else:
image_files = [image_file for image_file in os.listdir(label_directory_path) if not image_file.startswith('.')]
self._load_images_from_directory_to_array(image_files, images, label_directory, label_directory_path, labels)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | python | def load_data(self):
"""
Loads image and label data from specified directory path.
:return: Dataset object containing image and label data.
"""
images = list()
labels = list()
emotion_index_map = dict()
label_directories = [dir for dir in os.listdir(self.datapath) if not dir.startswith('.')]
for label_directory in label_directories:
if self.target_emotion_map:
if label_directory not in self.target_emotion_map.keys(): continue
self._add_new_label_to_map(label_directory, emotion_index_map)
label_directory_path = self.datapath + '/' + label_directory
if self.time_delay:
self._load_series_for_single_emotion_directory(images, label_directory, label_directory_path, labels)
else:
image_files = [image_file for image_file in os.listdir(label_directory_path) if not image_file.startswith('.')]
self._load_images_from_directory_to_array(image_files, images, label_directory, label_directory_path, labels)
vectorized_labels = self._vectorize_labels(emotion_index_map, labels)
self._check_data_not_empty(images)
return self._load_dataset(np.array(images), np.array(vectorized_labels), emotion_index_map) | [
"def",
"load_data",
"(",
"self",
")",
":",
"images",
"=",
"list",
"(",
")",
"labels",
"=",
"list",
"(",
")",
"emotion_index_map",
"=",
"dict",
"(",
")",
"label_directories",
"=",
"[",
"dir",
"for",
"dir",
"in",
"os",
".",
"listdir",
"(",
"self",
".",... | Loads image and label data from specified directory path.
:return: Dataset object containing image and label data. | [
"Loads",
"image",
"and",
"label",
"data",
"from",
"specified",
"directory",
"path",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/directory_data_loader.py#L23-L47 |
225,653 | thoughtworksarts/EmoPy | EmoPy/src/directory_data_loader.py | DirectoryDataLoader._check_directory_arguments | def _check_directory_arguments(self):
"""
Validates arguments for loading from directories, including static image and time series directories.
"""
if not os.path.isdir(self.datapath):
raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
if self.time_delay:
if self.time_delay < 1:
raise ValueError('Time step argument must be greater than 0, but gave: %i' % self.time_delay)
if not isinstance(self.time_delay, int):
raise ValueError('Time step argument must be an integer, but gave: %s' % str(self.time_delay)) | python | def _check_directory_arguments(self):
"""
Validates arguments for loading from directories, including static image and time series directories.
"""
if not os.path.isdir(self.datapath):
raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
if self.time_delay:
if self.time_delay < 1:
raise ValueError('Time step argument must be greater than 0, but gave: %i' % self.time_delay)
if not isinstance(self.time_delay, int):
raise ValueError('Time step argument must be an integer, but gave: %s' % str(self.time_delay)) | [
"def",
"_check_directory_arguments",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"datapath",
")",
":",
"raise",
"(",
"NotADirectoryError",
"(",
"'Directory does not exist: %s'",
"%",
"self",
".",
"datapath",
")",
")... | Validates arguments for loading from directories, including static image and time series directories. | [
"Validates",
"arguments",
"for",
"loading",
"from",
"directories",
"including",
"static",
"image",
"and",
"time",
"series",
"directories",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/directory_data_loader.py#L86-L96 |
225,654 | thoughtworksarts/EmoPy | EmoPy/src/fermodel.py | FERModel.predict | def predict(self, image_file):
"""
Predicts discrete emotion for given image.
:param images: image file (jpg or png format)
"""
image = misc.imread(image_file)
gray_image = image
if len(image.shape) > 2:
gray_image = cv2.cvtColor(image, code=cv2.COLOR_BGR2GRAY)
resized_image = cv2.resize(gray_image, self.target_dimensions, interpolation=cv2.INTER_LINEAR)
final_image = np.array([np.array([resized_image]).reshape(list(self.target_dimensions)+[self.channels])])
prediction = self.model.predict(final_image)
# Return the dominant expression
dominant_expression = self._print_prediction(prediction[0])
return dominant_expression | python | def predict(self, image_file):
"""
Predicts discrete emotion for given image.
:param images: image file (jpg or png format)
"""
image = misc.imread(image_file)
gray_image = image
if len(image.shape) > 2:
gray_image = cv2.cvtColor(image, code=cv2.COLOR_BGR2GRAY)
resized_image = cv2.resize(gray_image, self.target_dimensions, interpolation=cv2.INTER_LINEAR)
final_image = np.array([np.array([resized_image]).reshape(list(self.target_dimensions)+[self.channels])])
prediction = self.model.predict(final_image)
# Return the dominant expression
dominant_expression = self._print_prediction(prediction[0])
return dominant_expression | [
"def",
"predict",
"(",
"self",
",",
"image_file",
")",
":",
"image",
"=",
"misc",
".",
"imread",
"(",
"image_file",
")",
"gray_image",
"=",
"image",
"if",
"len",
"(",
"image",
".",
"shape",
")",
">",
"2",
":",
"gray_image",
"=",
"cv2",
".",
"cvtColor... | Predicts discrete emotion for given image.
:param images: image file (jpg or png format) | [
"Predicts",
"discrete",
"emotion",
"for",
"given",
"image",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/fermodel.py#L47-L62 |
225,655 | thoughtworksarts/EmoPy | EmoPy/src/fermodel.py | FERModel._check_emotion_set_is_supported | def _check_emotion_set_is_supported(self):
"""
Validates set of user-supplied target emotions.
"""
supported_emotion_subsets = [
set(['anger', 'fear', 'surprise', 'calm']),
set(['happiness', 'disgust', 'surprise']),
set(['anger', 'fear', 'surprise']),
set(['anger', 'fear', 'calm']),
set(['anger', 'happiness', 'calm']),
set(['anger', 'fear', 'disgust']),
set(['calm', 'disgust', 'surprise']),
set(['sadness', 'disgust', 'surprise']),
set(['anger', 'happiness'])
]
if not set(self.target_emotions) in supported_emotion_subsets:
error_string = 'Target emotions must be a supported subset. '
error_string += 'Choose from one of the following emotion subset: \n'
possible_subset_string = ''
for emotion_set in supported_emotion_subsets:
possible_subset_string += ', '.join(emotion_set)
possible_subset_string += '\n'
error_string += possible_subset_string
raise ValueError(error_string) | python | def _check_emotion_set_is_supported(self):
"""
Validates set of user-supplied target emotions.
"""
supported_emotion_subsets = [
set(['anger', 'fear', 'surprise', 'calm']),
set(['happiness', 'disgust', 'surprise']),
set(['anger', 'fear', 'surprise']),
set(['anger', 'fear', 'calm']),
set(['anger', 'happiness', 'calm']),
set(['anger', 'fear', 'disgust']),
set(['calm', 'disgust', 'surprise']),
set(['sadness', 'disgust', 'surprise']),
set(['anger', 'happiness'])
]
if not set(self.target_emotions) in supported_emotion_subsets:
error_string = 'Target emotions must be a supported subset. '
error_string += 'Choose from one of the following emotion subset: \n'
possible_subset_string = ''
for emotion_set in supported_emotion_subsets:
possible_subset_string += ', '.join(emotion_set)
possible_subset_string += '\n'
error_string += possible_subset_string
raise ValueError(error_string) | [
"def",
"_check_emotion_set_is_supported",
"(",
"self",
")",
":",
"supported_emotion_subsets",
"=",
"[",
"set",
"(",
"[",
"'anger'",
",",
"'fear'",
",",
"'surprise'",
",",
"'calm'",
"]",
")",
",",
"set",
"(",
"[",
"'happiness'",
",",
"'disgust'",
",",
"'surpr... | Validates set of user-supplied target emotions. | [
"Validates",
"set",
"of",
"user",
"-",
"supplied",
"target",
"emotions",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/fermodel.py#L64-L87 |
225,656 | thoughtworksarts/EmoPy | EmoPy/src/fermodel.py | FERModel._choose_model_from_target_emotions | def _choose_model_from_target_emotions(self):
"""
Initializes pre-trained deep learning model for the set of target emotions supplied by user.
"""
model_indices = [self.emotion_index_map[emotion] for emotion in self.target_emotions]
sorted_indices = [str(idx) for idx in sorted(model_indices)]
model_suffix = ''.join(sorted_indices)
#Modify the path to choose the model file and the emotion map that you want to use
model_file = 'models/conv_model_%s.hdf5' % model_suffix
emotion_map_file = 'models/conv_emotion_map_%s.json' % model_suffix
emotion_map = json.loads(open(resource_filename('EmoPy', emotion_map_file)).read())
return load_model(resource_filename('EmoPy', model_file)), emotion_map | python | def _choose_model_from_target_emotions(self):
"""
Initializes pre-trained deep learning model for the set of target emotions supplied by user.
"""
model_indices = [self.emotion_index_map[emotion] for emotion in self.target_emotions]
sorted_indices = [str(idx) for idx in sorted(model_indices)]
model_suffix = ''.join(sorted_indices)
#Modify the path to choose the model file and the emotion map that you want to use
model_file = 'models/conv_model_%s.hdf5' % model_suffix
emotion_map_file = 'models/conv_emotion_map_%s.json' % model_suffix
emotion_map = json.loads(open(resource_filename('EmoPy', emotion_map_file)).read())
return load_model(resource_filename('EmoPy', model_file)), emotion_map | [
"def",
"_choose_model_from_target_emotions",
"(",
"self",
")",
":",
"model_indices",
"=",
"[",
"self",
".",
"emotion_index_map",
"[",
"emotion",
"]",
"for",
"emotion",
"in",
"self",
".",
"target_emotions",
"]",
"sorted_indices",
"=",
"[",
"str",
"(",
"idx",
")... | Initializes pre-trained deep learning model for the set of target emotions supplied by user. | [
"Initializes",
"pre",
"-",
"trained",
"deep",
"learning",
"model",
"for",
"the",
"set",
"of",
"target",
"emotions",
"supplied",
"by",
"user",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/fermodel.py#L89-L100 |
225,657 | thoughtworksarts/EmoPy | EmoPy/library/image.py | apply_transform | def apply_transform(sample,
transform_matrix,
channel_axis=0,
fill_mode='nearest',
cval=0.):
"""Apply the image transformation specified by a matrix.
# Arguments
sample: 2D numpy array, single sample.
transform_matrix: Numpy array specifying the geometric transformation.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
# Returns
The transformed version of the input.
"""
if sample.ndim == 4:
channel_axis = channel_axis - 1
transformed_frames = [transform(frame, transform_matrix, channel_axis, fill_mode, cval) for frame in sample]
return np.stack(transformed_frames, axis=0)
if sample.ndim == 3:
return transform(sample, transform_matrix, channel_axis, fill_mode, cval) | python | def apply_transform(sample,
transform_matrix,
channel_axis=0,
fill_mode='nearest',
cval=0.):
"""Apply the image transformation specified by a matrix.
# Arguments
sample: 2D numpy array, single sample.
transform_matrix: Numpy array specifying the geometric transformation.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
# Returns
The transformed version of the input.
"""
if sample.ndim == 4:
channel_axis = channel_axis - 1
transformed_frames = [transform(frame, transform_matrix, channel_axis, fill_mode, cval) for frame in sample]
return np.stack(transformed_frames, axis=0)
if sample.ndim == 3:
return transform(sample, transform_matrix, channel_axis, fill_mode, cval) | [
"def",
"apply_transform",
"(",
"sample",
",",
"transform_matrix",
",",
"channel_axis",
"=",
"0",
",",
"fill_mode",
"=",
"'nearest'",
",",
"cval",
"=",
"0.",
")",
":",
"if",
"sample",
".",
"ndim",
"==",
"4",
":",
"channel_axis",
"=",
"channel_axis",
"-",
... | Apply the image transformation specified by a matrix.
# Arguments
sample: 2D numpy array, single sample.
transform_matrix: Numpy array specifying the geometric transformation.
channel_axis: Index of axis for channels in the input tensor.
fill_mode: Points outside the boundaries of the input
are filled according to the given mode
(one of `{'constant', 'nearest', 'reflect', 'wrap'}`).
cval: Value used for points outside the boundaries
of the input if `mode='constant'`.
# Returns
The transformed version of the input. | [
"Apply",
"the",
"image",
"transformation",
"specified",
"by",
"a",
"matrix",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L75-L101 |
225,658 | thoughtworksarts/EmoPy | EmoPy/library/image.py | ImageDataGenerator.standardize | def standardize(self, x):
"""Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized.
"""
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center:
x -= np.mean(x, keepdims=True)
if self.samplewise_std_normalization:
x /= np.std(x, keepdims=True) + 1e-7
if self.featurewise_center:
if self.mean is not None:
x -= self.mean
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_center`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.featurewise_std_normalization:
if self.std is not None:
x /= (self.std + 1e-7)
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_std_normalization`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.zca_whitening:
if self.principal_components is not None:
flatx = np.reshape(x, (-1, np.prod(x.shape[-3:])))
whitex = np.dot(flatx, self.principal_components)
x = np.reshape(whitex, x.shape)
else:
warnings.warn('This ImageDataGenerator specifies '
'`zca_whitening`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
return x | python | def standardize(self, x):
"""Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized.
"""
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center:
x -= np.mean(x, keepdims=True)
if self.samplewise_std_normalization:
x /= np.std(x, keepdims=True) + 1e-7
if self.featurewise_center:
if self.mean is not None:
x -= self.mean
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_center`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.featurewise_std_normalization:
if self.std is not None:
x /= (self.std + 1e-7)
else:
warnings.warn('This ImageDataGenerator specifies '
'`featurewise_std_normalization`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
if self.zca_whitening:
if self.principal_components is not None:
flatx = np.reshape(x, (-1, np.prod(x.shape[-3:])))
whitex = np.dot(flatx, self.principal_components)
x = np.reshape(whitex, x.shape)
else:
warnings.warn('This ImageDataGenerator specifies '
'`zca_whitening`, but it hasn\'t '
'been fit on any training data. Fit it '
'first by calling `.fit(numpy_data)`.')
return x | [
"def",
"standardize",
"(",
"self",
",",
"x",
")",
":",
"if",
"self",
".",
"preprocessing_function",
":",
"x",
"=",
"self",
".",
"preprocessing_function",
"(",
"x",
")",
"if",
"self",
".",
"rescale",
":",
"x",
"*=",
"self",
".",
"rescale",
"if",
"self",... | Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized. | [
"Apply",
"the",
"normalization",
"configuration",
"to",
"a",
"batch",
"of",
"inputs",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L247-L291 |
225,659 | thoughtworksarts/EmoPy | EmoPy/library/image.py | ImageDataGenerator.fit | def fit(self, x,
augment=False,
rounds=1,
seed=None):
"""Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 5 or 4 when time_delay is None.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`.
"""
x = np.asarray(x, dtype=K.floatx())
if x.shape[self.channel_axis] not in {1, 3, 4}:
warnings.warn(
'Expected input to be images (as Numpy array) '
'following the data format convention "' + self.data_format + '" '
'(channels on axis ' + str(
self.channel_axis) + '), i.e. expected '
'either 1, 3 or 4 channels on axis ' + str(self.channel_axis) + '. '
'However, it was passed an array with shape ' + str(
x.shape) +
' (' + str(x.shape[self.channel_axis]) + ' channels).')
if seed is not None:
np.random.seed(seed)
x = np.copy(x)
if augment:
ax = np.zeros(tuple([rounds * x.shape[0]] + list(x.shape)[1:]), dtype=K.floatx())
for r in range(rounds):
for i in range(x.shape[0]):
ax[i + r * x.shape[0]] = self.random_transform(x[i])
x = ax
if self.featurewise_center:
self.mean = np.mean(x, axis=0)
x -= self.mean
if self.featurewise_std_normalization:
self.std = np.std(x, axis=0)
x /= (self.std + K.epsilon())
if self.zca_whitening:
flat_x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2] * x.shape[3]))
sigma = np.dot(flat_x.T, flat_x) / flat_x.shape[0]
u, s, _ = linalg.svd(sigma)
self.principal_components = np.dot(np.dot(u, np.diag(1. / np.sqrt(s + self.zca_epsilon))), u.T) | python | def fit(self, x,
augment=False,
rounds=1,
seed=None):
"""Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 5 or 4 when time_delay is None.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`.
"""
x = np.asarray(x, dtype=K.floatx())
if x.shape[self.channel_axis] not in {1, 3, 4}:
warnings.warn(
'Expected input to be images (as Numpy array) '
'following the data format convention "' + self.data_format + '" '
'(channels on axis ' + str(
self.channel_axis) + '), i.e. expected '
'either 1, 3 or 4 channels on axis ' + str(self.channel_axis) + '. '
'However, it was passed an array with shape ' + str(
x.shape) +
' (' + str(x.shape[self.channel_axis]) + ' channels).')
if seed is not None:
np.random.seed(seed)
x = np.copy(x)
if augment:
ax = np.zeros(tuple([rounds * x.shape[0]] + list(x.shape)[1:]), dtype=K.floatx())
for r in range(rounds):
for i in range(x.shape[0]):
ax[i + r * x.shape[0]] = self.random_transform(x[i])
x = ax
if self.featurewise_center:
self.mean = np.mean(x, axis=0)
x -= self.mean
if self.featurewise_std_normalization:
self.std = np.std(x, axis=0)
x /= (self.std + K.epsilon())
if self.zca_whitening:
flat_x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2] * x.shape[3]))
sigma = np.dot(flat_x.T, flat_x) / flat_x.shape[0]
u, s, _ = linalg.svd(sigma)
self.principal_components = np.dot(np.dot(u, np.diag(1. / np.sqrt(s + self.zca_epsilon))), u.T) | [
"def",
"fit",
"(",
"self",
",",
"x",
",",
"augment",
"=",
"False",
",",
"rounds",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"K",
".",
"floatx",
"(",
")",
")",
"if",
"x",
".",
... | Fits internal statistics to some sample data.
Required for featurewise_center, featurewise_std_normalization
and zca_whitening.
# Arguments
x: Numpy array, the data to fit on. Should have rank 5 or 4 when time_delay is None.
In case of grayscale data,
the channels axis should have value 1, and in case
of RGB data, it should have value 3.
augment: Whether to fit on randomly augmented samples
rounds: If `augment`,
how many augmentation passes to do over the data
seed: random seed.
# Raises
ValueError: in case of invalid input `x`. | [
"Fits",
"internal",
"statistics",
"to",
"some",
"sample",
"data",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L404-L461 |
225,660 | thoughtworksarts/EmoPy | EmoPy/library/image.py | NumpyArrayIterator.next | def next(self):
"""For python 2.x.
# Returns
The next batch.
"""
# Keeps under lock only the mechanism which advances
# the indexing of each batch.
with self.lock:
index_array = next(self.index_generator)
# The transformation of images is not under thread lock
# so it can be done in parallel
return self._get_batches_of_transformed_samples(index_array) | python | def next(self):
"""For python 2.x.
# Returns
The next batch.
"""
# Keeps under lock only the mechanism which advances
# the indexing of each batch.
with self.lock:
index_array = next(self.index_generator)
# The transformation of images is not under thread lock
# so it can be done in parallel
return self._get_batches_of_transformed_samples(index_array) | [
"def",
"next",
"(",
"self",
")",
":",
"# Keeps under lock only the mechanism which advances",
"# the indexing of each batch.",
"with",
"self",
".",
"lock",
":",
"index_array",
"=",
"next",
"(",
"self",
".",
"index_generator",
")",
"# The transformation of images is not unde... | For python 2.x.
# Returns
The next batch. | [
"For",
"python",
"2",
".",
"x",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/library/image.py#L625-L637 |
225,661 | thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | ConvolutionalLstmNN._init_model | def _init_model(self):
"""
Composes all layers of CNN.
"""
model = Sequential()
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=[self.time_delay] + list(self.image_size) + [self.channels],
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=(self.time_delay, self.channels) + self.image_size,
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation))
model.add(BatchNormalization())
model.add(Conv2D(filters=1, kernel_size=self.kernel_size, activation="sigmoid", data_format="channels_last"))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="sigmoid"))
if self.verbose:
model.summary()
self.model = model | python | def _init_model(self):
"""
Composes all layers of CNN.
"""
model = Sequential()
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=[self.time_delay] + list(self.image_size) + [self.channels],
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation,
input_shape=(self.time_delay, self.channels) + self.image_size,
data_format='channels_last', return_sequences=True))
model.add(BatchNormalization())
model.add(ConvLSTM2D(filters=self.filters, kernel_size=self.kernel_size, activation=self.activation))
model.add(BatchNormalization())
model.add(Conv2D(filters=1, kernel_size=self.kernel_size, activation="sigmoid", data_format="channels_last"))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="sigmoid"))
if self.verbose:
model.summary()
self.model = model | [
"def",
"_init_model",
"(",
"self",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"ConvLSTM2D",
"(",
"filters",
"=",
"self",
".",
"filters",
",",
"kernel_size",
"=",
"self",
".",
"kernel_size",
",",
"activation",
"=",
"self",
... | Composes all layers of CNN. | [
"Composes",
"all",
"layers",
"of",
"CNN",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L166-L186 |
225,662 | thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | ConvolutionalNN._init_model | def _init_model(self):
"""
Composes all layers of 2D CNN.
"""
model = Sequential()
model.add(Conv2D(input_shape=list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | python | def _init_model(self):
"""
Composes all layers of 2D CNN.
"""
model = Sequential()
model.add(Conv2D(input_shape=list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv2D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling2D())
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | [
"def",
"_init_model",
"(",
"self",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Conv2D",
"(",
"input_shape",
"=",
"list",
"(",
"self",
".",
"image_size",
")",
"+",
"[",
"self",
".",
"channels",
"]",
",",
"filters",
"=",
... | Composes all layers of 2D CNN. | [
"Composes",
"all",
"layers",
"of",
"2D",
"CNN",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L232-L252 |
225,663 | thoughtworksarts/EmoPy | EmoPy/src/neuralnets.py | TimeDelayConvNN._init_model | def _init_model(self):
"""
Composes all layers of 3D CNN.
"""
model = Sequential()
model.add(Conv3D(input_shape=[self.time_delay] + list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | python | def _init_model(self):
"""
Composes all layers of 3D CNN.
"""
model = Sequential()
model.add(Conv3D(input_shape=[self.time_delay] + list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(
Conv3D(filters=self.filters, kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
model.add(MaxPooling3D(pool_size=(1, 2, 2), data_format='channels_last'))
model.add(Flatten())
model.add(Dense(units=len(self.emotion_map.keys()), activation="relu"))
if self.verbose:
model.summary()
self.model = model | [
"def",
"_init_model",
"(",
"self",
")",
":",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"Conv3D",
"(",
"input_shape",
"=",
"[",
"self",
".",
"time_delay",
"]",
"+",
"list",
"(",
"self",
".",
"image_size",
")",
"+",
"[",
"self",
... | Composes all layers of 3D CNN. | [
"Composes",
"all",
"layers",
"of",
"3D",
"CNN",
"."
] | a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7 | https://github.com/thoughtworksarts/EmoPy/blob/a0ab97b3719ebe0a9de9bfc5adae5e46c9b77fd7/EmoPy/src/neuralnets.py#L300-L320 |
225,664 | sosreport/sos | sos/plugins/foreman.py | Foreman.build_query_cmd | def build_query_cmd(self, query, csv=False):
"""
Builds the command needed to invoke the pgsql query as the postgres
user.
The query requires significant quoting work to satisfy both the
shell and postgres parsing requirements. Note that this will generate
a large amount of quoting in sos logs referencing the command being run
"""
_cmd = "su postgres -c %s"
if not csv:
_dbcmd = "psql foreman -c %s"
else:
_dbcmd = "psql foreman -A -F , -X -c %s"
dbq = _dbcmd % quote(query)
return _cmd % quote(dbq) | python | def build_query_cmd(self, query, csv=False):
"""
Builds the command needed to invoke the pgsql query as the postgres
user.
The query requires significant quoting work to satisfy both the
shell and postgres parsing requirements. Note that this will generate
a large amount of quoting in sos logs referencing the command being run
"""
_cmd = "su postgres -c %s"
if not csv:
_dbcmd = "psql foreman -c %s"
else:
_dbcmd = "psql foreman -A -F , -X -c %s"
dbq = _dbcmd % quote(query)
return _cmd % quote(dbq) | [
"def",
"build_query_cmd",
"(",
"self",
",",
"query",
",",
"csv",
"=",
"False",
")",
":",
"_cmd",
"=",
"\"su postgres -c %s\"",
"if",
"not",
"csv",
":",
"_dbcmd",
"=",
"\"psql foreman -c %s\"",
"else",
":",
"_dbcmd",
"=",
"\"psql foreman -A -F , -X -c %s\"",
"dbq... | Builds the command needed to invoke the pgsql query as the postgres
user.
The query requires significant quoting work to satisfy both the
shell and postgres parsing requirements. Note that this will generate
a large amount of quoting in sos logs referencing the command being run | [
"Builds",
"the",
"command",
"needed",
"to",
"invoke",
"the",
"pgsql",
"query",
"as",
"the",
"postgres",
"user",
".",
"The",
"query",
"requires",
"significant",
"quoting",
"work",
"to",
"satisfy",
"both",
"the",
"shell",
"and",
"postgres",
"parsing",
"requireme... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/foreman.py#L163-L177 |
225,665 | sosreport/sos | sos/policies/__init__.py | InitSystem.is_enabled | def is_enabled(self, name):
"""Check if given service name is enabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'enabled'
return False | python | def is_enabled(self, name):
"""Check if given service name is enabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'enabled'
return False | [
"def",
"is_enabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'enabled'",
"return",
"False"
] | Check if given service name is enabled | [
"Check",
"if",
"given",
"service",
"name",
"is",
"enabled"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L70-L74 |
225,666 | sosreport/sos | sos/policies/__init__.py | InitSystem.is_disabled | def is_disabled(self, name):
"""Check if a given service name is disabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'disabled'
return False | python | def is_disabled(self, name):
"""Check if a given service name is disabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'disabled'
return False | [
"def",
"is_disabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'disabled'",
"return",
"False"... | Check if a given service name is disabled | [
"Check",
"if",
"a",
"given",
"service",
"name",
"is",
"disabled"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L76-L80 |
225,667 | sosreport/sos | sos/policies/__init__.py | InitSystem._query_service | def _query_service(self, name):
"""Query an individual service"""
if self.query_cmd:
try:
return sos_get_command_output("%s %s" % (self.query_cmd, name))
except Exception:
return None
return None | python | def _query_service(self, name):
"""Query an individual service"""
if self.query_cmd:
try:
return sos_get_command_output("%s %s" % (self.query_cmd, name))
except Exception:
return None
return None | [
"def",
"_query_service",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"query_cmd",
":",
"try",
":",
"return",
"sos_get_command_output",
"(",
"\"%s %s\"",
"%",
"(",
"self",
".",
"query_cmd",
",",
"name",
")",
")",
"except",
"Exception",
":",
"re... | Query an individual service | [
"Query",
"an",
"individual",
"service"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L106-L113 |
225,668 | sosreport/sos | sos/policies/__init__.py | InitSystem.get_service_status | def get_service_status(self, name):
"""Returns the status for the given service name along with the output
of the query command
"""
svc = self._query_service(name)
if svc is not None:
return {'name': name,
'status': self.parse_query(svc['output']),
'output': svc['output']
}
else:
return {'name': name,
'status': 'missing',
'output': ''
} | python | def get_service_status(self, name):
"""Returns the status for the given service name along with the output
of the query command
"""
svc = self._query_service(name)
if svc is not None:
return {'name': name,
'status': self.parse_query(svc['output']),
'output': svc['output']
}
else:
return {'name': name,
'status': 'missing',
'output': ''
} | [
"def",
"get_service_status",
"(",
"self",
",",
"name",
")",
":",
"svc",
"=",
"self",
".",
"_query_service",
"(",
"name",
")",
"if",
"svc",
"is",
"not",
"None",
":",
"return",
"{",
"'name'",
":",
"name",
",",
"'status'",
":",
"self",
".",
"parse_query",... | Returns the status for the given service name along with the output
of the query command | [
"Returns",
"the",
"status",
"for",
"the",
"given",
"service",
"name",
"along",
"with",
"the",
"output",
"of",
"the",
"query",
"command"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L123-L137 |
225,669 | sosreport/sos | sos/policies/__init__.py | PackageManager.all_pkgs_by_name_regex | def all_pkgs_by_name_regex(self, regex_name, flags=0):
"""
Return a list of packages that match regex_name.
"""
reg = re.compile(regex_name, flags)
return [pkg for pkg in self.all_pkgs().keys() if reg.match(pkg)] | python | def all_pkgs_by_name_regex(self, regex_name, flags=0):
"""
Return a list of packages that match regex_name.
"""
reg = re.compile(regex_name, flags)
return [pkg for pkg in self.all_pkgs().keys() if reg.match(pkg)] | [
"def",
"all_pkgs_by_name_regex",
"(",
"self",
",",
"regex_name",
",",
"flags",
"=",
"0",
")",
":",
"reg",
"=",
"re",
".",
"compile",
"(",
"regex_name",
",",
"flags",
")",
"return",
"[",
"pkg",
"for",
"pkg",
"in",
"self",
".",
"all_pkgs",
"(",
")",
".... | Return a list of packages that match regex_name. | [
"Return",
"a",
"list",
"of",
"packages",
"that",
"match",
"regex_name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L210-L215 |
225,670 | sosreport/sos | sos/policies/__init__.py | PackageManager.pkg_by_name | def pkg_by_name(self, name):
"""
Return a single package that matches name.
"""
pkgmatches = self.all_pkgs_by_name(name)
if (len(pkgmatches) != 0):
return self.all_pkgs_by_name(name)[-1]
else:
return None | python | def pkg_by_name(self, name):
"""
Return a single package that matches name.
"""
pkgmatches = self.all_pkgs_by_name(name)
if (len(pkgmatches) != 0):
return self.all_pkgs_by_name(name)[-1]
else:
return None | [
"def",
"pkg_by_name",
"(",
"self",
",",
"name",
")",
":",
"pkgmatches",
"=",
"self",
".",
"all_pkgs_by_name",
"(",
"name",
")",
"if",
"(",
"len",
"(",
"pkgmatches",
")",
"!=",
"0",
")",
":",
"return",
"self",
".",
"all_pkgs_by_name",
"(",
"name",
")",
... | Return a single package that matches name. | [
"Return",
"a",
"single",
"package",
"that",
"matches",
"name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L217-L225 |
225,671 | sosreport/sos | sos/policies/__init__.py | PackageManager.all_pkgs | def all_pkgs(self):
"""
Return a list of all packages.
"""
if not self.packages:
self.packages = self.get_pkg_list()
return self.packages | python | def all_pkgs(self):
"""
Return a list of all packages.
"""
if not self.packages:
self.packages = self.get_pkg_list()
return self.packages | [
"def",
"all_pkgs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"packages",
":",
"self",
".",
"packages",
"=",
"self",
".",
"get_pkg_list",
"(",
")",
"return",
"self",
".",
"packages"
] | Return a list of all packages. | [
"Return",
"a",
"list",
"of",
"all",
"packages",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L258-L264 |
225,672 | sosreport/sos | sos/policies/__init__.py | PackageManager.all_files | def all_files(self):
"""
Returns a list of files known by the package manager
"""
if self.files_command and not self.files:
cmd = self.files_command
files = shell_out(cmd, timeout=0, chroot=self.chroot)
self.files = files.splitlines()
return self.files | python | def all_files(self):
"""
Returns a list of files known by the package manager
"""
if self.files_command and not self.files:
cmd = self.files_command
files = shell_out(cmd, timeout=0, chroot=self.chroot)
self.files = files.splitlines()
return self.files | [
"def",
"all_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"files_command",
"and",
"not",
"self",
".",
"files",
":",
"cmd",
"=",
"self",
".",
"files_command",
"files",
"=",
"shell_out",
"(",
"cmd",
",",
"timeout",
"=",
"0",
",",
"chroot",
"=",
"se... | Returns a list of files known by the package manager | [
"Returns",
"a",
"list",
"of",
"files",
"known",
"by",
"the",
"package",
"manager"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L272-L280 |
225,673 | sosreport/sos | sos/policies/__init__.py | PresetDefaults.write | def write(self, presets_path):
"""Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written.
"""
if self.builtin:
raise TypeError("Cannot write built-in preset")
# Make dictionaries of PresetDefaults values
odict = self.opts.dict()
pdict = {self.name: {DESC: self.desc, NOTE: self.note, OPTS: odict}}
if not os.path.exists(presets_path):
os.makedirs(presets_path, mode=0o755)
with open(os.path.join(presets_path, self.name), "w") as pfile:
json.dump(pdict, pfile) | python | def write(self, presets_path):
"""Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written.
"""
if self.builtin:
raise TypeError("Cannot write built-in preset")
# Make dictionaries of PresetDefaults values
odict = self.opts.dict()
pdict = {self.name: {DESC: self.desc, NOTE: self.note, OPTS: odict}}
if not os.path.exists(presets_path):
os.makedirs(presets_path, mode=0o755)
with open(os.path.join(presets_path, self.name), "w") as pfile:
json.dump(pdict, pfile) | [
"def",
"write",
"(",
"self",
",",
"presets_path",
")",
":",
"if",
"self",
".",
"builtin",
":",
"raise",
"TypeError",
"(",
"\"Cannot write built-in preset\"",
")",
"# Make dictionaries of PresetDefaults values",
"odict",
"=",
"self",
".",
"opts",
".",
"dict",
"(",
... | Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written. | [
"Write",
"this",
"preset",
"to",
"disk",
"in",
"JSON",
"notation",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L374-L391 |
225,674 | sosreport/sos | sos/policies/__init__.py | Policy.get_archive_name | def get_archive_name(self):
"""
This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like the following:
legacy - 'sosreport-tux.123456-20171224185433'
friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'
A custom name_pattern can be used by a policy provided that it
defines name_pattern using a format() style string substitution.
Usable substitutions are:
name - the short hostname of the system
label - the label given by --label
case - the case id given by --case-id or --ticker-number
rand - a random string of 7 alpha characters
Note that if a datestamp is needed, the substring should be set
in the name_pattern in the format accepted by strftime().
"""
name = self.get_local_name().split('.')[0]
case = self.case_id
label = self.commons['cmdlineopts'].label
date = ''
rand = ''.join(random.choice(string.ascii_lowercase) for x in range(7))
if self.name_pattern == 'legacy':
nstr = "sosreport-{name}{case}{date}"
case = '.' + case if case else ''
date = '-%Y%m%d%H%M%S'
elif self.name_pattern == 'friendly':
nstr = "sosreport-{name}{label}{case}{date}-{rand}"
case = '-' + case if case else ''
label = '-' + label if label else ''
date = '-%Y-%m-%d'
else:
nstr = self.name_pattern
nstr = nstr.format(
name=name,
label=label,
case=case,
date=date,
rand=rand
)
return self.sanitize_filename(time.strftime(nstr)) | python | def get_archive_name(self):
"""
This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like the following:
legacy - 'sosreport-tux.123456-20171224185433'
friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'
A custom name_pattern can be used by a policy provided that it
defines name_pattern using a format() style string substitution.
Usable substitutions are:
name - the short hostname of the system
label - the label given by --label
case - the case id given by --case-id or --ticker-number
rand - a random string of 7 alpha characters
Note that if a datestamp is needed, the substring should be set
in the name_pattern in the format accepted by strftime().
"""
name = self.get_local_name().split('.')[0]
case = self.case_id
label = self.commons['cmdlineopts'].label
date = ''
rand = ''.join(random.choice(string.ascii_lowercase) for x in range(7))
if self.name_pattern == 'legacy':
nstr = "sosreport-{name}{case}{date}"
case = '.' + case if case else ''
date = '-%Y%m%d%H%M%S'
elif self.name_pattern == 'friendly':
nstr = "sosreport-{name}{label}{case}{date}-{rand}"
case = '-' + case if case else ''
label = '-' + label if label else ''
date = '-%Y-%m-%d'
else:
nstr = self.name_pattern
nstr = nstr.format(
name=name,
label=label,
case=case,
date=date,
rand=rand
)
return self.sanitize_filename(time.strftime(nstr)) | [
"def",
"get_archive_name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"get_local_name",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"case",
"=",
"self",
".",
"case_id",
"label",
"=",
"self",
".",
"commons",
"[",
"'cmdlineopts'",
"]"... | This function should return the filename of the archive without the
extension.
This uses the policy's name_pattern attribute to determine the name.
There are two pre-defined naming patterns - 'legacy' and 'friendly'
that give names like the following:
legacy - 'sosreport-tux.123456-20171224185433'
friendly - 'sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz'
A custom name_pattern can be used by a policy provided that it
defines name_pattern using a format() style string substitution.
Usable substitutions are:
name - the short hostname of the system
label - the label given by --label
case - the case id given by --case-id or --ticker-number
rand - a random string of 7 alpha characters
Note that if a datestamp is needed, the substring should be set
in the name_pattern in the format accepted by strftime(). | [
"This",
"function",
"should",
"return",
"the",
"filename",
"of",
"the",
"archive",
"without",
"the",
"extension",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L496-L547 |
225,675 | sosreport/sos | sos/policies/__init__.py | Policy.validate_plugin | def validate_plugin(self, plugin_class, experimental=False):
"""
Verifies that the plugin_class should execute under this policy
"""
valid_subclasses = [IndependentPlugin] + self.valid_subclasses
if experimental:
valid_subclasses += [ExperimentalPlugin]
return any(issubclass(plugin_class, class_) for
class_ in valid_subclasses) | python | def validate_plugin(self, plugin_class, experimental=False):
"""
Verifies that the plugin_class should execute under this policy
"""
valid_subclasses = [IndependentPlugin] + self.valid_subclasses
if experimental:
valid_subclasses += [ExperimentalPlugin]
return any(issubclass(plugin_class, class_) for
class_ in valid_subclasses) | [
"def",
"validate_plugin",
"(",
"self",
",",
"plugin_class",
",",
"experimental",
"=",
"False",
")",
":",
"valid_subclasses",
"=",
"[",
"IndependentPlugin",
"]",
"+",
"self",
".",
"valid_subclasses",
"if",
"experimental",
":",
"valid_subclasses",
"+=",
"[",
"Expe... | Verifies that the plugin_class should execute under this policy | [
"Verifies",
"that",
"the",
"plugin_class",
"should",
"execute",
"under",
"this",
"policy"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L591-L599 |
225,676 | sosreport/sos | sos/policies/__init__.py | Policy._print | def _print(self, msg=None, always=False):
"""A wrapper around print that only prints if we are not running in
quiet mode"""
if always or not self.commons['cmdlineopts'].quiet:
if msg:
print_(msg)
else:
print_() | python | def _print(self, msg=None, always=False):
"""A wrapper around print that only prints if we are not running in
quiet mode"""
if always or not self.commons['cmdlineopts'].quiet:
if msg:
print_(msg)
else:
print_() | [
"def",
"_print",
"(",
"self",
",",
"msg",
"=",
"None",
",",
"always",
"=",
"False",
")",
":",
"if",
"always",
"or",
"not",
"self",
".",
"commons",
"[",
"'cmdlineopts'",
"]",
".",
"quiet",
":",
"if",
"msg",
":",
"print_",
"(",
"msg",
")",
"else",
... | A wrapper around print that only prints if we are not running in
quiet mode | [
"A",
"wrapper",
"around",
"print",
"that",
"only",
"prints",
"if",
"we",
"are",
"not",
"running",
"in",
"quiet",
"mode"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L671-L678 |
225,677 | sosreport/sos | sos/policies/__init__.py | Policy.get_msg | def get_msg(self):
"""This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated."""
width = 72
_msg = self.msg % {'distro': self.distro, 'vendor': self.vendor,
'vendor_url': self.vendor_url,
'vendor_text': self.vendor_text,
'tmpdir': self.commons['tmpdir']}
_fmt = ""
for line in _msg.splitlines():
_fmt = _fmt + fill(line, width, replace_whitespace=False) + '\n'
return _fmt | python | def get_msg(self):
"""This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated."""
width = 72
_msg = self.msg % {'distro': self.distro, 'vendor': self.vendor,
'vendor_url': self.vendor_url,
'vendor_text': self.vendor_text,
'tmpdir': self.commons['tmpdir']}
_fmt = ""
for line in _msg.splitlines():
_fmt = _fmt + fill(line, width, replace_whitespace=False) + '\n'
return _fmt | [
"def",
"get_msg",
"(",
"self",
")",
":",
"width",
"=",
"72",
"_msg",
"=",
"self",
".",
"msg",
"%",
"{",
"'distro'",
":",
"self",
".",
"distro",
",",
"'vendor'",
":",
"self",
".",
"vendor",
",",
"'vendor_url'",
":",
"self",
".",
"vendor_url",
",",
"... | This method is used to prepare the preamble text to display to
the user in non-batch mode. If your policy sets self.distro that
text will be substituted accordingly. You can also override this
method to do something more complicated. | [
"This",
"method",
"is",
"used",
"to",
"prepare",
"the",
"preamble",
"text",
"to",
"display",
"to",
"the",
"user",
"in",
"non",
"-",
"batch",
"mode",
".",
"If",
"your",
"policy",
"sets",
"self",
".",
"distro",
"that",
"text",
"will",
"be",
"substituted",
... | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L680-L693 |
225,678 | sosreport/sos | sos/policies/__init__.py | Policy.register_presets | def register_presets(self, presets, replace=False):
"""Add new presets to this policy object.
Merges the presets dictionary ``presets`` into this ``Policy``
object, or replaces the current presets if ``replace`` is
``True``.
``presets`` should be a dictionary mapping ``str`` preset names
to ``<class PresetDefaults>`` objects specifying the command
line defaults.
:param presets: dictionary of presets to add or replace
:param replace: replace presets rather than merge new presets.
"""
if replace:
self.presets = {}
self.presets.update(presets) | python | def register_presets(self, presets, replace=False):
"""Add new presets to this policy object.
Merges the presets dictionary ``presets`` into this ``Policy``
object, or replaces the current presets if ``replace`` is
``True``.
``presets`` should be a dictionary mapping ``str`` preset names
to ``<class PresetDefaults>`` objects specifying the command
line defaults.
:param presets: dictionary of presets to add or replace
:param replace: replace presets rather than merge new presets.
"""
if replace:
self.presets = {}
self.presets.update(presets) | [
"def",
"register_presets",
"(",
"self",
",",
"presets",
",",
"replace",
"=",
"False",
")",
":",
"if",
"replace",
":",
"self",
".",
"presets",
"=",
"{",
"}",
"self",
".",
"presets",
".",
"update",
"(",
"presets",
")"
] | Add new presets to this policy object.
Merges the presets dictionary ``presets`` into this ``Policy``
object, or replaces the current presets if ``replace`` is
``True``.
``presets`` should be a dictionary mapping ``str`` preset names
to ``<class PresetDefaults>`` objects specifying the command
line defaults.
:param presets: dictionary of presets to add or replace
:param replace: replace presets rather than merge new presets. | [
"Add",
"new",
"presets",
"to",
"this",
"policy",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L695-L711 |
225,679 | sosreport/sos | sos/policies/__init__.py | Policy.find_preset | def find_preset(self, preset):
"""Find a preset profile matching the specified preset string.
:param preset: a string containing a preset profile name.
:returns: a matching PresetProfile.
"""
# FIXME: allow fuzzy matching?
for match in self.presets.keys():
if match == preset:
return self.presets[match]
return None | python | def find_preset(self, preset):
"""Find a preset profile matching the specified preset string.
:param preset: a string containing a preset profile name.
:returns: a matching PresetProfile.
"""
# FIXME: allow fuzzy matching?
for match in self.presets.keys():
if match == preset:
return self.presets[match]
return None | [
"def",
"find_preset",
"(",
"self",
",",
"preset",
")",
":",
"# FIXME: allow fuzzy matching?",
"for",
"match",
"in",
"self",
".",
"presets",
".",
"keys",
"(",
")",
":",
"if",
"match",
"==",
"preset",
":",
"return",
"self",
".",
"presets",
"[",
"match",
"]... | Find a preset profile matching the specified preset string.
:param preset: a string containing a preset profile name.
:returns: a matching PresetProfile. | [
"Find",
"a",
"preset",
"profile",
"matching",
"the",
"specified",
"preset",
"string",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L713-L724 |
225,680 | sosreport/sos | sos/policies/__init__.py | Policy.load_presets | def load_presets(self, presets_path=None):
"""Load presets from disk.
Read JSON formatted preset data from the specified path,
or the default location at ``/var/lib/sos/presets``.
:param presets_path: a directory containing JSON presets.
"""
presets_path = presets_path or self.presets_path
if not os.path.exists(presets_path):
return
for preset_path in os.listdir(presets_path):
preset_path = os.path.join(presets_path, preset_path)
try:
preset_data = json.load(open(preset_path))
except ValueError:
continue
for preset in preset_data.keys():
pd = PresetDefaults(preset, opts=SoSOptions())
data = preset_data[preset]
pd.desc = data[DESC] if DESC in data else ""
pd.note = data[NOTE] if NOTE in data else ""
if OPTS in data:
for arg in _arg_names:
if arg in data[OPTS]:
setattr(pd.opts, arg, data[OPTS][arg])
pd.builtin = False
self.presets[preset] = pd | python | def load_presets(self, presets_path=None):
"""Load presets from disk.
Read JSON formatted preset data from the specified path,
or the default location at ``/var/lib/sos/presets``.
:param presets_path: a directory containing JSON presets.
"""
presets_path = presets_path or self.presets_path
if not os.path.exists(presets_path):
return
for preset_path in os.listdir(presets_path):
preset_path = os.path.join(presets_path, preset_path)
try:
preset_data = json.load(open(preset_path))
except ValueError:
continue
for preset in preset_data.keys():
pd = PresetDefaults(preset, opts=SoSOptions())
data = preset_data[preset]
pd.desc = data[DESC] if DESC in data else ""
pd.note = data[NOTE] if NOTE in data else ""
if OPTS in data:
for arg in _arg_names:
if arg in data[OPTS]:
setattr(pd.opts, arg, data[OPTS][arg])
pd.builtin = False
self.presets[preset] = pd | [
"def",
"load_presets",
"(",
"self",
",",
"presets_path",
"=",
"None",
")",
":",
"presets_path",
"=",
"presets_path",
"or",
"self",
".",
"presets_path",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"presets_path",
")",
":",
"return",
"for",
"preset_p... | Load presets from disk.
Read JSON formatted preset data from the specified path,
or the default location at ``/var/lib/sos/presets``.
:param presets_path: a directory containing JSON presets. | [
"Load",
"presets",
"from",
"disk",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L735-L765 |
225,681 | sosreport/sos | sos/policies/__init__.py | Policy.add_preset | def add_preset(self, name=None, desc=None, note=None, opts=SoSOptions()):
"""Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add
"""
presets_path = self.presets_path
if not name:
raise ValueError("Preset name cannot be empty")
if name in self.presets.keys():
raise ValueError("A preset with name '%s' already exists" % name)
preset = PresetDefaults(name=name, desc=desc, note=note, opts=opts)
preset.builtin = False
self.presets[preset.name] = preset
preset.write(presets_path) | python | def add_preset(self, name=None, desc=None, note=None, opts=SoSOptions()):
"""Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add
"""
presets_path = self.presets_path
if not name:
raise ValueError("Preset name cannot be empty")
if name in self.presets.keys():
raise ValueError("A preset with name '%s' already exists" % name)
preset = PresetDefaults(name=name, desc=desc, note=note, opts=opts)
preset.builtin = False
self.presets[preset.name] = preset
preset.write(presets_path) | [
"def",
"add_preset",
"(",
"self",
",",
"name",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"note",
"=",
"None",
",",
"opts",
"=",
"SoSOptions",
"(",
")",
")",
":",
"presets_path",
"=",
"self",
".",
"presets_path",
"if",
"not",
"name",
":",
"raise",
... | Add a new on-disk preset and write it to the configured
presets path.
:param preset: the new PresetDefaults to add | [
"Add",
"a",
"new",
"on",
"-",
"disk",
"preset",
"and",
"write",
"it",
"to",
"the",
"configured",
"presets",
"path",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L767-L784 |
225,682 | sosreport/sos | sos/policies/__init__.py | LinuxPolicy.lsmod | def lsmod(self):
"""Return a list of kernel module names as strings.
"""
lines = shell_out("lsmod", timeout=0).splitlines()
return [line.split()[0].strip() for line in lines] | python | def lsmod(self):
"""Return a list of kernel module names as strings.
"""
lines = shell_out("lsmod", timeout=0).splitlines()
return [line.split()[0].strip() for line in lines] | [
"def",
"lsmod",
"(",
"self",
")",
":",
"lines",
"=",
"shell_out",
"(",
"\"lsmod\"",
",",
"timeout",
"=",
"0",
")",
".",
"splitlines",
"(",
")",
"return",
"[",
"line",
".",
"split",
"(",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"for",
"line",
... | Return a list of kernel module names as strings. | [
"Return",
"a",
"list",
"of",
"kernel",
"module",
"names",
"as",
"strings",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/policies/__init__.py#L873-L877 |
225,683 | sosreport/sos | sos/plugins/lvm2.py | Lvm2.do_lvmdump | def do_lvmdump(self, metadata=False):
"""Collects an lvmdump in standard format with optional metadata
archives for each physical volume present.
"""
lvmdump_path = self.get_cmd_output_path(name="lvmdump", make=False)
lvmdump_cmd = "lvmdump %s -d '%s'"
lvmdump_opts = ""
if metadata:
lvmdump_opts = "-a -m"
cmd = lvmdump_cmd % (lvmdump_opts, lvmdump_path)
self.add_cmd_output(cmd, chroot=self.tmp_in_sysroot()) | python | def do_lvmdump(self, metadata=False):
"""Collects an lvmdump in standard format with optional metadata
archives for each physical volume present.
"""
lvmdump_path = self.get_cmd_output_path(name="lvmdump", make=False)
lvmdump_cmd = "lvmdump %s -d '%s'"
lvmdump_opts = ""
if metadata:
lvmdump_opts = "-a -m"
cmd = lvmdump_cmd % (lvmdump_opts, lvmdump_path)
self.add_cmd_output(cmd, chroot=self.tmp_in_sysroot()) | [
"def",
"do_lvmdump",
"(",
"self",
",",
"metadata",
"=",
"False",
")",
":",
"lvmdump_path",
"=",
"self",
".",
"get_cmd_output_path",
"(",
"name",
"=",
"\"lvmdump\"",
",",
"make",
"=",
"False",
")",
"lvmdump_cmd",
"=",
"\"lvmdump %s -d '%s'\"",
"lvmdump_opts",
"... | Collects an lvmdump in standard format with optional metadata
archives for each physical volume present. | [
"Collects",
"an",
"lvmdump",
"in",
"standard",
"format",
"with",
"optional",
"metadata",
"archives",
"for",
"each",
"physical",
"volume",
"present",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/lvm2.py#L24-L37 |
225,684 | sosreport/sos | sos/__init__.py | SoSOptions.__str | def __str(self, quote=False, sep=" ", prefix="", suffix=""):
"""Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals
"""
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix | python | def __str(self, quote=False, sep=" ", prefix="", suffix=""):
"""Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals
"""
args = prefix
arg_fmt = "=%s"
for arg in _arg_names:
args += arg + arg_fmt + sep
args.strip(sep)
vals = [getattr(self, arg) for arg in _arg_names]
if not quote:
# Convert Python source notation for sequences into plain strings
vals = [",".join(v) if _is_seq(v) else v for v in vals]
else:
def is_string(val):
return isinstance(val, six.string_types)
# Only quote strings if quote=False
vals = ["'%s'" % v if is_string(v) else v for v in vals]
return (args % tuple(vals)).strip(sep) + suffix | [
"def",
"__str",
"(",
"self",
",",
"quote",
"=",
"False",
",",
"sep",
"=",
"\" \"",
",",
"prefix",
"=",
"\"\"",
",",
"suffix",
"=",
"\"\"",
")",
":",
"args",
"=",
"prefix",
"arg_fmt",
"=",
"\"=%s\"",
"for",
"arg",
"in",
"_arg_names",
":",
"args",
"+... | Format a SoSOptions object as a human or machine readable string.
:param quote: quote option values
:param sep: list separator string
:param prefix: arbitrary prefix string
:param suffix: arbitrary suffix string
:param literal: print values as Python literals | [
"Format",
"a",
"SoSOptions",
"object",
"as",
"a",
"human",
"or",
"machine",
"readable",
"string",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L111-L136 |
225,685 | sosreport/sos | sos/__init__.py | SoSOptions.from_args | def from_args(cls, args):
"""Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions
"""
opts = SoSOptions()
opts._merge_opts(args, True)
return opts | python | def from_args(cls, args):
"""Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions
"""
opts = SoSOptions()
opts._merge_opts(args, True)
return opts | [
"def",
"from_args",
"(",
"cls",
",",
"args",
")",
":",
"opts",
"=",
"SoSOptions",
"(",
")",
"opts",
".",
"_merge_opts",
"(",
"args",
",",
"True",
")",
"return",
"opts"
] | Initialise a new SoSOptions object from a ``Namespace``
obtained by parsing command line arguments.
:param args: parsed command line arguments
:returns: an initialised SoSOptions object
:returntype: SoSOptions | [
"Initialise",
"a",
"new",
"SoSOptions",
"object",
"from",
"a",
"Namespace",
"obtained",
"by",
"parsing",
"command",
"line",
"arguments",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L201-L211 |
225,686 | sosreport/sos | sos/__init__.py | SoSOptions.merge | def merge(self, src, skip_default=True):
"""Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set.
"""
for arg in _arg_names:
if not hasattr(src, arg):
continue
if getattr(src, arg) is not None or not skip_default:
self._merge_opt(arg, src, False) | python | def merge(self, src, skip_default=True):
"""Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set.
"""
for arg in _arg_names:
if not hasattr(src, arg):
continue
if getattr(src, arg) is not None or not skip_default:
self._merge_opt(arg, src, False) | [
"def",
"merge",
"(",
"self",
",",
"src",
",",
"skip_default",
"=",
"True",
")",
":",
"for",
"arg",
"in",
"_arg_names",
":",
"if",
"not",
"hasattr",
"(",
"src",
",",
"arg",
")",
":",
"continue",
"if",
"getattr",
"(",
"src",
",",
"arg",
")",
"is",
... | Merge another set of ``SoSOptions`` into this object.
Merge two ``SoSOptions`` objects by setting unset or default
values to their value in the ``src`` object.
:param src: the ``SoSOptions`` object to copy from
:param is_default: ``True`` if new default values are to be set. | [
"Merge",
"another",
"set",
"of",
"SoSOptions",
"into",
"this",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L272-L285 |
225,687 | sosreport/sos | sos/__init__.py | SoSOptions.dict | def dict(self):
"""Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values.
"""
odict = {}
for arg in _arg_names:
value = getattr(self, arg)
# Do not attempt to store preset option values in presets
if arg in ('add_preset', 'del_preset', 'desc', 'note'):
value = None
odict[arg] = value
return odict | python | def dict(self):
"""Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values.
"""
odict = {}
for arg in _arg_names:
value = getattr(self, arg)
# Do not attempt to store preset option values in presets
if arg in ('add_preset', 'del_preset', 'desc', 'note'):
value = None
odict[arg] = value
return odict | [
"def",
"dict",
"(",
"self",
")",
":",
"odict",
"=",
"{",
"}",
"for",
"arg",
"in",
"_arg_names",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"arg",
")",
"# Do not attempt to store preset option values in presets",
"if",
"arg",
"in",
"(",
"'add_preset'",
"... | Return this ``SoSOptions`` option values as a dictionary of
argument name to value mappings.
:returns: a name:value dictionary of option values. | [
"Return",
"this",
"SoSOptions",
"option",
"values",
"as",
"a",
"dictionary",
"of",
"argument",
"name",
"to",
"value",
"mappings",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L287-L300 |
225,688 | sosreport/sos | sos/__init__.py | SoSOptions.to_args | def to_args(self):
"""Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]``
"""
def has_value(name, value):
""" Test for non-null option values.
"""
null_values = ("False", "None", "[]", '""', "''", "0")
if not value or value in null_values:
return False
if name in _arg_defaults:
if str(value) == str(_arg_defaults[name]):
return False
return True
def filter_opt(name, value):
""" Filter out preset and null-valued options.
"""
if name in ("add_preset", "del_preset", "desc", "note"):
return False
return has_value(name, value)
def argify(name, value):
""" Convert sos option notation to command line arguments.
"""
# Handle --verbosity specially
if name.startswith("verbosity"):
arg = "-" + int(value) * "v"
return arg
name = name.replace("_", "-")
value = ",".join(value) if _is_seq(value) else value
if value is not True:
opt = "%s %s" % (name, value)
else:
opt = name
arg = "--" + opt if len(opt) > 1 else "-" + opt
return arg
opt_items = sorted(self.dict().items(), key=lambda x: x[0])
return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)] | python | def to_args(self):
"""Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]``
"""
def has_value(name, value):
""" Test for non-null option values.
"""
null_values = ("False", "None", "[]", '""', "''", "0")
if not value or value in null_values:
return False
if name in _arg_defaults:
if str(value) == str(_arg_defaults[name]):
return False
return True
def filter_opt(name, value):
""" Filter out preset and null-valued options.
"""
if name in ("add_preset", "del_preset", "desc", "note"):
return False
return has_value(name, value)
def argify(name, value):
""" Convert sos option notation to command line arguments.
"""
# Handle --verbosity specially
if name.startswith("verbosity"):
arg = "-" + int(value) * "v"
return arg
name = name.replace("_", "-")
value = ",".join(value) if _is_seq(value) else value
if value is not True:
opt = "%s %s" % (name, value)
else:
opt = name
arg = "--" + opt if len(opt) > 1 else "-" + opt
return arg
opt_items = sorted(self.dict().items(), key=lambda x: x[0])
return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)] | [
"def",
"to_args",
"(",
"self",
")",
":",
"def",
"has_value",
"(",
"name",
",",
"value",
")",
":",
"\"\"\" Test for non-null option values.\n \"\"\"",
"null_values",
"=",
"(",
"\"False\"",
",",
"\"None\"",
",",
"\"[]\"",
",",
"'\"\"'",
",",
"\"''\"",
"... | Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]`` | [
"Return",
"command",
"arguments",
"for",
"this",
"object",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/__init__.py#L302-L350 |
225,689 | sosreport/sos | sos/plugins/autofs.py | Autofs.checkdebug | def checkdebug(self):
""" testing if autofs debug has been enabled anywhere
"""
# Global debugging
opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
*self.files)
for opt1 in opt:
for opt2 in opt1.split(" "):
if opt2 in ("--debug", "debug"):
return True
return False | python | def checkdebug(self):
""" testing if autofs debug has been enabled anywhere
"""
# Global debugging
opt = self.file_grep(r"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)",
*self.files)
for opt1 in opt:
for opt2 in opt1.split(" "):
if opt2 in ("--debug", "debug"):
return True
return False | [
"def",
"checkdebug",
"(",
"self",
")",
":",
"# Global debugging",
"opt",
"=",
"self",
".",
"file_grep",
"(",
"r\"^(DEFAULT_LOGGING|DAEMONOPTIONS)=(.*)\"",
",",
"*",
"self",
".",
"files",
")",
"for",
"opt1",
"in",
"opt",
":",
"for",
"opt2",
"in",
"opt1",
".",... | testing if autofs debug has been enabled anywhere | [
"testing",
"if",
"autofs",
"debug",
"has",
"been",
"enabled",
"anywhere"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/autofs.py#L24-L34 |
225,690 | sosreport/sos | sos/plugins/autofs.py | Autofs.getdaemondebug | def getdaemondebug(self):
""" capture daemon debug output
"""
debugout = self.file_grep(r"^(daemon.*)\s+(\/var\/log\/.*)",
*self.files)
for i in debugout:
return i[1] | python | def getdaemondebug(self):
""" capture daemon debug output
"""
debugout = self.file_grep(r"^(daemon.*)\s+(\/var\/log\/.*)",
*self.files)
for i in debugout:
return i[1] | [
"def",
"getdaemondebug",
"(",
"self",
")",
":",
"debugout",
"=",
"self",
".",
"file_grep",
"(",
"r\"^(daemon.*)\\s+(\\/var\\/log\\/.*)\"",
",",
"*",
"self",
".",
"files",
")",
"for",
"i",
"in",
"debugout",
":",
"return",
"i",
"[",
"1",
"]"
] | capture daemon debug output | [
"capture",
"daemon",
"debug",
"output"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/autofs.py#L36-L42 |
225,691 | sosreport/sos | sos/plugins/jars.py | Jars.is_jar | def is_jar(path):
"""Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'.
"""
if os.path.isfile(path) and zipfile.is_zipfile(path):
try:
with zipfile.ZipFile(path) as f:
if "META-INF/MANIFEST.MF" in f.namelist():
return True
except (IOError, zipfile.BadZipfile):
pass
return False | python | def is_jar(path):
"""Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'.
"""
if os.path.isfile(path) and zipfile.is_zipfile(path):
try:
with zipfile.ZipFile(path) as f:
if "META-INF/MANIFEST.MF" in f.namelist():
return True
except (IOError, zipfile.BadZipfile):
pass
return False | [
"def",
"is_jar",
"(",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"zipfile",
".",
"is_zipfile",
"(",
"path",
")",
":",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"path",
")",
"as",
"f",
":",
"if",
... | Check whether given file is a JAR file.
JARs are ZIP files which usually include a manifest
at the canonical location 'META-INF/MANIFEST.MF'. | [
"Check",
"whether",
"given",
"file",
"is",
"a",
"JAR",
"file",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L84-L97 |
225,692 | sosreport/sos | sos/plugins/jars.py | Jars.get_maven_id | def get_maven_id(jar_path):
"""Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there.
"""
props = {}
try:
with zipfile.ZipFile(jar_path) as f:
r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
result = [x for x in f.namelist() if r.match(x)]
if len(result) != 1:
return None
with f.open(result[0]) as props_f:
for line in props_f.readlines():
line = line.strip()
if not line.startswith(b"#"):
try:
(key, value) = line.split(b"=")
key = key.decode('utf8').strip()
value = value.decode('utf8').strip()
props[key] = value
except ValueError:
return None
except IOError:
pass
return props | python | def get_maven_id(jar_path):
"""Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there.
"""
props = {}
try:
with zipfile.ZipFile(jar_path) as f:
r = re.compile("META-INF/maven/[^/]+/[^/]+/pom.properties$")
result = [x for x in f.namelist() if r.match(x)]
if len(result) != 1:
return None
with f.open(result[0]) as props_f:
for line in props_f.readlines():
line = line.strip()
if not line.startswith(b"#"):
try:
(key, value) = line.split(b"=")
key = key.decode('utf8').strip()
value = value.decode('utf8').strip()
props[key] = value
except ValueError:
return None
except IOError:
pass
return props | [
"def",
"get_maven_id",
"(",
"jar_path",
")",
":",
"props",
"=",
"{",
"}",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"jar_path",
")",
"as",
"f",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"\"META-INF/maven/[^/]+/[^/]+/pom.properties$\"",
")",
"resu... | Extract Maven coordinates from a given JAR file, if possible.
JARs build by Maven (most popular Java build system) contain
'pom.properties' file. We can extract Maven coordinates
from there. | [
"Extract",
"Maven",
"coordinates",
"from",
"a",
"given",
"JAR",
"file",
"if",
"possible",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L100-L127 |
225,693 | sosreport/sos | sos/plugins/jars.py | Jars.get_jar_id | def get_jar_id(jar_path):
"""Compute JAR id.
Returns sha1 hash of a given JAR file.
"""
jar_id = ""
try:
with open(jar_path, mode="rb") as f:
m = hashlib.sha1()
for buf in iter(partial(f.read, 4096), b''):
m.update(buf)
jar_id = m.hexdigest()
except IOError:
pass
return jar_id | python | def get_jar_id(jar_path):
"""Compute JAR id.
Returns sha1 hash of a given JAR file.
"""
jar_id = ""
try:
with open(jar_path, mode="rb") as f:
m = hashlib.sha1()
for buf in iter(partial(f.read, 4096), b''):
m.update(buf)
jar_id = m.hexdigest()
except IOError:
pass
return jar_id | [
"def",
"get_jar_id",
"(",
"jar_path",
")",
":",
"jar_id",
"=",
"\"\"",
"try",
":",
"with",
"open",
"(",
"jar_path",
",",
"mode",
"=",
"\"rb\"",
")",
"as",
"f",
":",
"m",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"buf",
"in",
"iter",
"(",
"par... | Compute JAR id.
Returns sha1 hash of a given JAR file. | [
"Compute",
"JAR",
"id",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/jars.py#L130-L144 |
225,694 | sosreport/sos | sos/plugins/qpid.py | Qpid.setup | def setup(self):
""" performs data collection for qpid broker """
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key"]:
if self.get_option(option):
amqps_prefix = "amqps://"
options = (options + " --%s=" % (option) +
self.get_option(option))
if self.get_option("port"):
options = (options + " -b " + amqps_prefix +
"localhost:%s" % (self.get_option("port")))
self.add_cmd_output([
"qpid-stat -g" + options, # applies since 0.18 version
"qpid-stat -b" + options, # applies to pre-0.18 versions
"qpid-stat -c" + options,
"qpid-stat -e" + options,
"qpid-stat -q" + options,
"qpid-stat -u" + options,
"qpid-stat -m" + options, # applies since 0.18 version
"qpid-config exchanges" + options,
"qpid-config queues" + options,
"qpid-config exchanges -b" + options, # applies to pre-0.18 vers.
"qpid-config queues -b" + options, # applies to pre-0.18 versions
"qpid-config exchanges -r" + options, # applies since 0.18 version
"qpid-config queues -r" + options, # applies since 0.18 version
"qpid-route link list" + options,
"qpid-route route list" + options,
"qpid-cluster" + options, # applies to pre-0.22 versions
"qpid-ha query" + options, # applies since 0.22 version
"ls -lanR /var/lib/qpidd"
])
self.add_copy_spec([
"/etc/qpidd.conf", # applies to pre-0.22 versions
"/etc/qpid/qpidd.conf", # applies since 0.22 version
"/var/lib/qpid/syslog",
"/etc/ais/openais.conf",
"/var/log/cumin.log",
"/var/log/mint.log",
"/etc/sasl2/qpidd.conf",
"/etc/qpid/qpidc.conf",
"/etc/sesame/sesame.conf",
"/etc/cumin/cumin.conf",
"/etc/corosync/corosync.conf",
"/var/lib/sesame",
"/var/log/qpidd.log",
"/var/log/sesame",
"/var/log/cumin"
]) | python | def setup(self):
""" performs data collection for qpid broker """
options = ""
amqps_prefix = "" # set amqps:// when SSL is used
if self.get_option("ssl"):
amqps_prefix = "amqps://"
# for either present option, add --option=value to 'options' variable
for option in ["ssl-certificate", "ssl-key"]:
if self.get_option(option):
amqps_prefix = "amqps://"
options = (options + " --%s=" % (option) +
self.get_option(option))
if self.get_option("port"):
options = (options + " -b " + amqps_prefix +
"localhost:%s" % (self.get_option("port")))
self.add_cmd_output([
"qpid-stat -g" + options, # applies since 0.18 version
"qpid-stat -b" + options, # applies to pre-0.18 versions
"qpid-stat -c" + options,
"qpid-stat -e" + options,
"qpid-stat -q" + options,
"qpid-stat -u" + options,
"qpid-stat -m" + options, # applies since 0.18 version
"qpid-config exchanges" + options,
"qpid-config queues" + options,
"qpid-config exchanges -b" + options, # applies to pre-0.18 vers.
"qpid-config queues -b" + options, # applies to pre-0.18 versions
"qpid-config exchanges -r" + options, # applies since 0.18 version
"qpid-config queues -r" + options, # applies since 0.18 version
"qpid-route link list" + options,
"qpid-route route list" + options,
"qpid-cluster" + options, # applies to pre-0.22 versions
"qpid-ha query" + options, # applies since 0.22 version
"ls -lanR /var/lib/qpidd"
])
self.add_copy_spec([
"/etc/qpidd.conf", # applies to pre-0.22 versions
"/etc/qpid/qpidd.conf", # applies since 0.22 version
"/var/lib/qpid/syslog",
"/etc/ais/openais.conf",
"/var/log/cumin.log",
"/var/log/mint.log",
"/etc/sasl2/qpidd.conf",
"/etc/qpid/qpidc.conf",
"/etc/sesame/sesame.conf",
"/etc/cumin/cumin.conf",
"/etc/corosync/corosync.conf",
"/var/lib/sesame",
"/var/log/qpidd.log",
"/var/log/sesame",
"/var/log/cumin"
]) | [
"def",
"setup",
"(",
"self",
")",
":",
"options",
"=",
"\"\"",
"amqps_prefix",
"=",
"\"\"",
"# set amqps:// when SSL is used",
"if",
"self",
".",
"get_option",
"(",
"\"ssl\"",
")",
":",
"amqps_prefix",
"=",
"\"amqps://\"",
"# for either present option, add --option=va... | performs data collection for qpid broker | [
"performs",
"data",
"collection",
"for",
"qpid",
"broker"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/qpid.py#L27-L80 |
225,695 | sosreport/sos | sos/sosreport.py | SoSReport._exception | def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
six.print_()
# ...then start the debugger in post-mortem mode.
pdb.pm() | python | def _exception(etype, eval_, etrace):
""" Wrap exception in debugger if not in tty """
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(etype, eval_, etrace)
else:
# we are NOT in interactive mode, print the exception...
traceback.print_exception(etype, eval_, etrace, limit=2,
file=sys.stdout)
six.print_()
# ...then start the debugger in post-mortem mode.
pdb.pm() | [
"def",
"_exception",
"(",
"etype",
",",
"eval_",
",",
"etrace",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"'ps1'",
")",
"or",
"not",
"sys",
".",
"stderr",
".",
"isatty",
"(",
")",
":",
"# we are in interactive mode or we don't have a tty-like",
"# device, so... | Wrap exception in debugger if not in tty | [
"Wrap",
"exception",
"in",
"debugger",
"if",
"not",
"in",
"tty"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L404-L416 |
225,696 | sosreport/sos | sos/sosreport.py | SoSReport.add_preset | def add_preset(self, name, desc="", note=""):
"""Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise
"""
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self._args.index("--add-preset")
args = self._args[0:arg_index] + self._args[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True | python | def add_preset(self, name, desc="", note=""):
"""Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise
"""
policy = self.policy
if policy.find_preset(name):
self.ui_log.error("A preset named '%s' already exists" % name)
return False
desc = desc or self.opts.desc
note = note or self.opts.note
try:
policy.add_preset(name=name, desc=desc, note=note, opts=self.opts)
except Exception as e:
self.ui_log.error("Could not add preset: %s" % e)
return False
# Filter --add-preset <name> from arguments list
arg_index = self._args.index("--add-preset")
args = self._args[0:arg_index] + self._args[arg_index + 2:]
self.ui_log.info("Added preset '%s' with options %s\n" %
(name, " ".join(args)))
return True | [
"def",
"add_preset",
"(",
"self",
",",
"name",
",",
"desc",
"=",
"\"\"",
",",
"note",
"=",
"\"\"",
")",
":",
"policy",
"=",
"self",
".",
"policy",
"if",
"policy",
".",
"find_preset",
"(",
"name",
")",
":",
"self",
".",
"ui_log",
".",
"error",
"(",
... | Add a new command line preset for the current options with the
specified name.
:param name: the name of the new preset
:returns: True on success or False otherwise | [
"Add",
"a",
"new",
"command",
"line",
"preset",
"for",
"the",
"current",
"options",
"with",
"the",
"specified",
"name",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L802-L829 |
225,697 | sosreport/sos | sos/sosreport.py | SoSReport.del_preset | def del_preset(self, name):
"""Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise
"""
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True | python | def del_preset(self, name):
"""Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise
"""
policy = self.policy
if not policy.find_preset(name):
self.ui_log.error("Preset '%s' not found" % name)
return False
try:
policy.del_preset(name=name)
except Exception as e:
self.ui_log.error(str(e) + "\n")
return False
self.ui_log.info("Deleted preset '%s'\n" % name)
return True | [
"def",
"del_preset",
"(",
"self",
",",
"name",
")",
":",
"policy",
"=",
"self",
".",
"policy",
"if",
"not",
"policy",
".",
"find_preset",
"(",
"name",
")",
":",
"self",
".",
"ui_log",
".",
"error",
"(",
"\"Preset '%s' not found\"",
"%",
"name",
")",
"r... | Delete a named command line preset.
:param name: the name of the preset to delete
:returns: True on success or False otherwise | [
"Delete",
"a",
"named",
"command",
"line",
"preset",
"."
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L831-L849 |
225,698 | sosreport/sos | sos/sosreport.py | SoSReport.version | def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt') | python | def version(self):
"""Fetch version information from all plugins and store in the report
version file"""
versions = []
versions.append("sosreport: %s" % __version__)
for plugname, plug in self.loaded_plugins:
versions.append("%s: %s" % (plugname, plug.version))
self.archive.add_string(content="\n".join(versions),
dest='version.txt') | [
"def",
"version",
"(",
"self",
")",
":",
"versions",
"=",
"[",
"]",
"versions",
".",
"append",
"(",
"\"sosreport: %s\"",
"%",
"__version__",
")",
"for",
"plugname",
",",
"plug",
"in",
"self",
".",
"loaded_plugins",
":",
"versions",
".",
"append",
"(",
"\... | Fetch version information from all plugins and store in the report
version file | [
"Fetch",
"version",
"information",
"from",
"all",
"plugins",
"and",
"store",
"in",
"the",
"report",
"version",
"file"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/sosreport.py#L949-L960 |
225,699 | sosreport/sos | sos/plugins/navicli.py | Navicli.get_navicli_SP_info | def get_navicli_SP_info(self, SP_address):
""" EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands
"""
self.add_cmd_output([
"navicli -h %s getall" % SP_address,
"navicli -h %s getsptime -spa" % SP_address,
"navicli -h %s getsptime -spb" % SP_address,
"navicli -h %s getlog" % SP_address,
"navicli -h %s getdisk" % SP_address,
"navicli -h %s getcache" % SP_address,
"navicli -h %s getlun" % SP_address,
"navicli -h %s getlun -rg -type -default -owner -crus "
"-capacity" % SP_address,
"navicli -h %s lunmapinfo" % SP_address,
"navicli -h %s getcrus" % SP_address,
"navicli -h %s port -list -all" % SP_address,
"navicli -h %s storagegroup -list" % SP_address,
"navicli -h %s spportspeed -get" % SP_address
]) | python | def get_navicli_SP_info(self, SP_address):
""" EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands
"""
self.add_cmd_output([
"navicli -h %s getall" % SP_address,
"navicli -h %s getsptime -spa" % SP_address,
"navicli -h %s getsptime -spb" % SP_address,
"navicli -h %s getlog" % SP_address,
"navicli -h %s getdisk" % SP_address,
"navicli -h %s getcache" % SP_address,
"navicli -h %s getlun" % SP_address,
"navicli -h %s getlun -rg -type -default -owner -crus "
"-capacity" % SP_address,
"navicli -h %s lunmapinfo" % SP_address,
"navicli -h %s getcrus" % SP_address,
"navicli -h %s port -list -all" % SP_address,
"navicli -h %s storagegroup -list" % SP_address,
"navicli -h %s spportspeed -get" % SP_address
]) | [
"def",
"get_navicli_SP_info",
"(",
"self",
",",
"SP_address",
")",
":",
"self",
".",
"add_cmd_output",
"(",
"[",
"\"navicli -h %s getall\"",
"%",
"SP_address",
",",
"\"navicli -h %s getsptime -spa\"",
"%",
"SP_address",
",",
"\"navicli -h %s getsptime -spb\"",
"%",
"SP_... | EMC Navisphere Host Agent NAVICLI specific
information - CLARiiON - commands | [
"EMC",
"Navisphere",
"Host",
"Agent",
"NAVICLI",
"specific",
"information",
"-",
"CLARiiON",
"-",
"commands"
] | 2ebc04da53dc871c8dd5243567afa4f8592dca29 | https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/navicli.py#L41-L60 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.