| 1 |
# -*- Mode: Python -*- |
| 2 |
# cython: embedsignature=True |
| 3 |
# cython: language_level=3 |
| 4 |
|
| 5 |
# TODO: When Cython3 is release |
| 6 |
# Change from the deprecated the numpy 1.7 API, see |
| 7 |
# - https://github.com/cython/cython/issues/2498 |
| 8 |
# - https://github.com/scipy/scipy/pull/10840#issuecomment-549939230 |
| 9 |
|
| 10 |
import cython |
| 11 |
import numpy as np |
| 12 |
cimport numpy as np |
| 13 |
from numpy cimport ( |
| 14 |
ndarray, |
| 15 |
npy_intp, |
| 16 |
NPY_DOUBLE, |
| 17 |
PyArray_SimpleNewFromData, |
| 18 |
) |
| 19 |
cimport c_loess # c_loess.pxd |
| 20 |
|
| 21 |
# NumPy must be initialized |
| 22 |
np.import_array() |
| 23 |
|
| 24 |
|
| 25 |
cdef floatarray_from_data(int rows, int cols, double *data): |
| 26 |
cdef ndarray a_ndr |
| 27 |
cdef npy_intp dims[2] |
| 28 |
cdef int nd |
| 29 |
dims = (rows, cols) |
| 30 |
nd = 2 if cols > 1 else 1 |
| 31 |
a_ndr = <object>PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, data) |
| 32 |
# Since the memory is owned by the containing object, we pass a copy |
| 33 |
# of the data so that when the owner is destroyed the return data |
| 34 |
# is not destroyed. |
| 35 |
return a_ndr.copy() |
| 36 |
|
| 37 |
|
| 38 |
cdef boolarray_from_data(int rows, int cols, int *data): |
| 39 |
cdef ndarray a_ndr |
| 40 |
cdef npy_intp dims[2] |
| 41 |
cdef int nd |
| 42 |
dims = (rows, cols) |
| 43 |
nd = 2 if cols > 1 else 1 |
| 44 |
a_ndr = <object>PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, data) |
| 45 |
# Since the memory is owned by the containing object, we pass a copy |
| 46 |
# of the data so that when the owner is destroyed the return data |
| 47 |
# is not destroyed. |
| 48 |
return a_ndr.astype(bool).copy() |
| 49 |
|
| 50 |
|
| 51 |
cdef class loess_inputs: |
| 52 |
""" |
| 53 |
Initialization class for loess data inputs |
| 54 |
|
| 55 |
Parameters |
| 56 |
---------- |
| 57 |
x : ndarray[n, p] |
| 58 |
n independent observations for p no. of variables |
| 59 |
y : ndarray[n] |
| 60 |
A (n,) ndarray of response observations |
| 61 |
weights : ndarray[n] or None |
| 62 |
Weights to be given to individual observations |
| 63 |
in the sum of squared residuals that forms the local fitting |
| 64 |
criterion. If not None, the weights should be non negative. If |
| 65 |
the different observations have non-equal variances, the weights |
| 66 |
should be inversely proportional to the variances. By default, |
| 67 |
an unweighted fit is carried out (all the weights are one). |
| 68 |
""" |
| 69 |
cdef c_loess.c_loess_inputs _base |
| 70 |
cdef readonly allocated |
| 71 |
|
| 72 |
def __cinit__(self, x, y, weights=None): |
| 73 |
cdef ndarray _x, _y, _w |
| 74 |
# When errors are raised the object gets destroyed and |
| 75 |
# __dealloc__ is called. It should not free up memory |
| 76 |
# if none was allocated prior to the error. |
| 77 |
self.allocated = False |
| 78 |
|
| 79 |
x = np.array(x, copy=False, subok=True, |
| 80 |
dtype=np.float_, order='C') |
| 81 |
y = np.array(y, copy=False, subok=True, |
| 82 |
dtype=np.float_, order='C') |
| 83 |
n = len(x) |
| 84 |
|
| 85 |
# Check the dimensions |
| 86 |
if x.ndim == 1: |
| 87 |
p = 1 |
| 88 |
elif x.ndim == 2: |
| 89 |
p = x.shape[1] |
| 90 |
else: |
| 91 |
raise ValueError("The array of independent variables " |
| 92 |
"should be 2D at most!") |
| 93 |
|
| 94 |
if y.ndim != 1: |
| 95 |
raise ValueError("The array of dependent variables " |
| 96 |
"should be 1D.") |
| 97 |
elif n != len(y): |
| 98 |
raise ValueError("The independent and dependent variables " |
| 99 |
"should have the same number of " |
| 100 |
"observations.") |
| 101 |
|
| 102 |
if weights is None: |
| 103 |
weights = np.ones((n,), dtype=np.float_) |
| 104 |
|
| 105 |
if weights.ndim > 1 or weights.size != n: |
| 106 |
raise ValueError("Invalid size of the 'weights' vector!") |
| 107 |
|
| 108 |
weights = np.array(weights, copy=False, subok=True, |
| 109 |
dtype=np.float_, order='C') |
| 110 |
|
| 111 |
# Python objects -> C structures -> *data in C structures |
| 112 |
_x = x.ravel() |
| 113 |
_y = y |
| 114 |
_w = weights |
| 115 |
|
| 116 |
x_dat = <double *>_x.data |
| 117 |
y_dat = <double *>_y.data |
| 118 |
w_dat = <double *>_w.data |
| 119 |
|
| 120 |
c_loess.loess_inputs_setup(x_dat, y_dat, w_dat, n, p, &self._base) |
| 121 |
self.allocated = True |
| 122 |
|
| 123 |
def __init__(self, x, y, weights=None): |
| 124 |
# For documentation |
| 125 |
pass |
| 126 |
|
| 127 |
def __dealloc__(self): |
| 128 |
if self.allocated: |
| 129 |
c_loess.loess_inputs_free(&self._base) |
| 130 |
|
| 131 |
@property |
| 132 |
def n(self): |
| 133 |
""" |
| 134 |
:class:`int` - Number of independent observations |
| 135 |
""" |
| 136 |
return self._base.n |
| 137 |
|
| 138 |
@property |
| 139 |
def p(self): |
| 140 |
""" |
| 141 |
:class:`int` - Number of variables |
| 142 |
""" |
| 143 |
return self._base.p |
| 144 |
|
| 145 |
@property |
| 146 |
def x(self): |
| 147 |
""" |
| 148 |
:class:`~numpy.ndarray` - Independent observations, shape ``(n, p)`` |
| 149 |
""" |
| 150 |
return floatarray_from_data(self.n, self.p, self._base.x) |
| 151 |
|
| 152 |
@property |
| 153 |
def y(self): |
| 154 |
""" |
| 155 |
:class:`~numpy.ndarray` - Response observations, shape ``(n,)`` |
| 156 |
""" |
| 157 |
return floatarray_from_data(self.n, 1, self._base.y) |
| 158 |
|
| 159 |
|
| 160 |
cdef class loess_control: |
| 161 |
""" |
| 162 |
Initialization class for loess control parameters |
| 163 |
|
| 164 |
Parameters |
| 165 |
---------- |
| 166 |
surface : str, optional |
| 167 |
One of ['interpolate', 'direct'] |
| 168 |
Determines whether the fitted surface is computed directly |
| 169 |
at all points ('direct') or whether an interpolation method |
| 170 |
is used ('interpolate'). The default 'interpolate') is what |
| 171 |
most users should use unless special circumstances warrant. |
| 172 |
statistics : str, optional |
| 173 |
One of ['approximate', 'exact'] |
| 174 |
Determines whether the statistical quantities are computed |
| 175 |
exactly ('exact') or approximately ('approximate'). 'exact' |
| 176 |
should only be used for testing the approximation in |
| 177 |
statistical development and is not meant for routine usage |
| 178 |
because computation time can be horrendous. |
| 179 |
trace_hat : str, optional |
| 180 |
One of ['wait.to.decide', 'exact', 'approximate'] |
| 181 |
Determines how the trace of the hat matrix should be computed. |
| 182 |
The hat matrix is used in the computation of the statistical |
| 183 |
quantities. If 'exact', an exact computation is done; this |
| 184 |
could be slow when the number of observations n becomes large. |
| 185 |
If 'wait.to.decide' is selected, then a default is 'exact' |
| 186 |
for n < 500 and 'approximate' otherwise. |
| 187 |
This option is only useful when the fitted surface is |
| 188 |
interpolated. If surface is 'exact', an exact computation is |
| 189 |
always done for the trace. Setting trace_hat to 'approximate' |
| 190 |
for large dataset will substantially reduce the computation time. |
| 191 |
iterations : int, optional |
| 192 |
Number of iterations of the robust fitting method. If the family |
| 193 |
is 'gaussian', the number of iterations is set to 0. |
| 194 |
cell : float, optional |
| 195 |
Maximum cell size of the kd-tree. Suppose k = floor(n*cell*span), |
| 196 |
where n is the number of observations, and span the smoothing |
| 197 |
parameter. Then, a cell is further divided if the number of |
| 198 |
observations within it is greater than or equal to k. This |
| 199 |
option is only used if the surface is interpolated. |
| 200 |
""" |
| 201 |
cdef c_loess.c_loess_control _base |
| 202 |
cdef bytes _surface |
| 203 |
cdef bytes _statistics |
| 204 |
cdef bytes _trace_hat |
| 205 |
|
| 206 |
def __cinit__(self, *args, **kwargs): |
| 207 |
# Does not allocate memory |
| 208 |
c_loess.loess_control_setup(&self._base) |
| 209 |
|
| 210 |
def __init__(self, surface='interpolate', statistics='approximate', |
| 211 |
trace_hat='wait.to.decide', iterations=4, cell=0.2): |
| 212 |
self.surface = surface |
| 213 |
self.statistics = statistics |
| 214 |
self.trace_hat = trace_hat |
| 215 |
self.iterations = iterations |
| 216 |
self.cell = cell |
| 217 |
|
| 218 |
@property |
| 219 |
def surface(self): |
| 220 |
return self._base.surface.decode('utf-8') |
| 221 |
|
| 222 |
@surface.setter |
| 223 |
def surface(self, value): |
| 224 |
if value not in ('interpolate', 'direct'): |
| 225 |
raise ValueError( |
| 226 |
"Invalid value for the 'surface' argument: " |
| 227 |
"should be in ('interpolate', 'direct').") |
| 228 |
self._surface = value.encode('utf-8') |
| 229 |
self._base.surface = self._surface |
| 230 |
|
| 231 |
@property |
| 232 |
def statistics(self): |
| 233 |
return self._base.statistics.decode('utf-8') |
| 234 |
|
| 235 |
@statistics.setter |
| 236 |
def statistics(self, value): |
| 237 |
if value not in ('approximate', 'exact'): |
| 238 |
raise ValueError( |
| 239 |
"Invalid value for the 'statistics' argument: " |
| 240 |
"should be in ('approximate', 'exact').") |
| 241 |
self._statistics = value.encode('utf-8') |
| 242 |
self._base.statistics = self._statistics |
| 243 |
|
| 244 |
@property |
| 245 |
def trace_hat(self): |
| 246 |
return self._base.trace_hat.decode('utf-8') |
| 247 |
|
| 248 |
@trace_hat.setter |
| 249 |
def trace_hat(self, value): |
| 250 |
if value not in ('wait.to.decide', 'approximate', 'exact'): |
| 251 |
raise ValueError( |
| 252 |
"Invalid value for the 'trace_hat' argument: " |
| 253 |
"should be in ('approximate', 'exact').") |
| 254 |
self._trace_hat = value.encode('utf-8') |
| 255 |
self._base.trace_hat = self._trace_hat |
| 256 |
|
| 257 |
@property |
| 258 |
def iterations(self): |
| 259 |
return self._base.iterations |
| 260 |
|
| 261 |
@iterations.setter |
| 262 |
def iterations(self, value): |
| 263 |
if value < 0: |
| 264 |
raise ValueError( |
| 265 |
"Invalid number of iterations: " |
| 266 |
"should be positive") |
| 267 |
self._base.iterations = value |
| 268 |
|
| 269 |
@property |
| 270 |
def cell(self): |
| 271 |
return self._base.cell |
| 272 |
|
| 273 |
@cell.setter |
| 274 |
def cell(self, value): |
| 275 |
if value <= 0: |
| 276 |
raise ValueError( |
| 277 |
"Invalid value for the cell argument: " |
| 278 |
" should be positive") |
| 279 |
self._base.cell = value |
| 280 |
|
| 281 |
def __str__(self): |
| 282 |
strg = ["Control", |
| 283 |
"-------", |
| 284 |
"Surface type : %s" % self.surface, |
| 285 |
"Statistics : %s" % self.statistics, |
| 286 |
"Trace estimation : %s" % self.trace_hat, |
| 287 |
"Cell size : %s" % self.cell, |
| 288 |
"Nb iterations : %s" % self.iterations,] |
| 289 |
return '\n'.join(strg) |
| 290 |
|
| 291 |
|
| 292 |
cdef class loess_kd_tree: |
| 293 |
cdef c_loess.c_loess_kd_tree _base |
| 294 |
|
| 295 |
def __cinit__(self, n, p): |
| 296 |
c_loess.loess_kd_tree_setup(n, p, &self._base) |
| 297 |
|
| 298 |
def __dealloc__(self): |
| 299 |
c_loess.loess_kd_tree_free(&self._base) |
| 300 |
|
| 301 |
|
| 302 |
cdef class loess_model: |
| 303 |
""" |
| 304 |
Initialization class for loess fitting parameters |
| 305 |
|
| 306 |
Parameters |
| 307 |
---------- |
| 308 |
p : int |
| 309 |
Number of variables |
| 310 |
family : str |
| 311 |
One of ('gaussian', 'symmetric') |
| 312 |
Determines the assumed distribution of the errors. If 'gaussian' |
| 313 |
the fit is performed with least-squares. If 'symmetric' is |
| 314 |
selected, the fit is performed robustly by redescending |
| 315 |
M-estimators. |
| 316 |
span : float |
| 317 |
Smoothing factor, as a fraction of the number of points to take |
| 318 |
into account. Should be in the range (0, 1]. Default is 0.75 |
| 319 |
degree : int |
| 320 |
Overall degree of locally-fitted polynomial. 1 is locally-linear |
| 321 |
fitting and 2 is locally-quadratic fitting. Degree should be 2 at |
| 322 |
most. Default is 2. |
| 323 |
normalize : bool |
| 324 |
Determines whether the independent variables should be normalized. |
| 325 |
If True, the normalization is performed by setting the 10% trimmed |
| 326 |
standard deviation to one. If False, no normalization is carried |
| 327 |
out. This option is only useful for more than one variable. For |
| 328 |
spatial coordinates predictors or variables with a common scale, |
| 329 |
it should be set to False. Default is True. |
| 330 |
parametric : bool | list-of-bools of length p |
| 331 |
Indicates which independent variables should be |
| 332 |
conditionally-parametric (if there are two or more independent |
| 333 |
variables). If a sequence is given, the values should be ordered |
| 334 |
according to the predictor group in x. |
| 335 |
drop_square : bool | list-of-bools of length p |
| 336 |
Which squares to drop. When there are two or more independent |
| 337 |
variables and when a 2nd order polynomial(degree) is used, |
| 338 |
'drop_square' specifies those numeric predictors |
| 339 |
whose squares should be dropped from the set of fitting variables. |
| 340 |
If a sequence is given, the values should be ordered according to |
| 341 |
the predictor group in x. |
| 342 |
""" |
| 343 |
|
| 344 |
cdef c_loess.c_loess_model _base |
| 345 |
cdef p |
| 346 |
cdef bytes _family |
| 347 |
|
| 348 |
def __cinit__(self, *args, **kwargs): |
| 349 |
# Does not allocate memory |
| 350 |
c_loess.loess_model_setup(&self._base) |
| 351 |
|
| 352 |
def __init__(self, p, family='gaussian', span=0.75, |
| 353 |
degree=2, normalize=True, parametric=False, |
| 354 |
drop_square=False): |
| 355 |
self.p = p |
| 356 |
self.family = family |
| 357 |
self.span = span |
| 358 |
self.degree = degree |
| 359 |
self.normalize = normalize |
| 360 |
self.parametric = parametric |
| 361 |
self.drop_square = drop_square |
| 362 |
|
| 363 |
@property |
| 364 |
def normalize(self): |
| 365 |
return bool(self._base.normalize) |
| 366 |
|
| 367 |
@normalize.setter |
| 368 |
def normalize(self, value): |
| 369 |
self._base.normalize = value |
| 370 |
|
| 371 |
@property |
| 372 |
def span(self): |
| 373 |
return self._base.span |
| 374 |
|
| 375 |
@span.setter |
| 376 |
def span(self, value): |
| 377 |
if value <= 0. or value > 1.: |
| 378 |
raise ValueError("Span should be between 0 and 1!") |
| 379 |
self._base.span = value |
| 380 |
|
| 381 |
@property |
| 382 |
def degree(self): |
| 383 |
return self._base.degree |
| 384 |
|
| 385 |
@degree.setter |
| 386 |
def degree(self, value): |
| 387 |
if value < 0 or value > 2: |
| 388 |
raise ValueError("Degree should be be 0, 1 or 2!") |
| 389 |
self._base.degree = value |
| 390 |
|
| 391 |
@property |
| 392 |
def family(self): |
| 393 |
return self._base.family.decode('utf-8') |
| 394 |
|
| 395 |
@family.setter |
| 396 |
def family(self, value): |
| 397 |
if value.lower() not in ('symmetric', 'gaussian'): |
| 398 |
raise ValueError( |
| 399 |
"Invalid value for the 'family' argument: " |
| 400 |
"should be in ('symmetric', 'gaussian').") |
| 401 |
self._family = value.encode('utf-8') |
| 402 |
self._base.family = self._family |
| 403 |
|
| 404 |
@property |
| 405 |
def parametric(self): |
| 406 |
return boolarray_from_data(self.p, 1, self._base.parametric) |
| 407 |
|
| 408 |
@parametric.setter |
| 409 |
def parametric(self, value): |
| 410 |
cdef ndarray p_ndr |
| 411 |
|
| 412 |
if value in (True, False): |
| 413 |
value = [value] * self.p |
| 414 |
elif len(value) != self.p: |
| 415 |
raise ValueError( |
| 416 |
"'parametric' should be a boolean or a list " |
| 417 |
"of booleans with length equal to the number " |
| 418 |
"of independent variables") |
| 419 |
|
| 420 |
p_ndr = np.atleast_1d(np.array(value, copy=False, subok=True, |
| 421 |
dtype=bool)) |
| 422 |
for i in range(self.p): |
| 423 |
self._base.parametric[i] = p_ndr[i] |
| 424 |
|
| 425 |
@property |
| 426 |
def drop_square(self): |
| 427 |
return boolarray_from_data(self.p, 1, self._base.drop_square) |
| 428 |
|
| 429 |
@drop_square.setter |
| 430 |
def drop_square(self, value): |
| 431 |
cdef ndarray d_ndr |
| 432 |
|
| 433 |
if value in (True, False): |
| 434 |
value = [value] * self.p |
| 435 |
elif len(value) != self.p: |
| 436 |
raise ValueError( |
| 437 |
"'drop_square' should be a boolean or a list " |
| 438 |
"of booleans with length equal to the number " |
| 439 |
"of independent variables") |
| 440 |
|
| 441 |
d_ndr = np.atleast_1d(np.array(value, copy=False, |
| 442 |
subok=True, dtype=bool)) |
| 443 |
for i in range(self.p): |
| 444 |
self._base.drop_square[i] = d_ndr[i] |
| 445 |
|
| 446 |
def __repr__(self): |
| 447 |
return "<loess object: model parameters>" |
| 448 |
|
| 449 |
def __str__(self): |
| 450 |
strg = ["Model parameters", |
| 451 |
"----------------", |
| 452 |
"Family : %s" % self.family, |
| 453 |
"Span : %s" % self.span, |
| 454 |
"Degree : %s" % self.degree, |
| 455 |
"Normalized : %s" % self.normalize, |
| 456 |
"Parametric : %s" % self.parametric[:self.p], |
| 457 |
"Drop_square : %s" % self.drop_square[:self.p], |
| 458 |
] |
| 459 |
return '\n'.join(strg) |
| 460 |
|
| 461 |
|
| 462 |
cdef class loess_outputs: |
| 463 |
""" |
| 464 |
Class of a loess fit outputs |
| 465 |
|
| 466 |
This object is automatically created with empty values when a |
| 467 |
new loess object is instantiated. The object gets filled when the |
| 468 |
loess.fit() method is called. |
| 469 |
|
| 470 |
Parameters |
| 471 |
---------- |
| 472 |
n : int |
| 473 |
Number of independent observation |
| 474 |
p : int |
| 475 |
Number of variables |
| 476 |
""" |
| 477 |
cdef c_loess.c_loess_outputs _base |
| 478 |
# private |
| 479 |
cdef readonly family |
| 480 |
cdef readonly n, p |
| 481 |
cdef readonly activated |
| 482 |
|
| 483 |
def __cinit__(self, n, p, family): |
| 484 |
c_loess.loess_outputs_setup(n, p, &self._base) |
| 485 |
|
| 486 |
def __init__(self, n, p, family): |
| 487 |
self.n = n |
| 488 |
self.p = p |
| 489 |
self.family = family |
| 490 |
self.activated = False |
| 491 |
|
| 492 |
def __dealloc__(self): |
| 493 |
c_loess.loess_outputs_free(&self._base) |
| 494 |
|
| 495 |
@property |
| 496 |
def fitted_values(self): |
| 497 |
""" |
| 498 |
:class:`~numpy.ndarray` - Fitted values, shape ``(n,)`` |
| 499 |
""" |
| 500 |
return floatarray_from_data(self.n, 1, self._base.fitted_values) |
| 501 |
|
| 502 |
@property |
| 503 |
def fitted_residuals(self): |
| 504 |
""" |
| 505 |
:class:`~numpy.ndarray` - Fitted residuals, shape ``(n,)``, |
| 506 |
(observations - fitted values) |
| 507 |
""" |
| 508 |
return floatarray_from_data(self.n, 1, self._base.fitted_residuals) |
| 509 |
|
| 510 |
@property |
| 511 |
def pseudovalues(self): |
| 512 |
""" |
| 513 |
:class:`~numpy.ndarray` - Adjusted values of the response |
| 514 |
when robust estimation is used, shape ``(n,)`` |
| 515 |
""" |
| 516 |
if self.family != 'symmetric': |
| 517 |
raise ValueError( |
| 518 |
"pseudovalues are available only when " |
| 519 |
"robust fitting. Use family='symmetric' " |
| 520 |
"for robust fitting") |
| 521 |
return floatarray_from_data(self.n, 1, self._base.pseudovalues) |
| 522 |
|
| 523 |
@property |
| 524 |
def diagonal(self): |
| 525 |
""" |
| 526 |
:class:`~numpy.ndarray` - Diagonal of the operator hat matrix, |
| 527 |
shape ``(n,)`` |
| 528 |
""" |
| 529 |
return floatarray_from_data(self.n, 1, self._base.diagonal) |
| 530 |
|
| 531 |
@property |
| 532 |
def robust(self): |
| 533 |
""" |
| 534 |
:class:`~numpy.ndarray` - Robustness weights for robust fitting, |
| 535 |
shape ``(n,)`` |
| 536 |
""" |
| 537 |
return floatarray_from_data(self.n, 1, self._base.robust) |
| 538 |
|
| 539 |
@property |
| 540 |
def divisor(self): |
| 541 |
""" |
| 542 |
:class:`~numpy.ndarray` - Normalization divisors for numeric |
| 543 |
predictors, shape ``(p,)`` |
| 544 |
""" |
| 545 |
return floatarray_from_data(self.n, 1, self._base.divisor) |
| 546 |
|
| 547 |
@property |
| 548 |
def enp(self): |
| 549 |
""" |
| 550 |
:class:`float` - Equivalent number of parameters |
| 551 |
""" |
| 552 |
return self._base.enp |
| 553 |
|
| 554 |
@property |
| 555 |
def residual_scale(self): |
| 556 |
""" |
| 557 |
:class:`float` - Estimate of the scale of residuals |
| 558 |
""" |
| 559 |
return self._base.residual_scale |
| 560 |
|
| 561 |
@property |
| 562 |
def one_delta(self): |
| 563 |
""" |
| 564 |
:class:`float` - Statistical parameter used in the computation |
| 565 |
of standard errors |
| 566 |
""" |
| 567 |
return self._base.one_delta |
| 568 |
|
| 569 |
@property |
| 570 |
def two_delta(self): |
| 571 |
""" |
| 572 |
:class:`float` - Statistical parameter used in the computation |
| 573 |
of standard errors |
| 574 |
""" |
| 575 |
return self._base.two_delta |
| 576 |
|
| 577 |
@property |
| 578 |
def trace_hat(self): |
| 579 |
""" |
| 580 |
:class:`float` - Trace of the operator hat matrix |
| 581 |
""" |
| 582 |
return self._base.trace_hat |
| 583 |
|
| 584 |
def __str__(self): |
| 585 |
strg = ["Outputs", |
| 586 |
"-------", |
| 587 |
"Fitted values : %s\n" % self.fitted_values, |
| 588 |
"Fitted residuals : %s\n" % self.fitted_residuals, |
| 589 |
"Eqv. nb of parameters : %s" % self.enp, |
| 590 |
"Residual Scale : %s" % self.residual_scale, |
| 591 |
"Deltas : %s - %s" % (self.one_delta, |
| 592 |
self.two_delta), |
| 593 |
"Normalization factors : %s" % self.divisor,] |
| 594 |
return '\n'.join(strg) |
| 595 |
|
| 596 |
|
| 597 |
cdef class loess_confidence_intervals: |
| 598 |
""" |
| 599 |
Pointwise confidence intervals of a loess-predicted object |
| 600 |
|
| 601 |
Parameters |
| 602 |
---------- |
| 603 |
pred : loess_prediction |
| 604 |
Prediction object |
| 605 |
alpha : float |
| 606 |
The alpha level for the confidence interval. |
| 607 |
It must be in the range (0, 1) |
| 608 |
""" |
| 609 |
cdef c_loess.c_confidence_intervals _base |
| 610 |
cdef readonly m |
| 611 |
|
| 612 |
def __cinit__(loess_confidence_intervals self, loess_prediction pred, |
| 613 |
float alpha): |
| 614 |
coverage = 1 - alpha |
| 615 |
if coverage < .5: |
| 616 |
coverage = 1 - coverage |
| 617 |
|
| 618 |
if not 0 < alpha < 1. : |
| 619 |
raise ValueError("The alpha value should be " |
| 620 |
"between 0 and 1.") |
| 621 |
if not pred._base.se: |
| 622 |
raise ValueError("Cannot compute confidence intervals " |
| 623 |
"without standard errors.") |
| 624 |
|
| 625 |
c_loess.c_pointwise(&pred._base, coverage, &self._base) |
| 626 |
self.m = pred.m |
| 627 |
|
| 628 |
def __init__(self, pred, alpha): |
| 629 |
# For documentation |
| 630 |
pass |
| 631 |
|
| 632 |
def __dealloc__(self): |
| 633 |
c_loess.pw_free_mem(&self._base) |
| 634 |
|
| 635 |
@property |
| 636 |
def fit(self): |
| 637 |
""" |
| 638 |
:class:`~numpy.ndarray` - Predicted values |
| 639 |
""" |
| 640 |
return floatarray_from_data(self.m, 1, self._base.fit) |
| 641 |
|
| 642 |
@property |
| 643 |
def upper(self): |
| 644 |
""" |
| 645 |
:class:`~numpy.ndarray` - Upper bounds of the confidence intervals |
| 646 |
""" |
| 647 |
return floatarray_from_data(self.m, 1, self._base.upper) |
| 648 |
|
| 649 |
@property |
| 650 |
def lower(self): |
| 651 |
""" |
| 652 |
:class:`~numpy.ndarray` - Lower bounds of the confidence intervals |
| 653 |
""" |
| 654 |
return floatarray_from_data(self.m, 1, self._base.lower) |
| 655 |
|
| 656 |
|
| 657 |
cdef class loess_prediction: |
| 658 |
""" |
| 659 |
Class for loess prediction results |
| 660 |
|
| 661 |
Holds the predicted values and standard errors of a loess object |
| 662 |
|
| 663 |
Parameters |
| 664 |
---------- |
| 665 |
newdata : ndarray[m, p] |
| 666 |
Independent variables where the surface must be estimated, |
| 667 |
with m the number of new data points, and p the number of |
| 668 |
independent variables. |
| 669 |
loess : loess.loess |
| 670 |
Loess object that has been successfully fitted, |
| 671 |
i.e `loess.fit` has been called and it returned without |
| 672 |
any errors. |
| 673 |
stderror : boolean |
| 674 |
Whether the standard error should be computed |
| 675 |
""" |
| 676 |
|
| 677 |
cdef c_loess.c_prediction _base |
| 678 |
cdef readonly allocated |
| 679 |
|
| 680 |
def __cinit__(self, newdata, loess loess, stderror=False): |
| 681 |
cdef ndarray p_ndr |
| 682 |
cdef double *p_dat |
| 683 |
cdef int se |
| 684 |
|
| 685 |
self.allocated = False |
| 686 |
|
| 687 |
# Note : we need a copy as we may have to normalize |
| 688 |
p_ndr = np.array(newdata, copy=True, subok=True, order='C') |
| 689 |
p_ndr = p_ndr.astype(float) |
| 690 |
|
| 691 |
# Dimensions should match those of the input |
| 692 |
if p_ndr.size == 0 or p_ndr.ndim == 0: |
| 693 |
raise ValueError("Can't predict without input data !") |
| 694 |
|
| 695 |
if p_ndr.ndim > 2: |
| 696 |
raise ValueError("New data has more than 2 dimensions.") |
| 697 |
|
| 698 |
_p = 1 if p_ndr.ndim == 1 else p_ndr.shape[1] |
| 699 |
if _p != loess.inputs.p: |
| 700 |
msg = ("Incompatible data size: there should be as many " |
| 701 |
"columns as parameters. Got %d instead of %d " |
| 702 |
"parameters" % (_p, loess.inputs.p)) |
| 703 |
raise ValueError(msg) |
| 704 |
|
| 705 |
se = 1 if stderror else 0 |
| 706 |
m = len(p_ndr) |
| 707 |
p_ndr = p_ndr.ravel() |
| 708 |
p_dat = <double *>p_ndr.data |
| 709 |
|
| 710 |
c_loess.predict_setup(&self._base, &loess._base, se, m) |
| 711 |
self.allocated = True |
| 712 |
c_loess.c_predict(p_dat, &loess._base, &self._base) |
| 713 |
|
| 714 |
if loess._base.status.err_status: |
| 715 |
raise ValueError(loess._base.status.err_msg) |
| 716 |
|
| 717 |
def __init__(self, newdata, loess, stderror=False): |
| 718 |
# For documentation |
| 719 |
pass |
| 720 |
|
| 721 |
def __dealloc__(self): |
| 722 |
if self.allocated: |
| 723 |
c_loess.predict_free(&self._base) |
| 724 |
|
| 725 |
@property |
| 726 |
def values(self): |
| 727 |
""" |
| 728 |
:class:`~numpy.ndarray` - loess values evaluated at newdata, |
| 729 |
shape ``(m,)`` |
| 730 |
""" |
| 731 |
return floatarray_from_data(self.m, 1, self._base.fit) |
| 732 |
|
| 733 |
@property |
| 734 |
def stderr(self): |
| 735 |
""" |
| 736 |
:class:`~numpy.ndarray` - Estimates of the standard error on |
| 737 |
the estimated values, shape ``(m,)`` |
| 738 |
|
| 739 |
Raises `ValueError` if the standard error was not computed. |
| 740 |
""" |
| 741 |
if not self._base.se: |
| 742 |
raise ValueError("Standard error was not computed." |
| 743 |
"Use 'stderror=True' when predicting.") |
| 744 |
return floatarray_from_data(self.m, 1, self._base.se_fit) |
| 745 |
|
| 746 |
@property |
| 747 |
def residual_scale(self): |
| 748 |
""" |
| 749 |
:class:`float` - Estimate of the scale of the residuals |
| 750 |
""" |
| 751 |
return self._base.residual_scale |
| 752 |
|
| 753 |
@property |
| 754 |
def df(self): |
| 755 |
""" |
| 756 |
:class:`float` - Degrees of freedom of the loess fit. |
| 757 |
|
| 758 |
It is used with the t-distribution to compute pointwise |
| 759 |
confidence intervals for the evaluated surface. It is |
| 760 |
obtained using the formula ``(one_delta ** 2) / two_delta``. |
| 761 |
""" |
| 762 |
return self._base.df |
| 763 |
|
| 764 |
@property |
| 765 |
def m(self): |
| 766 |
""" |
| 767 |
:class:`int` - Number of observations in the new data points |
| 768 |
""" |
| 769 |
return self._base.m |
| 770 |
|
| 771 |
def confidence(self, alpha=0.05): |
| 772 |
""" |
| 773 |
Returns the pointwise confidence intervals |
| 774 |
|
| 775 |
Parameters |
| 776 |
---------- |
| 777 |
alpha : float |
| 778 |
The alpha level for the confidence interval. The |
| 779 |
default ``alpha=0.05`` returns a 95% confidence |
| 780 |
interval. Therefore it must be in the range (0, 1). |
| 781 |
|
| 782 |
Returns |
| 783 |
------- |
| 784 |
out : loess_confidence_intervals |
| 785 |
Confidence intervals object. It has attributes `fit`, |
| 786 |
`lower` and `upper` |
| 787 |
""" |
| 788 |
return loess_confidence_intervals(self, alpha) |
| 789 |
|
| 790 |
def __str__(self): |
| 791 |
try: |
| 792 |
stderr = "Predicted std error : %s\n" % self.stderr |
| 793 |
except ValueError: |
| 794 |
stderr = "" |
| 795 |
|
| 796 |
strg = ["Outputs", |
| 797 |
"-------", |
| 798 |
"Predicted values : %s\n" % self.values, |
| 799 |
stderr, |
| 800 |
"Residual scale : %s" % self.residual_scale, |
| 801 |
"Degrees of freedom : %s" % self.df, |
| 802 |
] |
| 803 |
return '\n'.join(strg) |
| 804 |
|
| 805 |
def _new_loess(init_arguments, fit): |
| 806 |
""" |
| 807 |
Create the loess object from initial arguments |
| 808 |
|
| 809 |
Used for pickling |
| 810 |
""" |
| 811 |
# Generate the object from the initialising arguments |
| 812 |
# Run the fit method if it was run before |
| 813 |
l = loess(**init_arguments) |
| 814 |
if fit: |
| 815 |
l.fit() |
| 816 |
return l |
| 817 |
|
| 818 |
|
| 819 |
cdef class loess: |
| 820 |
""" |
| 821 |
Locally-weighted regression |
| 822 |
|
| 823 |
A loess object is initialized with the combined parameters of |
| 824 |
:class:`loess_inputs`, :class:`loess_model` and |
| 825 |
:class:`loess_control`. The parameters of :class:`loess_inputs` |
| 826 |
i.e ``x``, ``y`` and ``weights`` can be positional in that order. |
| 827 |
In the descriptions below, `n` is the number of observations, |
| 828 |
and `p` is the number of predictor variables. |
| 829 |
|
| 830 |
Parameters |
| 831 |
---------- |
| 832 |
x : ndarray[n, p] |
| 833 |
n independent observations for p no. of variables |
| 834 |
y : ndarray[n,] |
| 835 |
A (n,) ndarray of response observations |
| 836 |
weights : ndarray[n] or None |
| 837 |
Weights to be given to individual observations |
| 838 |
in the sum of squared residuals that forms the local fitting |
| 839 |
criterion. If not None, the weights should be non negative. If |
| 840 |
the different observations have non-equal variances, the weights |
| 841 |
should be inversely proportional to the variances. By default, |
| 842 |
an unweighted fit is carried out (all the weights are one). |
| 843 |
**options : dict |
| 844 |
The parameters of :class:`loess_model` and |
| 845 |
:class:`loess_control`. |
| 846 |
|
| 847 |
Attributes |
| 848 |
---------- |
| 849 |
inputs : :class:`loess_inputs` |
| 850 |
Object that handles the inputs |
| 851 |
model : :class:`loess_model` |
| 852 |
Object that handles the model |
| 853 |
control : :class:`loess_control` |
| 854 |
Object that holds the control parameters |
| 855 |
kd_tree : :class:`loess_kdtree` |
| 856 |
Object that holds the parameters and structures used |
| 857 |
internally by the regression algorithm. |
| 858 |
outputs : :class:`loess_outputs` |
| 859 |
Object that holds the output values and parameters. |
| 860 |
These should be read after :meth:`loess.fit` has been |
| 861 |
called. |
| 862 |
|
| 863 |
Note |
| 864 |
---- |
| 865 |
Loess smoothing creates large state, so pickling a fitted loess |
| 866 |
object does not save the state. It saves the `__init__` parameters |
| 867 |
from which the state is recreated (refitting) when unpickled. So |
| 868 |
pickling and unpickling does not save on computation time. |
| 869 |
""" |
| 870 |
cdef c_loess.c_loess _base |
| 871 |
cdef readonly loess_inputs inputs |
| 872 |
cdef readonly loess_model model |
| 873 |
cdef readonly loess_control control |
| 874 |
cdef readonly loess_kd_tree kd_tree |
| 875 |
cdef readonly loess_outputs outputs |
| 876 |
|
| 877 |
# save all the arguments to enable pickling |
| 878 |
cdef object _init_arguments |
| 879 |
|
| 880 |
def __init__(self, object x, object y, object weights=None, **options): |
| 881 |
self._init_arguments = { |
| 882 |
"x": x, "y": y, "weights": weights, **options |
| 883 |
} |
| 884 |
|
| 885 |
# Process options |
| 886 |
model_options = {} |
| 887 |
control_options= {} |
| 888 |
for (k, v) in options.items(): |
| 889 |
if k in ('family', 'span', 'degree', 'normalize', |
| 890 |
'parametric', 'drop_square',): |
| 891 |
model_options[k] = v |
| 892 |
elif k in ('surface', 'statistics', 'trace_hat', |
| 893 |
'iterations', 'cell'): |
| 894 |
control_options[k] = v |
| 895 |
|
| 896 |
# Initialize the inputs |
| 897 |
self.inputs = loess_inputs(x, y, weights) |
| 898 |
self._base.inputs = &self.inputs._base |
| 899 |
|
| 900 |
n = self.inputs.n |
| 901 |
p = self.inputs.p |
| 902 |
|
| 903 |
# Initialize the control parameters |
| 904 |
self.control = loess_control(**control_options) |
| 905 |
self._base.control = &self.control._base |
| 906 |
|
| 907 |
# Initialize the model parameters |
| 908 |
self.model = loess_model(p, **model_options) |
| 909 |
self._base.model = &self.model._base |
| 910 |
|
| 911 |
# Initialize the outputs |
| 912 |
self.outputs = loess_outputs(n, p, self.model.family) |
| 913 |
self._base.outputs = &self.outputs._base |
| 914 |
|
| 915 |
# Initialize the kd tree |
| 916 |
self.kd_tree = loess_kd_tree(n, p) |
| 917 |
self._base.kd_tree = &self.kd_tree._base |
| 918 |
|
| 919 |
def fit(self): |
| 920 |
""" |
| 921 |
Computes the loess parameters on the current inputs and |
| 922 |
sets of parameters. |
| 923 |
""" |
| 924 |
c_loess.loess_fit(&self._base) |
| 925 |
self.outputs.activated = True |
| 926 |
if self._base.status.err_status: |
| 927 |
raise ValueError(self._base.status.err_msg) |
| 928 |
return |
| 929 |
|
| 930 |
def input_summary(self): |
| 931 |
""" |
| 932 |
Returns some generic information about the loess parameters. |
| 933 |
""" |
| 934 |
toprint = [str(self.model), str(self.control)] |
| 935 |
return "\n\n".join(toprint) |
| 936 |
|
| 937 |
def output_summary(self): |
| 938 |
"""Returns some generic information about the loess fit.""" |
| 939 |
fit_flag = bool(self.outputs.activated) |
| 940 |
|
| 941 |
if self.model.family == "gaussian": |
| 942 |
rse = ("Residual Standard Error : %.4f" % |
| 943 |
self.outputs.residual_scale) |
| 944 |
else: |
| 945 |
rse = ("Residual Scale Estimate : %.4f" % |
| 946 |
self.outputs.residual_scale) |
| 947 |
|
| 948 |
strg = ["Output Summary", |
| 949 |
"--------------", |
| 950 |
"Number of Observations : %d" % self.inputs.n, |
| 951 |
"Fit flag : %d" % fit_flag, |
| 952 |
"Equivalent Number of Parameters: %.1f" % self.outputs.enp, |
| 953 |
rse |
| 954 |
] |
| 955 |
return '\n'.join(strg) |
| 956 |
|
| 957 |
def predict(self, newdata, stderror=False): |
| 958 |
""" |
| 959 |
Compute loess estimates at the given new data points newdata. |
| 960 |
|
| 961 |
Parameters |
| 962 |
---------- |
| 963 |
newdata : ndarray[m, p] |
| 964 |
Independent variables where the surface must be estimated, |
| 965 |
with m the number of new data points, and p the number of |
| 966 |
independent variables. |
| 967 |
stderror : boolean |
| 968 |
Whether the standard error should be computed |
| 969 |
|
| 970 |
Returns |
| 971 |
------- |
| 972 |
A :class:`loess_prediction` object. |
| 973 |
""" |
| 974 |
# Make sure there's been a fit earlier |
| 975 |
if self.outputs.activated == 0: |
| 976 |
self.fit() |
| 977 |
|
| 978 |
return loess_prediction(newdata, self, stderror) |
| 979 |
|
| 980 |
# Pickling support |
| 981 |
@cython.final |
| 982 |
def __reduce__(self): |
| 983 |
return (_new_loess, (self._init_arguments, self.outputs.activated)) |
| 984 |
|
| 985 |
cdef class loess_anova: |
| 986 |
""" |
| 987 |
Analysis of variance for two loess objects |
| 988 |
|
| 989 |
Parameters |
| 990 |
---------- |
| 991 |
loess_one : loess.loess |
| 992 |
First loess object |
| 993 |
loess_two : loess.loess |
| 994 |
Second loess object |
| 995 |
|
| 996 |
Attributes |
| 997 |
---------- |
| 998 |
F_value : float |
| 999 |
Value of the F-statistic |
| 1000 |
Pr_F : float |
| 1001 |
Probability of getting a value as large as the |
| 1002 |
`F_value`. The is the p-value of the F-statistic. |
| 1003 |
""" |
| 1004 |
cdef readonly double dfn, dfd, F_value, Pr_F |
| 1005 |
|
| 1006 |
def __init__(self, loess_one, loess_two): |
| 1007 |
cdef double one_d1, one_d2, one_s, two_d1, two_d2, two_s |
| 1008 |
cdef double rssdiff, d1diff, tmp, df1, df2 |
| 1009 |
|
| 1010 |
if (not isinstance(loess_one, loess) or |
| 1011 |
not isinstance(loess_two, loess)): |
| 1012 |
raise ValueError("Arguments should be valid loess objects!" |
| 1013 |
"got '%s' instead" % type(loess_one)) |
| 1014 |
|
| 1015 |
out_one = loess_one.outputs |
| 1016 |
out_two = loess_two.outputs |
| 1017 |
|
| 1018 |
one_d1 = out_one.one_delta |
| 1019 |
one_d2 = out_one.two_delta |
| 1020 |
one_s = out_one.residual_scale |
| 1021 |
|
| 1022 |
two_d1 = out_two.one_delta |
| 1023 |
two_d2 = out_two.two_delta |
| 1024 |
two_s = out_two.residual_scale |
| 1025 |
|
| 1026 |
rssdiff = abs(one_s * one_s * one_d1 - two_s * two_s * two_d1) |
| 1027 |
d1diff = abs(one_d1 - two_d1) |
| 1028 |
self.dfn = d1diff * d1diff / abs(one_d2 - two_d2) |
| 1029 |
df1 = self.dfn |
| 1030 |
|
| 1031 |
if out_one.enp > out_two.enp: |
| 1032 |
self.dfd = one_d1 * one_d1 / one_d2 |
| 1033 |
tmp = one_s |
| 1034 |
else: |
| 1035 |
self.dfd = two_d1 * two_d1 / two_d2 |
| 1036 |
tmp = two_s |
| 1037 |
df2 = self.dfd |
| 1038 |
self.F_value = (rssdiff / d1diff) / (tmp * tmp) |
| 1039 |
self.Pr_F = 1. - c_loess.pf(self.F_value, df1, df2) |