2011-11-30 18:05:10 +08:00
|
|
|
"""
|
|
|
|
|
The :mod:`sklearn.utils` module includes various utilites.
|
|
|
|
|
"""
|
|
|
|
|
|
2011-01-20 20:47:30 +08:00
|
|
|
import numpy as np
|
2012-08-15 06:33:41 +08:00
|
|
|
from scipy.sparse import issparse
|
2011-07-24 03:10:06 +08:00
|
|
|
import warnings
|
2011-01-20 20:47:30 +08:00
|
|
|
|
2011-12-24 04:27:46 +08:00
|
|
|
from .validation import *
|
2012-01-17 09:30:59 +08:00
|
|
|
from .murmurhash import murmurhash3_32
|
2011-08-24 00:28:29 +08:00
|
|
|
|
2012-04-23 00:18:32 +08:00
|
|
|
# Make sure that DeprecationWarning get printed
|
|
|
|
|
warnings.simplefilter("always", DeprecationWarning)
|
2011-08-24 00:28:29 +08:00
|
|
|
|
2012-04-24 03:22:27 +08:00
|
|
|
|
2011-07-24 03:10:06 +08:00
|
|
|
class deprecated(object):
|
2011-07-27 02:59:26 +08:00
|
|
|
"""Decorator to mark a function or class as deprecated.
|
2011-07-24 03:10:06 +08:00
|
|
|
|
2011-09-20 05:32:57 +08:00
|
|
|
Issue a warning when the function is called/the class is instantiated and
|
2011-07-27 02:59:26 +08:00
|
|
|
adds a warning to the docstring.
|
2011-07-24 03:10:06 +08:00
|
|
|
|
|
|
|
|
The optional extra argument will be appended to the deprecation message
|
|
|
|
|
and the docstring. Note: to use this with the default value for extra, put
|
|
|
|
|
in an empty of parentheses:
|
|
|
|
|
|
2011-09-02 17:00:02 +08:00
|
|
|
>>> from sklearn.utils import deprecated
|
2011-09-20 05:22:03 +08:00
|
|
|
>>> deprecated() # doctest: +ELLIPSIS
|
|
|
|
|
<sklearn.utils.deprecated object at ...>
|
|
|
|
|
|
2011-07-24 03:10:06 +08:00
|
|
|
>>> @deprecated()
|
|
|
|
|
... def some_function(): pass
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
# Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,
|
|
|
|
|
# but with many changes.
|
|
|
|
|
|
|
|
|
|
def __init__(self, extra=''):
|
2012-02-23 02:33:36 +08:00
|
|
|
"""
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
extra: string
|
|
|
|
|
to be added to the deprecation messages
|
|
|
|
|
|
|
|
|
|
"""
|
2011-07-24 03:10:06 +08:00
|
|
|
self.extra = extra
|
|
|
|
|
|
2011-07-27 02:59:26 +08:00
|
|
|
def __call__(self, obj):
|
|
|
|
|
if isinstance(obj, type):
|
|
|
|
|
return self._decorate_class(obj)
|
|
|
|
|
else:
|
|
|
|
|
return self._decorate_fun(obj)
|
|
|
|
|
|
|
|
|
|
def _decorate_class(self, cls):
|
2011-07-27 03:29:02 +08:00
|
|
|
msg = "Class %s is deprecated" % cls.__name__
|
2011-07-27 02:59:26 +08:00
|
|
|
if self.extra:
|
|
|
|
|
msg += "; %s" % self.extra
|
|
|
|
|
|
|
|
|
|
# FIXME: we should probably reset __new__ for full generality
|
|
|
|
|
init = cls.__init__
|
2011-09-20 21:37:23 +08:00
|
|
|
|
2011-07-27 02:59:26 +08:00
|
|
|
def wrapped(*args, **kwargs):
|
|
|
|
|
warnings.warn(msg, category=DeprecationWarning)
|
|
|
|
|
return init(*args, **kwargs)
|
|
|
|
|
cls.__init__ = wrapped
|
|
|
|
|
|
|
|
|
|
wrapped.__name__ = '__init__'
|
|
|
|
|
wrapped.__doc__ = self._update_doc(init.__doc__)
|
2011-09-07 16:56:20 +08:00
|
|
|
wrapped.deprecated_original = init
|
2011-07-27 02:59:26 +08:00
|
|
|
|
|
|
|
|
return cls
|
|
|
|
|
|
|
|
|
|
def _decorate_fun(self, fun):
|
2011-07-24 03:10:06 +08:00
|
|
|
"""Decorate function fun"""
|
|
|
|
|
|
2011-12-11 07:55:39 +08:00
|
|
|
msg = "Function %s is deprecated" % fun.__name__
|
2011-07-24 03:10:06 +08:00
|
|
|
if self.extra:
|
|
|
|
|
msg += "; %s" % self.extra
|
|
|
|
|
|
|
|
|
|
def wrapped(*args, **kwargs):
|
|
|
|
|
warnings.warn(msg, category=DeprecationWarning)
|
|
|
|
|
return fun(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
wrapped.__name__ = fun.__name__
|
|
|
|
|
wrapped.__dict__ = fun.__dict__
|
2011-07-27 02:59:26 +08:00
|
|
|
wrapped.__doc__ = self._update_doc(fun.__doc__)
|
2011-07-24 03:10:06 +08:00
|
|
|
|
2011-07-27 02:59:26 +08:00
|
|
|
return wrapped
|
|
|
|
|
|
|
|
|
|
def _update_doc(self, olddoc):
|
2011-07-24 03:10:06 +08:00
|
|
|
newdoc = "DEPRECATED"
|
|
|
|
|
if self.extra:
|
|
|
|
|
newdoc = "%s: %s" % (newdoc, self.extra)
|
|
|
|
|
if olddoc:
|
|
|
|
|
newdoc = "%s\n\n%s" % (newdoc, olddoc)
|
2011-07-27 02:59:26 +08:00
|
|
|
return newdoc
|
2011-07-24 03:10:06 +08:00
|
|
|
|
|
|
|
|
|
2012-01-13 14:31:45 +08:00
|
|
|
def safe_mask(X, mask):
|
2012-01-13 18:28:55 +08:00
|
|
|
"""Return a mask which is safe to use on X.
|
2012-01-13 14:31:45 +08:00
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2012-09-18 17:13:33 +08:00
|
|
|
X : {array-like, sparse matrix}
|
|
|
|
|
Data on which to apply mask.
|
2012-01-13 14:31:45 +08:00
|
|
|
|
2012-09-18 17:13:33 +08:00
|
|
|
mask: array
|
|
|
|
|
Mask to be used on X.
|
2012-01-13 14:31:45 +08:00
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
mask
|
|
|
|
|
"""
|
|
|
|
|
mask = np.asanyarray(mask)
|
2012-08-27 19:35:17 +08:00
|
|
|
if np.issubdtype(mask.dtype, np.int):
|
|
|
|
|
return mask
|
|
|
|
|
|
2012-01-13 14:31:45 +08:00
|
|
|
if hasattr(X, "toarray"):
|
|
|
|
|
ind = np.arange(mask.shape[0])
|
|
|
|
|
mask = ind[mask]
|
|
|
|
|
return mask
|
|
|
|
|
|
|
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
def resample(*arrays, **options):
|
2011-05-21 20:46:16 +08:00
|
|
|
"""Resample arrays or sparse matrices in a consistent way
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
The default strategy implements one step of the bootstrapping
|
|
|
|
|
procedure.
|
|
|
|
|
|
2011-05-17 15:49:05 +08:00
|
|
|
Parameters
|
|
|
|
|
----------
|
2011-12-21 23:11:16 +08:00
|
|
|
`*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0]
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
replace : boolean, True by default
|
|
|
|
|
Implements resampling with replacement. If False, this will implement
|
|
|
|
|
(sliced) random permutations.
|
|
|
|
|
|
|
|
|
|
n_samples : int, None by default
|
|
|
|
|
Number of samples to generate. If left to None this is
|
|
|
|
|
automatically set to the first dimension of the arrays.
|
|
|
|
|
|
2011-05-17 15:49:05 +08:00
|
|
|
random_state : int or RandomState instance
|
|
|
|
|
Control the shuffling for reproducible behavior.
|
|
|
|
|
|
2011-12-23 02:34:33 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2011-05-21 20:32:43 +08:00
|
|
|
Sequence of resampled views of the collections. The original arrays are
|
2011-05-18 08:15:50 +08:00
|
|
|
not impacted.
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-12-23 02:47:49 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
2011-05-17 15:49:05 +08:00
|
|
|
It is possible to mix sparse and dense arrays in the same run::
|
|
|
|
|
|
|
|
|
|
>>> X = [[1., 0.], [2., 1.], [0., 0.]]
|
|
|
|
|
>>> y = np.array([0, 1, 2])
|
|
|
|
|
|
|
|
|
|
>>> from scipy.sparse import coo_matrix
|
|
|
|
|
>>> X_sparse = coo_matrix(X)
|
|
|
|
|
|
2011-09-02 17:00:02 +08:00
|
|
|
>>> from sklearn.utils import resample
|
2011-05-21 20:32:43 +08:00
|
|
|
>>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0)
|
2011-05-17 15:49:05 +08:00
|
|
|
>>> X
|
2011-05-21 20:32:43 +08:00
|
|
|
array([[ 1., 0.],
|
2011-05-17 15:49:05 +08:00
|
|
|
[ 2., 1.],
|
|
|
|
|
[ 1., 0.]])
|
|
|
|
|
|
2012-03-13 03:57:32 +08:00
|
|
|
>>> X_sparse # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
|
|
|
|
<3x2 sparse matrix of type '<... 'numpy.float64'>'
|
2011-05-21 20:32:43 +08:00
|
|
|
with 4 stored elements in Compressed Sparse Row format>
|
2011-05-17 15:49:05 +08:00
|
|
|
|
|
|
|
|
>>> X_sparse.toarray()
|
2011-05-21 20:32:43 +08:00
|
|
|
array([[ 1., 0.],
|
2011-05-17 15:49:05 +08:00
|
|
|
[ 2., 1.],
|
|
|
|
|
[ 1., 0.]])
|
|
|
|
|
|
|
|
|
|
>>> y
|
2011-05-21 20:32:43 +08:00
|
|
|
array([0, 1, 0])
|
|
|
|
|
|
|
|
|
|
>>> resample(y, n_samples=2, random_state=0)
|
|
|
|
|
array([0, 1])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
See also
|
|
|
|
|
--------
|
2011-09-06 20:44:32 +08:00
|
|
|
:class:`sklearn.cross_validation.Bootstrap`
|
2011-09-02 17:00:02 +08:00
|
|
|
:func:`sklearn.utils.shuffle`
|
2011-05-17 15:49:05 +08:00
|
|
|
"""
|
2011-05-18 00:44:01 +08:00
|
|
|
random_state = check_random_state(options.pop('random_state', None))
|
2011-05-21 20:32:43 +08:00
|
|
|
replace = options.pop('replace', True)
|
|
|
|
|
max_n_samples = options.pop('n_samples', None)
|
2011-05-18 00:44:01 +08:00
|
|
|
if options:
|
|
|
|
|
raise ValueError("Unexpected kw arguments: %r" % options.keys())
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-05-18 00:44:01 +08:00
|
|
|
if len(arrays) == 0:
|
2011-05-18 08:15:50 +08:00
|
|
|
return None
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-05-18 00:44:01 +08:00
|
|
|
first = arrays[0]
|
2011-05-17 15:49:05 +08:00
|
|
|
n_samples = first.shape[0] if hasattr(first, 'shape') else len(first)
|
|
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
if max_n_samples is None:
|
|
|
|
|
max_n_samples = n_samples
|
|
|
|
|
|
|
|
|
|
if max_n_samples > n_samples:
|
|
|
|
|
raise ValueError("Cannot sample %d out of arrays with dim %d" % (
|
|
|
|
|
max_n_samples, n_samples))
|
|
|
|
|
|
2011-12-09 00:41:49 +08:00
|
|
|
arrays = check_arrays(*arrays, sparse_format='csr')
|
2011-05-22 06:29:51 +08:00
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
if replace:
|
|
|
|
|
indices = random_state.randint(0, n_samples, size=(max_n_samples,))
|
|
|
|
|
else:
|
2011-05-21 20:46:16 +08:00
|
|
|
indices = np.arange(n_samples)
|
2011-05-21 20:32:43 +08:00
|
|
|
random_state.shuffle(indices)
|
2011-05-21 20:46:16 +08:00
|
|
|
indices = indices[:max_n_samples]
|
2011-05-21 20:32:43 +08:00
|
|
|
|
|
|
|
|
resampled_arrays = []
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-05-18 00:44:01 +08:00
|
|
|
for array in arrays:
|
|
|
|
|
array = array[indices]
|
2011-05-21 20:32:43 +08:00
|
|
|
resampled_arrays.append(array)
|
2011-05-17 15:49:05 +08:00
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
if len(resampled_arrays) == 1:
|
2011-05-18 08:15:50 +08:00
|
|
|
# syntactic sugar for the unit argument case
|
2011-05-21 20:32:43 +08:00
|
|
|
return resampled_arrays[0]
|
2011-05-18 08:15:50 +08:00
|
|
|
else:
|
2011-05-21 20:32:43 +08:00
|
|
|
return resampled_arrays
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def shuffle(*arrays, **options):
|
|
|
|
|
"""Shuffle arrays or sparse matrices in a consistent way
|
|
|
|
|
|
2011-12-21 23:11:16 +08:00
|
|
|
This is a convenience alias to ``resample(*arrays, replace=False)`` to do
|
2011-05-21 20:46:16 +08:00
|
|
|
random permutations of the collections.
|
2011-05-21 20:32:43 +08:00
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
2011-12-21 23:11:16 +08:00
|
|
|
`*arrays` : sequence of arrays or scipy.sparse matrices with same shape[0]
|
2011-05-21 20:32:43 +08:00
|
|
|
|
|
|
|
|
random_state : int or RandomState instance
|
|
|
|
|
Control the shuffling for reproducible behavior.
|
|
|
|
|
|
2011-05-21 20:46:16 +08:00
|
|
|
n_samples : int, None by default
|
|
|
|
|
Number of samples to generate. If left to None this is
|
|
|
|
|
automatically set to the first dimension of the arrays.
|
|
|
|
|
|
2011-12-23 02:34:33 +08:00
|
|
|
Returns
|
|
|
|
|
-------
|
2011-05-21 20:32:43 +08:00
|
|
|
Sequence of shuffled views of the collections. The original arrays are
|
|
|
|
|
not impacted.
|
|
|
|
|
|
2011-12-23 02:47:49 +08:00
|
|
|
Examples
|
|
|
|
|
--------
|
2011-05-21 20:32:43 +08:00
|
|
|
It is possible to mix sparse and dense arrays in the same run::
|
|
|
|
|
|
|
|
|
|
>>> X = [[1., 0.], [2., 1.], [0., 0.]]
|
|
|
|
|
>>> y = np.array([0, 1, 2])
|
|
|
|
|
|
|
|
|
|
>>> from scipy.sparse import coo_matrix
|
|
|
|
|
>>> X_sparse = coo_matrix(X)
|
|
|
|
|
|
2011-09-02 17:00:02 +08:00
|
|
|
>>> from sklearn.utils import shuffle
|
2011-05-21 20:32:43 +08:00
|
|
|
>>> X, X_sparse, y = shuffle(X, X_sparse, y, random_state=0)
|
|
|
|
|
>>> X
|
|
|
|
|
array([[ 0., 0.],
|
|
|
|
|
[ 2., 1.],
|
|
|
|
|
[ 1., 0.]])
|
|
|
|
|
|
2012-05-16 03:18:30 +08:00
|
|
|
>>> X_sparse # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
|
2012-03-13 03:57:32 +08:00
|
|
|
<3x2 sparse matrix of type '<... 'numpy.float64'>'
|
2011-05-21 20:32:43 +08:00
|
|
|
with 3 stored elements in Compressed Sparse Row format>
|
|
|
|
|
|
|
|
|
|
>>> X_sparse.toarray()
|
|
|
|
|
array([[ 0., 0.],
|
|
|
|
|
[ 2., 1.],
|
|
|
|
|
[ 1., 0.]])
|
|
|
|
|
|
|
|
|
|
>>> y
|
|
|
|
|
array([2, 1, 0])
|
|
|
|
|
|
2011-05-21 20:46:16 +08:00
|
|
|
>>> shuffle(y, n_samples=2, random_state=0)
|
|
|
|
|
array([0, 1])
|
|
|
|
|
|
2011-05-21 20:32:43 +08:00
|
|
|
See also
|
|
|
|
|
--------
|
2011-09-02 17:00:02 +08:00
|
|
|
:func:`sklearn.utils.resample`
|
2011-05-21 20:32:43 +08:00
|
|
|
"""
|
|
|
|
|
options['replace'] = False
|
|
|
|
|
return resample(*arrays, **options)
|
2011-07-17 01:48:08 +08:00
|
|
|
|
|
|
|
|
|
2012-08-15 18:03:59 +08:00
|
|
|
def safe_sqr(X, copy=True):
|
2012-08-15 06:33:41 +08:00
|
|
|
"""Element wise squaring of array-likes and sparse matrices.
|
|
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
|
----------
|
|
|
|
|
X : array like, matrix, sparse matrix
|
|
|
|
|
|
|
|
|
|
Returns
|
|
|
|
|
-------
|
|
|
|
|
X ** 2 : element wise square
|
|
|
|
|
"""
|
|
|
|
|
X = safe_asarray(X)
|
|
|
|
|
if issparse(X):
|
2012-08-15 18:03:59 +08:00
|
|
|
if copy:
|
|
|
|
|
X = X.copy()
|
|
|
|
|
X.data **= 2
|
2012-08-15 06:33:41 +08:00
|
|
|
else:
|
2012-08-15 18:03:59 +08:00
|
|
|
if copy:
|
|
|
|
|
X = X ** 2
|
|
|
|
|
else:
|
|
|
|
|
X **= 2
|
|
|
|
|
return X
|
2012-08-15 06:33:41 +08:00
|
|
|
|
|
|
|
|
|
2011-07-19 03:48:53 +08:00
|
|
|
def gen_even_slices(n, n_packs):
|
2011-07-17 01:48:08 +08:00
|
|
|
"""Generator to create n_packs slices going up to n.
|
|
|
|
|
|
|
|
|
|
Examples
|
2011-07-23 00:28:19 +08:00
|
|
|
--------
|
2011-09-02 17:00:02 +08:00
|
|
|
>>> from sklearn.utils import gen_even_slices
|
2011-07-19 03:48:53 +08:00
|
|
|
>>> list(gen_even_slices(10, 1))
|
2011-07-17 01:48:08 +08:00
|
|
|
[slice(0, 10, None)]
|
2011-07-19 03:48:53 +08:00
|
|
|
>>> list(gen_even_slices(10, 10)) #doctest: +ELLIPSIS
|
|
|
|
|
[slice(0, 1, None), slice(1, 2, None), ..., slice(9, 10, None)]
|
|
|
|
|
>>> list(gen_even_slices(10, 5)) #doctest: +ELLIPSIS
|
|
|
|
|
[slice(0, 2, None), slice(2, 4, None), ..., slice(8, 10, None)]
|
|
|
|
|
>>> list(gen_even_slices(10, 3))
|
2011-07-17 01:48:08 +08:00
|
|
|
[slice(0, 4, None), slice(4, 7, None), slice(7, 10, None)]
|
|
|
|
|
"""
|
|
|
|
|
start = 0
|
|
|
|
|
for pack_num in range(n_packs):
|
|
|
|
|
this_n = n // n_packs
|
|
|
|
|
if pack_num < n % n_packs:
|
|
|
|
|
this_n += 1
|
|
|
|
|
if this_n > 0:
|
|
|
|
|
end = start + this_n
|
|
|
|
|
yield slice(start, end, None)
|
|
|
|
|
start = end
|
2011-11-09 17:35:52 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class ConvergenceWarning(Warning):
|
|
|
|
|
"Custom warning to capture convergence problems"
|