1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
|
# Authors: Mathieu Blondel
# Olivier Grisel
# Peter Prettenhofer
# Lars Buitinck
# Giorgio Patrini
#
# License: BSD 3 clause
#!python
from libc.math cimport fabs, sqrt
cimport numpy as cnp
import numpy as np
from cython cimport floating
from numpy.math cimport isnan
cnp.import_array()
ctypedef fused integral:
int
long long
ctypedef cnp.float64_t DOUBLE
def csr_row_norms(X):
"""L2 norm of each row in CSR matrix X."""
if X.dtype not in [np.float32, np.float64]:
X = X.astype(np.float64)
return _csr_row_norms(X.data, X.shape, X.indices, X.indptr)
def _csr_row_norms(cnp.ndarray[floating, ndim=1, mode="c"] X_data,
shape,
cnp.ndarray[integral, ndim=1, mode="c"] X_indices,
cnp.ndarray[integral, ndim=1, mode="c"] X_indptr):
cdef:
unsigned long long n_samples = shape[0]
unsigned long long i
integral j
double sum_
norms = np.empty(n_samples, dtype=X_data.dtype)
cdef floating[::1] norms_view = norms
for i in range(n_samples):
sum_ = 0.0
for j in range(X_indptr[i], X_indptr[i + 1]):
sum_ += X_data[j] * X_data[j]
norms_view[i] = sum_
return norms
def csr_mean_variance_axis0(X, weights=None, return_sum_weights=False):
"""Compute mean and variance along axis 0 on a CSR matrix
Uses a np.float64 accumulator.
Parameters
----------
X : CSR sparse matrix, shape (n_samples, n_features)
Input data.
weights : ndarray of shape (n_samples,), dtype=floating, default=None
If it is set to None samples will be equally weighted.
.. versionadded:: 0.24
return_sum_weights : bool, default=False
If True, returns the sum of weights seen for each feature.
.. versionadded:: 0.24
Returns
-------
means : float array with shape (n_features,)
Feature-wise means
variances : float array with shape (n_features,)
Feature-wise variances
sum_weights : ndarray of shape (n_features,), dtype=floating
Returned if return_sum_weights is True.
"""
if X.dtype not in [np.float32, np.float64]:
X = X.astype(np.float64)
if weights is None:
weights = np.ones(X.shape[0], dtype=X.dtype)
means, variances, sum_weights = _csr_mean_variance_axis0(
X.data, X.shape[0], X.shape[1], X.indices, X.indptr, weights)
if return_sum_weights:
return means, variances, sum_weights
return means, variances
def _csr_mean_variance_axis0(cnp.ndarray[floating, ndim=1, mode="c"] X_data,
unsigned long long n_samples,
unsigned long long n_features,
cnp.ndarray[integral, ndim=1] X_indices,
cnp.ndarray[integral, ndim=1] X_indptr,
cnp.ndarray[floating, ndim=1] weights):
# Implement the function here since variables using fused types
# cannot be declared directly and can only be passed as function arguments
cdef:
cnp.npy_intp i
unsigned long long row_ind
integral col_ind
cnp.float64_t diff
# means[j] contains the mean of feature j
cnp.ndarray[cnp.float64_t, ndim=1] means = np.zeros(n_features)
# variances[j] contains the variance of feature j
cnp.ndarray[cnp.float64_t, ndim=1] variances = np.zeros(n_features)
cnp.ndarray[cnp.float64_t, ndim=1] sum_weights = np.full(
fill_value=np.sum(weights, dtype=np.float64), shape=n_features)
cnp.ndarray[cnp.float64_t, ndim=1] sum_weights_nz = np.zeros(
shape=n_features)
cnp.ndarray[cnp.float64_t, ndim=1] correction = np.zeros(
shape=n_features)
cnp.ndarray[cnp.uint64_t, ndim=1] counts = np.full(
fill_value=weights.shape[0], shape=n_features, dtype=np.uint64)
cnp.ndarray[cnp.uint64_t, ndim=1] counts_nz = np.zeros(
shape=n_features, dtype=np.uint64)
for row_ind in range(len(X_indptr) - 1):
for i in range(X_indptr[row_ind], X_indptr[row_ind + 1]):
col_ind = X_indices[i]
if not isnan(X_data[i]):
means[col_ind] += <cnp.float64_t>(X_data[i]) * weights[row_ind]
# sum of weights where X[:, col_ind] is non-zero
sum_weights_nz[col_ind] += weights[row_ind]
# number of non-zero elements of X[:, col_ind]
counts_nz[col_ind] += 1
else:
# sum of weights where X[:, col_ind] is not nan
sum_weights[col_ind] -= weights[row_ind]
# number of non nan elements of X[:, col_ind]
counts[col_ind] -= 1
for i in range(n_features):
means[i] /= sum_weights[i]
for row_ind in range(len(X_indptr) - 1):
for i in range(X_indptr[row_ind], X_indptr[row_ind + 1]):
col_ind = X_indices[i]
if not isnan(X_data[i]):
diff = X_data[i] - means[col_ind]
# correction term of the corrected 2 pass algorithm.
# See "Algorithms for computing the sample variance: analysis
# and recommendations", by Chan, Golub, and LeVeque.
correction[col_ind] += diff * weights[row_ind]
variances[col_ind] += diff * diff * weights[row_ind]
for i in range(n_features):
if counts[i] != counts_nz[i]:
correction[i] -= (sum_weights[i] - sum_weights_nz[i]) * means[i]
correction[i] = correction[i]**2 / sum_weights[i]
if counts[i] != counts_nz[i]:
# only compute it when it's guaranteed to be non-zero to avoid
# catastrophic cancellation.
variances[i] += (sum_weights[i] - sum_weights_nz[i]) * means[i]**2
variances[i] = (variances[i] - correction[i]) / sum_weights[i]
if floating is float:
return (np.array(means, dtype=np.float32),
np.array(variances, dtype=np.float32),
np.array(sum_weights, dtype=np.float32))
else:
return means, variances, sum_weights
def csc_mean_variance_axis0(X, weights=None, return_sum_weights=False):
"""Compute mean and variance along axis 0 on a CSC matrix
Uses a np.float64 accumulator.
Parameters
----------
X : CSC sparse matrix, shape (n_samples, n_features)
Input data.
weights : ndarray of shape (n_samples,), dtype=floating, default=None
If it is set to None samples will be equally weighted.
.. versionadded:: 0.24
return_sum_weights : bool, default=False
If True, returns the sum of weights seen for each feature.
.. versionadded:: 0.24
Returns
-------
means : float array with shape (n_features,)
Feature-wise means
variances : float array with shape (n_features,)
Feature-wise variances
sum_weights : ndarray of shape (n_features,), dtype=floating
Returned if return_sum_weights is True.
"""
if X.dtype not in [np.float32, np.float64]:
X = X.astype(np.float64)
if weights is None:
weights = np.ones(X.shape[0], dtype=X.dtype)
means, variances, sum_weights = _csc_mean_variance_axis0(
X.data, X.shape[0], X.shape[1], X.indices, X.indptr, weights)
if return_sum_weights:
return means, variances, sum_weights
return means, variances
def _csc_mean_variance_axis0(cnp.ndarray[floating, ndim=1, mode="c"] X_data,
unsigned long long n_samples,
unsigned long long n_features,
cnp.ndarray[integral, ndim=1] X_indices,
cnp.ndarray[integral, ndim=1] X_indptr,
cnp.ndarray[floating, ndim=1] weights):
# Implement the function here since variables using fused types
# cannot be declared directly and can only be passed as function arguments
cdef:
cnp.npy_intp i
unsigned long long col_ind
integral row_ind
cnp.float64_t diff
# means[j] contains the mean of feature j
cnp.ndarray[cnp.float64_t, ndim=1] means = np.zeros(n_features)
# variances[j] contains the variance of feature j
cnp.ndarray[cnp.float64_t, ndim=1] variances = np.zeros(n_features)
cnp.ndarray[cnp.float64_t, ndim=1] sum_weights = np.full(
fill_value=np.sum(weights, dtype=np.float64), shape=n_features)
cnp.ndarray[cnp.float64_t, ndim=1] sum_weights_nz = np.zeros(
shape=n_features)
cnp.ndarray[cnp.float64_t, ndim=1] correction = np.zeros(
shape=n_features)
cnp.ndarray[cnp.uint64_t, ndim=1] counts = np.full(
fill_value=weights.shape[0], shape=n_features, dtype=np.uint64)
cnp.ndarray[cnp.uint64_t, ndim=1] counts_nz = np.zeros(
shape=n_features, dtype=np.uint64)
for col_ind in range(n_features):
for i in range(X_indptr[col_ind], X_indptr[col_ind + 1]):
row_ind = X_indices[i]
if not isnan(X_data[i]):
means[col_ind] += <cnp.float64_t>(X_data[i]) * weights[row_ind]
# sum of weights where X[:, col_ind] is non-zero
sum_weights_nz[col_ind] += weights[row_ind]
# number of non-zero elements of X[:, col_ind]
counts_nz[col_ind] += 1
else:
# sum of weights where X[:, col_ind] is not nan
sum_weights[col_ind] -= weights[row_ind]
# number of non nan elements of X[:, col_ind]
counts[col_ind] -= 1
for i in range(n_features):
means[i] /= sum_weights[i]
for col_ind in range(n_features):
for i in range(X_indptr[col_ind], X_indptr[col_ind + 1]):
row_ind = X_indices[i]
if not isnan(X_data[i]):
diff = X_data[i] - means[col_ind]
# correction term of the corrected 2 pass algorithm.
# See "Algorithms for computing the sample variance: analysis
# and recommendations", by Chan, Golub, and LeVeque.
correction[col_ind] += diff * weights[row_ind]
variances[col_ind] += diff * diff * weights[row_ind]
for i in range(n_features):
if counts[i] != counts_nz[i]:
correction[i] -= (sum_weights[i] - sum_weights_nz[i]) * means[i]
correction[i] = correction[i]**2 / sum_weights[i]
if counts[i] != counts_nz[i]:
# only compute it when it's guaranteed to be non-zero to avoid
# catastrophic cancellation.
variances[i] += (sum_weights[i] - sum_weights_nz[i]) * means[i]**2
variances[i] = (variances[i] - correction[i]) / sum_weights[i]
if floating is float:
return (np.array(means, dtype=np.float32),
np.array(variances, dtype=np.float32),
np.array(sum_weights, dtype=np.float32))
else:
return means, variances, sum_weights
def incr_mean_variance_axis0(X, last_mean, last_var, last_n, weights=None):
"""Compute mean and variance along axis 0 on a CSR or CSC matrix.
last_mean, last_var are the statistics computed at the last step by this
function. Both must be initialized to 0.0. last_n is the
number of samples encountered until now and is initialized at 0.
Parameters
----------
X : CSR or CSC sparse matrix, shape (n_samples, n_features)
Input data.
last_mean : float array with shape (n_features,)
Array of feature-wise means to update with the new data X.
last_var : float array with shape (n_features,)
Array of feature-wise var to update with the new data X.
last_n : float array with shape (n_features,)
Sum of the weights seen so far (if weights are all set to 1
this will be the same as number of samples seen so far, before X).
weights : float array with shape (n_samples,) or None. If it is set
to None samples will be equally weighted.
Returns
-------
updated_mean : float array with shape (n_features,)
Feature-wise means
updated_variance : float array with shape (n_features,)
Feature-wise variances
updated_n : int array with shape (n_features,)
Updated number of samples seen
Notes
-----
NaNs are ignored during the computation.
References
----------
T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample
variance: recommendations, The American Statistician, Vol. 37, No. 3,
pp. 242-247
Also, see the non-sparse implementation of this in
`utils.extmath._batch_mean_variance_update`.
"""
if X.dtype not in [np.float32, np.float64]:
X = X.astype(np.float64)
X_dtype = X.dtype
if weights is None:
weights = np.ones(X.shape[0], dtype=X_dtype)
elif weights.dtype not in [np.float32, np.float64]:
weights = weights.astype(np.float64, copy=False)
if last_n.dtype not in [np.float32, np.float64]:
last_n = last_n.astype(np.float64, copy=False)
return _incr_mean_variance_axis0(X.data,
np.sum(weights),
X.shape[1],
X.indices,
X.indptr,
X.format,
last_mean.astype(X_dtype, copy=False),
last_var.astype(X_dtype, copy=False),
last_n.astype(X_dtype, copy=False),
weights.astype(X_dtype, copy=False))
def _incr_mean_variance_axis0(cnp.ndarray[floating, ndim=1] X_data,
floating n_samples,
unsigned long long n_features,
cnp.ndarray[int, ndim=1] X_indices,
# X_indptr might be either in32 or int64
cnp.ndarray[integral, ndim=1] X_indptr,
str X_format,
cnp.ndarray[floating, ndim=1] last_mean,
cnp.ndarray[floating, ndim=1] last_var,
cnp.ndarray[floating, ndim=1] last_n,
# previous sum of the weights (ie float)
cnp.ndarray[floating, ndim=1] weights):
# Implement the function here since variables using fused types
# cannot be declared directly and can only be passed as function arguments
cdef:
cnp.npy_intp i
# last = stats until now
# new = the current increment
# updated = the aggregated stats
# when arrays, they are indexed by i per-feature
cdef:
cnp.ndarray[floating, ndim=1] new_mean
cnp.ndarray[floating, ndim=1] new_var
cnp.ndarray[floating, ndim=1] updated_mean
cnp.ndarray[floating, ndim=1] updated_var
if floating is float:
dtype = np.float32
else:
dtype = np.float64
new_mean = np.zeros(n_features, dtype=dtype)
new_var = np.zeros_like(new_mean, dtype=dtype)
updated_mean = np.zeros_like(new_mean, dtype=dtype)
updated_var = np.zeros_like(new_mean, dtype=dtype)
cdef:
cnp.ndarray[floating, ndim=1] new_n
cnp.ndarray[floating, ndim=1] updated_n
cnp.ndarray[floating, ndim=1] last_over_new_n
# Obtain new stats first
updated_n = np.zeros(shape=n_features, dtype=dtype)
last_over_new_n = np.zeros_like(updated_n, dtype=dtype)
# X can be a CSR or CSC matrix
if X_format == 'csr':
new_mean, new_var, new_n = _csr_mean_variance_axis0(
X_data, n_samples, n_features, X_indices, X_indptr, weights)
else: # X_format == 'csc'
new_mean, new_var, new_n = _csc_mean_variance_axis0(
X_data, n_samples, n_features, X_indices, X_indptr, weights)
# First pass
cdef bint is_first_pass = True
for i in range(n_features):
if last_n[i] > 0:
is_first_pass = False
break
if is_first_pass:
return new_mean, new_var, new_n
for i in range(n_features):
updated_n[i] = last_n[i] + new_n[i]
# Next passes
for i in range(n_features):
if new_n[i] > 0:
last_over_new_n[i] = dtype(last_n[i]) / dtype(new_n[i])
# Unnormalized stats
last_mean[i] *= last_n[i]
last_var[i] *= last_n[i]
new_mean[i] *= new_n[i]
new_var[i] *= new_n[i]
# Update stats
updated_var[i] = (
last_var[i] + new_var[i] +
last_over_new_n[i] / updated_n[i] *
(last_mean[i] / last_over_new_n[i] - new_mean[i])**2
)
updated_mean[i] = (last_mean[i] + new_mean[i]) / updated_n[i]
updated_var[i] /= updated_n[i]
else:
updated_var[i] = last_var[i]
updated_mean[i] = last_mean[i]
updated_n[i] = last_n[i]
return updated_mean, updated_var, updated_n
def inplace_csr_row_normalize_l1(X):
"""Inplace row normalize using the l1 norm"""
_inplace_csr_row_normalize_l1(X.data, X.shape, X.indices, X.indptr)
def _inplace_csr_row_normalize_l1(cnp.ndarray[floating, ndim=1] X_data,
shape,
cnp.ndarray[integral, ndim=1] X_indices,
cnp.ndarray[integral, ndim=1] X_indptr):
cdef unsigned long long n_samples = shape[0]
cdef unsigned long long n_features = shape[1]
# the column indices for row i are stored in:
# indices[indptr[i]:indices[i+1]]
# and their corresponding values are stored in:
# data[indptr[i]:indptr[i+1]]
cdef cnp.npy_intp i, j
cdef double sum_
for i in range(n_samples):
sum_ = 0.0
for j in range(X_indptr[i], X_indptr[i + 1]):
sum_ += fabs(X_data[j])
if sum_ == 0.0:
# do not normalize empty rows (can happen if CSR is not pruned
# correctly)
continue
for j in range(X_indptr[i], X_indptr[i + 1]):
X_data[j] /= sum_
def inplace_csr_row_normalize_l2(X):
"""Inplace row normalize using the l2 norm"""
_inplace_csr_row_normalize_l2(X.data, X.shape, X.indices, X.indptr)
def _inplace_csr_row_normalize_l2(cnp.ndarray[floating, ndim=1] X_data,
shape,
cnp.ndarray[integral, ndim=1] X_indices,
cnp.ndarray[integral, ndim=1] X_indptr):
cdef integral n_samples = shape[0]
cdef integral n_features = shape[1]
cdef cnp.npy_intp i, j
cdef double sum_
for i in range(n_samples):
sum_ = 0.0
for j in range(X_indptr[i], X_indptr[i + 1]):
sum_ += (X_data[j] * X_data[j])
if sum_ == 0.0:
# do not normalize empty rows (can happen if CSR is not pruned
# correctly)
continue
sum_ = sqrt(sum_)
for j in range(X_indptr[i], X_indptr[i + 1]):
X_data[j] /= sum_
def assign_rows_csr(X,
cnp.ndarray[cnp.npy_intp, ndim=1] X_rows,
cnp.ndarray[cnp.npy_intp, ndim=1] out_rows,
cnp.ndarray[floating, ndim=2, mode="c"] out):
"""Densify selected rows of a CSR matrix into a preallocated array.
Like out[out_rows] = X[X_rows].toarray() but without copying.
No-copy supported for both dtype=np.float32 and dtype=np.float64.
Parameters
----------
X : scipy.sparse.csr_matrix, shape=(n_samples, n_features)
X_rows : array, dtype=np.intp, shape=n_rows
out_rows : array, dtype=np.intp, shape=n_rows
out : array, shape=(arbitrary, n_features)
"""
cdef:
# npy_intp (np.intp in Python) is what np.where returns,
# but int is what scipy.sparse uses.
int i, ind, j
cnp.npy_intp rX
cnp.ndarray[floating, ndim=1] data = X.data
cnp.ndarray[int, ndim=1] indices = X.indices, indptr = X.indptr
if X_rows.shape[0] != out_rows.shape[0]:
raise ValueError("cannot assign %d rows to %d"
% (X_rows.shape[0], out_rows.shape[0]))
out[out_rows] = 0.
for i in range(X_rows.shape[0]):
rX = X_rows[i]
for ind in range(indptr[rX], indptr[rX + 1]):
j = indices[ind]
out[out_rows[i], j] = data[ind]
|