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