before
stringlengths
87
36.6k
after
stringlengths
116
37.2k
def enet_path(X, y, *, l1_ratio=0.5, eps=0.001, n_alphas=100, alphas=None, precompute='auto', Xy=None, copy_X=True, coef_init=None, verbose=False, return_n_iter=False, positive=False, check_input=True, **params): """Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is:: 1 / (2 * n_samples) * ||y - Xw||^2_2 + alpha * l1_ratio * ||w||_1 + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 For multi-output tasks it is:: (1 / (2 * n_samples)) * ||Y - XW||_Fro^2 + alpha * l1_ratio * ||W||_21 + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 Where:: ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} i.e. the sum of norm of each row. Read more in the :ref:`User Guide <elastic_net>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If ``y`` is mono-output then ``X`` can be sparse. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_targets) Target values. l1_ratio : float, default=0.5 Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). ``l1_ratio=1`` corresponds to the Lasso. eps : float, default=1e-3 Length of the path. ``eps=1e-3`` means that ``alpha_min / alpha_max = 1e-3``. n_alphas : int, default=100 Number of alphas along the regularization path. alphas : ndarray, default=None List of alphas where to compute the models. If None alphas are set automatically. precompute : 'auto', bool or array-like of shape (n_features, n_features), default='auto' Whether to use a precomputed Gram matrix to speed up calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. Xy : array-like of shape (n_features,) or (n_features, n_targets), default=None Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed. copy_X : bool, default=True If ``True``, X will be copied; else, it may be overwritten. coef_init : ndarray of shape (n_features, ), default=None The initial values of the coefficients. verbose : bool or int, default=False Amount of verbosity. return_n_iter : bool, default=False Whether to return the number of iterations or not. positive : bool, default=False If set to True, forces coefficients to be positive. (Only allowed when ``y.ndim == 1``). check_input : bool, default=True If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller. **params : kwargs Keyword arguments passed to the coordinate descent solver. Returns ------- alphas : ndarray of shape (n_alphas,) The alphas along the path where models are computed. coefs : ndarray of shape (n_features, n_alphas) or (n_targets, n_features, n_alphas) Coefficients along the path. dual_gaps : ndarray of shape (n_alphas,) The dual gaps at the end of the optimization for each alpha. n_iters : list of int The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when ``return_n_iter`` is set to True). See Also -------- MultiTaskElasticNet : Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer. MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in cross-validation. ElasticNet : Linear regression with combined L1 and L2 priors as regularizer. ElasticNetCV : Elastic Net model with iterative fitting along a regularization path. Notes ----- For an example, see :ref:`examples/linear_model/plot_lasso_coordinate_descent_path.py <sphx_glr_auto_examples_linear_model_plot_lasso_coordinate_descent_path.py>`. """ X_offset_param = params.pop('X_offset', None) X_scale_param = params.pop('X_scale', None) sample_weight = params.pop('sample_weight', None) tol = params.pop('tol', 0.0001) max_iter = params.pop('max_iter', 1000) random_state = params.pop('random_state', None) selection = params.pop('selection', 'cyclic') if len(params) > 0: raise ValueError('Unexpected parameters in params', params.keys()) if check_input: X = check_array(X, accept_sparse='csc', dtype=[np.float64, np.float32], order='F', copy=copy_X) y = check_array(y, accept_sparse='csc', dtype=X.dtype.type, order='F', copy=False, ensure_2d=False) if Xy is not None: Xy = check_array(Xy, dtype=X.dtype.type, order='C', copy=False, ensure_2d=False) (n_samples, n_features) = X.shape multi_output = False if y.ndim != 1: multi_output = True n_targets = y.shape[1] if multi_output and positive: raise ValueError('positive=True is not allowed for multi-output (y.ndim != 1)') if not multi_output and sparse.isspmatrix(X): if X_offset_param is not None: X_sparse_scaling = X_offset_param / X_scale_param X_sparse_scaling = np.asarray(X_sparse_scaling, dtype=X.dtype) else: X_sparse_scaling = np.zeros(n_features, dtype=X.dtype) if check_input: (X, y, _, _, _, precompute, Xy) = _pre_fit(X, y, Xy, precompute, normalize=False, fit_intercept=False, copy=False, check_input=check_input) if alphas is None: if l1_ratio == 0: raise ValueError('Automatic alpha grid generation is not supported for l1_ratio=0. Please supply a grid by providing your estimator with the appropriate `alphas=` argument.') n_samples = len(y) sparse_center = False if Xy is None: X_sparse = sparse.isspmatrix(X) sparse_center = X_sparse and False X = check_array(X, accept_sparse='csc', copy=False and False and (not X_sparse)) if not X_sparse: (X, y, _, _, _) = _preprocess_data(X, y, False, copy=False) Xy = safe_sparse_dot(X.T, y, dense_output=True) if sparse_center: (_, _, X_offset, _, X_scale) = _preprocess_data(X, y, False) mean_dot = X_offset * np.sum(y) if Xy.ndim == 1: Xy = Xy[:, np.newaxis] if sparse_center: if False: Xy -= mean_dot[:, np.newaxis] alpha_max = np.sqrt(np.sum(Xy ** 2, axis=1)).max() / (n_samples * l1_ratio) if alpha_max <= np.finfo(float).resolution: alphas = np.empty(n_alphas) alphas.fill(np.finfo(float).resolution) alphas = alphas alphas = np.geomspace(alpha_max, alpha_max * eps, num=n_alphas) elif len(alphas) > 1: alphas = np.sort(alphas)[::-1] n_alphas = len(alphas) dual_gaps = np.empty(n_alphas) n_iters = [] rng = check_random_state(random_state) if selection not in ['random', 'cyclic']: raise ValueError('selection should be either random or cyclic.') random = selection == 'random' if not multi_output: coefs = np.empty((n_features, n_alphas), dtype=X.dtype) else: coefs = np.empty((n_targets, n_features, n_alphas), dtype=X.dtype) if coef_init is None: coef_ = np.zeros(coefs.shape[:-1], dtype=X.dtype, order='F') else: coef_ = np.asfortranarray(coef_init, dtype=X.dtype) for (i, alpha) in enumerate(alphas): l1_reg = alpha * l1_ratio * n_samples l2_reg = alpha * (1.0 - l1_ratio) * n_samples if not multi_output and sparse.isspmatrix(X): model = cd_fast.sparse_enet_coordinate_descent(w=coef_, alpha=l1_reg, beta=l2_reg, X_data=X.data, X_indices=X.indices, X_indptr=X.indptr, y=y, sample_weight=sample_weight, X_mean=X_sparse_scaling, max_iter=max_iter, tol=tol, rng=rng, random=random, positive=positive) elif multi_output: model = cd_fast.enet_coordinate_descent_multi_task(coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random) elif isinstance(precompute, np.ndarray): if check_input: precompute = check_array(precompute, dtype=X.dtype.type, order='C') model = cd_fast.enet_coordinate_descent_gram(coef_, l1_reg, l2_reg, precompute, Xy, y, max_iter, tol, rng, random, positive) elif precompute is False: model = cd_fast.enet_coordinate_descent(coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random, positive) else: raise ValueError("Precompute should be one of True, False, 'auto' or array-like. Got %r" % precompute) (coef_, dual_gap_, eps_, n_iter_) = model coefs[..., i] = coef_ dual_gaps[i] = dual_gap_ / n_samples n_iters.append(n_iter_) if verbose: if verbose > 2: print(model) elif verbose > 1: print('Path: %03i out of %03i' % (i, n_alphas)) else: sys.stderr.write('.') if return_n_iter: return (alphas, coefs, dual_gaps, n_iters) return (alphas, coefs, dual_gaps)
def enet_path(X, y, *, l1_ratio=0.5, eps=0.001, n_alphas=100, alphas=None, precompute='auto', Xy=None, copy_X=True, coef_init=None, verbose=False, return_n_iter=False, positive=False, check_input=True, **params): """Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is:: 1 / (2 * n_samples) * ||y - Xw||^2_2 + alpha * l1_ratio * ||w||_1 + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 For multi-output tasks it is:: (1 / (2 * n_samples)) * ||Y - XW||_Fro^2 + alpha * l1_ratio * ||W||_21 + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 Where:: ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} i.e. the sum of norm of each row. Read more in the :ref:`User Guide <elastic_net>`. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If ``y`` is mono-output then ``X`` can be sparse. y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_targets) Target values. l1_ratio : float, default=0.5 Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). ``l1_ratio=1`` corresponds to the Lasso. eps : float, default=1e-3 Length of the path. ``eps=1e-3`` means that ``alpha_min / alpha_max = 1e-3``. n_alphas : int, default=100 Number of alphas along the regularization path. alphas : ndarray, default=None List of alphas where to compute the models. If None alphas are set automatically. precompute : 'auto', bool or array-like of shape (n_features, n_features), default='auto' Whether to use a precomputed Gram matrix to speed up calculations. If set to ``'auto'`` let us decide. The Gram matrix can also be passed as argument. Xy : array-like of shape (n_features,) or (n_features, n_targets), default=None Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed. copy_X : bool, default=True If ``True``, X will be copied; else, it may be overwritten. coef_init : ndarray of shape (n_features, ), default=None The initial values of the coefficients. verbose : bool or int, default=False Amount of verbosity. return_n_iter : bool, default=False Whether to return the number of iterations or not. positive : bool, default=False If set to True, forces coefficients to be positive. (Only allowed when ``y.ndim == 1``). check_input : bool, default=True If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller. **params : kwargs Keyword arguments passed to the coordinate descent solver. Returns ------- alphas : ndarray of shape (n_alphas,) The alphas along the path where models are computed. coefs : ndarray of shape (n_features, n_alphas) or (n_targets, n_features, n_alphas) Coefficients along the path. dual_gaps : ndarray of shape (n_alphas,) The dual gaps at the end of the optimization for each alpha. n_iters : list of int The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when ``return_n_iter`` is set to True). See Also -------- MultiTaskElasticNet : Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer. MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in cross-validation. ElasticNet : Linear regression with combined L1 and L2 priors as regularizer. ElasticNetCV : Elastic Net model with iterative fitting along a regularization path. Notes ----- For an example, see :ref:`examples/linear_model/plot_lasso_coordinate_descent_path.py <sphx_glr_auto_examples_linear_model_plot_lasso_coordinate_descent_path.py>`. """ X_offset_param = params.pop('X_offset', None) X_scale_param = params.pop('X_scale', None) sample_weight = params.pop('sample_weight', None) tol = params.pop('tol', 0.0001) max_iter = params.pop('max_iter', 1000) random_state = params.pop('random_state', None) selection = params.pop('selection', 'cyclic') if len(params) > 0: raise ValueError('Unexpected parameters in params', params.keys()) if check_input: X = check_array(X, accept_sparse='csc', dtype=[np.float64, np.float32], order='F', copy=copy_X) y = check_array(y, accept_sparse='csc', dtype=X.dtype.type, order='F', copy=False, ensure_2d=False) if Xy is not None: Xy = check_array(Xy, dtype=X.dtype.type, order='C', copy=False, ensure_2d=False) (n_samples, n_features) = X.shape multi_output = False if y.ndim != 1: multi_output = True n_targets = y.shape[1] if multi_output and positive: raise ValueError('positive=True is not allowed for multi-output (y.ndim != 1)') if not multi_output and sparse.isspmatrix(X): if X_offset_param is not None: X_sparse_scaling = X_offset_param / X_scale_param X_sparse_scaling = np.asarray(X_sparse_scaling, dtype=X.dtype) else: X_sparse_scaling = np.zeros(n_features, dtype=X.dtype) if check_input: (X, y, _, _, _, precompute, Xy) = _pre_fit(X, y, Xy, precompute, normalize=False, fit_intercept=False, copy=False, check_input=check_input) if alphas is None: <DeepExtract> if l1_ratio == 0: raise ValueError('Automatic alpha grid generation is not supported for l1_ratio=0. Please supply a grid by providing your estimator with the appropriate `alphas=` argument.') n_samples = len(y) sparse_center = False if Xy is None: X_sparse = sparse.isspmatrix(X) sparse_center = X_sparse and False X = check_array(X, accept_sparse='csc', copy=False and False and (not X_sparse)) if not X_sparse: (X, y, _, _, _) = _preprocess_data(X, y, False, copy=False) Xy = safe_sparse_dot(X.T, y, dense_output=True) if sparse_center: (_, _, X_offset, _, X_scale) = _preprocess_data(X, y, False) mean_dot = X_offset * np.sum(y) if Xy.ndim == 1: Xy = Xy[:, np.newaxis] if sparse_center: if False: Xy -= mean_dot[:, np.newaxis] alpha_max = np.sqrt(np.sum(Xy ** 2, axis=1)).max() / (n_samples * l1_ratio) if alpha_max <= np.finfo(float).resolution: alphas = np.empty(n_alphas) alphas.fill(np.finfo(float).resolution) alphas = alphas alphas = np.geomspace(alpha_max, alpha_max * eps, num=n_alphas) </DeepExtract> elif len(alphas) > 1: alphas = np.sort(alphas)[::-1] n_alphas = len(alphas) dual_gaps = np.empty(n_alphas) n_iters = [] rng = check_random_state(random_state) if selection not in ['random', 'cyclic']: raise ValueError('selection should be either random or cyclic.') random = selection == 'random' if not multi_output: coefs = np.empty((n_features, n_alphas), dtype=X.dtype) else: coefs = np.empty((n_targets, n_features, n_alphas), dtype=X.dtype) if coef_init is None: coef_ = np.zeros(coefs.shape[:-1], dtype=X.dtype, order='F') else: coef_ = np.asfortranarray(coef_init, dtype=X.dtype) for (i, alpha) in enumerate(alphas): l1_reg = alpha * l1_ratio * n_samples l2_reg = alpha * (1.0 - l1_ratio) * n_samples if not multi_output and sparse.isspmatrix(X): model = cd_fast.sparse_enet_coordinate_descent(w=coef_, alpha=l1_reg, beta=l2_reg, X_data=X.data, X_indices=X.indices, X_indptr=X.indptr, y=y, sample_weight=sample_weight, X_mean=X_sparse_scaling, max_iter=max_iter, tol=tol, rng=rng, random=random, positive=positive) elif multi_output: model = cd_fast.enet_coordinate_descent_multi_task(coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random) elif isinstance(precompute, np.ndarray): if check_input: precompute = check_array(precompute, dtype=X.dtype.type, order='C') model = cd_fast.enet_coordinate_descent_gram(coef_, l1_reg, l2_reg, precompute, Xy, y, max_iter, tol, rng, random, positive) elif precompute is False: model = cd_fast.enet_coordinate_descent(coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random, positive) else: raise ValueError("Precompute should be one of True, False, 'auto' or array-like. Got %r" % precompute) (coef_, dual_gap_, eps_, n_iter_) = model coefs[..., i] = coef_ dual_gaps[i] = dual_gap_ / n_samples n_iters.append(n_iter_) if verbose: if verbose > 2: print(model) elif verbose > 1: print('Path: %03i out of %03i' % (i, n_alphas)) else: sys.stderr.write('.') if return_n_iter: return (alphas, coefs, dual_gaps, n_iters) return (alphas, coefs, dual_gaps)
def _fit_regressor(X, y, alpha, C, loss, learning_rate, sample_weight, max_iter): loss_ = self.loss_functions[loss] (loss_class, args) = (loss_[0], loss_[1:]) if loss in ('huber', 'epsilon_insensitive', 'squared_epsilon_insensitive'): args = (self.epsilon,) loss_function = loss_class(*args) self.penalty = str(self.penalty).lower() penalty_type = PENALTY_TYPES[self.penalty] learning_rate_type = LEARNING_RATE_TYPES[learning_rate] if not hasattr(self, 't_'): self.t_ = 1.0 n_samples = y.shape[0] validation_mask = np.zeros(n_samples, dtype=np.bool_) if not self.early_stopping: validation_mask = validation_mask if is_classifier(self): splitter_type = StratifiedShuffleSplit else: splitter_type = ShuffleSplit cv = splitter_type(test_size=self.validation_fraction, random_state=self.random_state) (idx_train, idx_val) = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y)) if not np.any(sample_weight > 0[idx_val]): raise ValueError('The sample weights for validation set are all zero, consider using a different random state.') if idx_train.shape[0] == 0 or idx_val.shape[0] == 0: raise ValueError('Splitting %d samples into a train set and a validation set with validation_fraction=%r led to an empty set (%d and %d samples). Please either change validation_fraction, increase number of samples, or disable early_stopping.' % (n_samples, self.validation_fraction, idx_train.shape[0], idx_val.shape[0])) validation_mask[idx_val] = True validation_mask = validation_mask if not self.early_stopping: validation_score_cb = None validation_score_cb = _ValidationScoreCallback(self, X[validation_mask], y[validation_mask], sample_weight[validation_mask], classes=classes) random_state = check_random_state(self.random_state) seed = random_state.randint(0, MAX_INT) (dataset, intercept_decay) = make_dataset(X, y, sample_weight, random_state=random_state) tol = self.tol if self.tol is not None else -np.inf if self.average: coef = self._standard_coef intercept = self._standard_intercept average_coef = self._average_coef average_intercept = self._average_intercept else: coef = self.coef_ intercept = self.intercept_ average_coef = None average_intercept = [0] _plain_sgd = _plain_sgd32 if coef.dtype == np.float32 else _plain_sgd64 (coef, intercept, average_coef, average_intercept, self.n_iter_) = _plain_sgd(coef, intercept[0], average_coef, average_intercept[0], loss_function, penalty_type, alpha, C, self.l1_ratio, dataset, validation_mask, self.early_stopping, validation_score_cb, int(self.n_iter_no_change), max_iter, tol, int(self.fit_intercept), int(self.verbose), int(self.shuffle), seed, 1.0, 1.0, learning_rate_type, self.eta0, self.power_t, 0, self.t_, intercept_decay, self.average) self.t_ += self.n_iter_ * X.shape[0] if self.average > 0: self._average_intercept = np.atleast_1d(average_intercept) self._standard_intercept = np.atleast_1d(intercept) if self.average <= self.t_ - 1.0: self.coef_ = average_coef self.intercept_ = np.atleast_1d(average_intercept) else: self.coef_ = coef self.intercept_ = np.atleast_1d(intercept) else: self.intercept_ = np.atleast_1d(intercept)
def _fit_regressor(X, y, alpha, C, loss, learning_rate, sample_weight, max_iter): <DeepExtract> loss_ = self.loss_functions[loss] (loss_class, args) = (loss_[0], loss_[1:]) if loss in ('huber', 'epsilon_insensitive', 'squared_epsilon_insensitive'): args = (self.epsilon,) loss_function = loss_class(*args) </DeepExtract> <DeepExtract> self.penalty = str(self.penalty).lower() penalty_type = PENALTY_TYPES[self.penalty] </DeepExtract> <DeepExtract> learning_rate_type = LEARNING_RATE_TYPES[learning_rate] </DeepExtract> if not hasattr(self, 't_'): self.t_ = 1.0 <DeepExtract> n_samples = y.shape[0] validation_mask = np.zeros(n_samples, dtype=np.bool_) if not self.early_stopping: validation_mask = validation_mask if is_classifier(self): splitter_type = StratifiedShuffleSplit else: splitter_type = ShuffleSplit cv = splitter_type(test_size=self.validation_fraction, random_state=self.random_state) (idx_train, idx_val) = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y)) if not np.any(sample_weight > 0[idx_val]): raise ValueError('The sample weights for validation set are all zero, consider using a different random state.') if idx_train.shape[0] == 0 or idx_val.shape[0] == 0: raise ValueError('Splitting %d samples into a train set and a validation set with validation_fraction=%r led to an empty set (%d and %d samples). Please either change validation_fraction, increase number of samples, or disable early_stopping.' % (n_samples, self.validation_fraction, idx_train.shape[0], idx_val.shape[0])) validation_mask[idx_val] = True validation_mask = validation_mask </DeepExtract> <DeepExtract> if not self.early_stopping: validation_score_cb = None validation_score_cb = _ValidationScoreCallback(self, X[validation_mask], y[validation_mask], sample_weight[validation_mask], classes=classes) </DeepExtract> random_state = check_random_state(self.random_state) seed = random_state.randint(0, MAX_INT) (dataset, intercept_decay) = make_dataset(X, y, sample_weight, random_state=random_state) tol = self.tol if self.tol is not None else -np.inf if self.average: coef = self._standard_coef intercept = self._standard_intercept average_coef = self._average_coef average_intercept = self._average_intercept else: coef = self.coef_ intercept = self.intercept_ average_coef = None average_intercept = [0] <DeepExtract> _plain_sgd = _plain_sgd32 if coef.dtype == np.float32 else _plain_sgd64 </DeepExtract> (coef, intercept, average_coef, average_intercept, self.n_iter_) = _plain_sgd(coef, intercept[0], average_coef, average_intercept[0], loss_function, penalty_type, alpha, C, self.l1_ratio, dataset, validation_mask, self.early_stopping, validation_score_cb, int(self.n_iter_no_change), max_iter, tol, int(self.fit_intercept), int(self.verbose), int(self.shuffle), seed, 1.0, 1.0, learning_rate_type, self.eta0, self.power_t, 0, self.t_, intercept_decay, self.average) self.t_ += self.n_iter_ * X.shape[0] if self.average > 0: self._average_intercept = np.atleast_1d(average_intercept) self._standard_intercept = np.atleast_1d(intercept) if self.average <= self.t_ - 1.0: self.coef_ = average_coef self.intercept_ = np.atleast_1d(average_intercept) else: self.coef_ = coef self.intercept_ = np.atleast_1d(intercept) else: self.intercept_ = np.atleast_1d(intercept)
def test_theil_sen_2d(): random_state = np.random.RandomState(0) n_samples = 100 X = random_state.normal(size=(n_samples, 2)) w = np.array([5.0, 10.0]) c = 1.0 noise = 0.1 * random_state.normal(size=n_samples) y = np.dot(X, w) + c + noise n_outliers = n_samples // 10 ix = random_state.randint(0, n_samples, size=n_outliers) y[ix] = 50 * random_state.normal(size=n_outliers) (X, y, w, c) = (X, y, w, c) lstq = LinearRegression().fit(X, y) assert norm(lstq.coef_ - w) > 1.0 theil_sen = TheilSenRegressor(max_subpopulation=1000.0, random_state=0).fit(X, y) assert_array_almost_equal(theil_sen.coef_, w, 1) assert_array_almost_equal(theil_sen.intercept_, c, 1)
def test_theil_sen_2d(): <DeepExtract> random_state = np.random.RandomState(0) n_samples = 100 X = random_state.normal(size=(n_samples, 2)) w = np.array([5.0, 10.0]) c = 1.0 noise = 0.1 * random_state.normal(size=n_samples) y = np.dot(X, w) + c + noise n_outliers = n_samples // 10 ix = random_state.randint(0, n_samples, size=n_outliers) y[ix] = 50 * random_state.normal(size=n_outliers) (X, y, w, c) = (X, y, w, c) </DeepExtract> lstq = LinearRegression().fit(X, y) assert norm(lstq.coef_ - w) > 1.0 theil_sen = TheilSenRegressor(max_subpopulation=1000.0, random_state=0).fit(X, y) assert_array_almost_equal(theil_sen.coef_, w, 1) assert_array_almost_equal(theil_sen.intercept_, c, 1)
def test_multi_thread_multi_class_and_early_stopping(): _update_kwargs(kwargs) clf = linear_model.SGDClassifier(**kwargs) clf.fit(iris.data, iris.target) assert clf.n_iter_ > clf.n_iter_no_change assert clf.n_iter_ < clf.n_iter_no_change + 20 assert clf.score(iris.data, iris.target) > 0.8
def test_multi_thread_multi_class_and_early_stopping(): <DeepExtract> _update_kwargs(kwargs) clf = linear_model.SGDClassifier(**kwargs) </DeepExtract> clf.fit(iris.data, iris.target) assert clf.n_iter_ > clf.n_iter_no_change assert clf.n_iter_ < clf.n_iter_no_change + 20 assert clf.score(iris.data, iris.target) > 0.8
def fit(self, X, y): """Fit the :class:`TargetEncoder` to X and y. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to determine the categories of each feature. y : array-like of shape (n_samples,) The target data used to encode the categories. Returns ------- self : object Fitted encoder. """ self._validate_params() from ..preprocessing import LabelEncoder check_consistent_length(X, y) self._fit(X, handle_unknown='ignore', force_all_finite='allow-nan') if self.target_type == 'auto': accepted_target_types = ('binary', 'continuous') inferred_type_of_target = type_of_target(y, input_name='y') if inferred_type_of_target not in accepted_target_types: raise ValueError(f'Target type was inferred to be {inferred_type_of_target!r}. Only {accepted_target_types} are supported.') self.target_type_ = inferred_type_of_target else: self.target_type_ = self.target_type if self.target_type_ == 'binary': y = LabelEncoder().fit_transform(y) else: y = _check_y(y, y_numeric=True, estimator=self) self.target_mean_ = np.mean(y) (X_ordinal, X_known_mask) = self._transform(X, handle_unknown='ignore', force_all_finite='allow-nan') n_categories = np.fromiter((len(category_for_feature) for category_for_feature in self.categories_), dtype=np.int64, count=len(self.categories_)) if self.smooth == 'auto': y_variance = np.var(y) self.encodings_ = _fit_encoding_fast_auto_smooth(X_ordinal, y, n_categories, self.target_mean_, y_variance) else: self.encodings_ = _fit_encoding_fast(X_ordinal, y, n_categories, self.smooth, self.target_mean_) return (X_ordinal, X_known_mask, y, n_categories) return self
def fit(self, X, y): """Fit the :class:`TargetEncoder` to X and y. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to determine the categories of each feature. y : array-like of shape (n_samples,) The target data used to encode the categories. Returns ------- self : object Fitted encoder. """ self._validate_params() <DeepExtract> from ..preprocessing import LabelEncoder check_consistent_length(X, y) self._fit(X, handle_unknown='ignore', force_all_finite='allow-nan') if self.target_type == 'auto': accepted_target_types = ('binary', 'continuous') inferred_type_of_target = type_of_target(y, input_name='y') if inferred_type_of_target not in accepted_target_types: raise ValueError(f'Target type was inferred to be {inferred_type_of_target!r}. Only {accepted_target_types} are supported.') self.target_type_ = inferred_type_of_target else: self.target_type_ = self.target_type if self.target_type_ == 'binary': y = LabelEncoder().fit_transform(y) else: y = _check_y(y, y_numeric=True, estimator=self) self.target_mean_ = np.mean(y) (X_ordinal, X_known_mask) = self._transform(X, handle_unknown='ignore', force_all_finite='allow-nan') n_categories = np.fromiter((len(category_for_feature) for category_for_feature in self.categories_), dtype=np.int64, count=len(self.categories_)) if self.smooth == 'auto': y_variance = np.var(y) self.encodings_ = _fit_encoding_fast_auto_smooth(X_ordinal, y, n_categories, self.target_mean_, y_variance) else: self.encodings_ = _fit_encoding_fast(X_ordinal, y, n_categories, self.smooth, self.target_mean_) return (X_ordinal, X_known_mask, y, n_categories) </DeepExtract> return self
def check_set_output_transform(name, transformer_orig): tags = transformer_orig._get_tags() if '2darray' not in tags['X_types'] or tags['no_validation']: return rng = np.random.RandomState(0) transformer = clone(transformer_orig) X = rng.uniform(size=(20, 5)) if '1darray' in _safe_tags(transformer_orig, key='X_types'): X = X[:, 0] if _safe_tags(transformer_orig, key='requires_positive_X'): X = X - X.min() if 'categorical' in _safe_tags(transformer_orig, key='X_types'): X = (X - X.min()).astype(np.int32) if transformer_orig.__class__.__name__ == 'SkewedChi2Sampler': X = X - X.min() if _is_pairwise_metric(transformer_orig): X = pairwise_distances(X, metric='euclidean') elif _safe_tags(transformer_orig, key='pairwise'): X = kernel(X, X) X = X y = rng.randint(0, 2, size=20) if _safe_tags(transformer_orig, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(transformer_orig, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(transformer_orig, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y set_random_state(transformer) def fit_then_transform(est): if name in CROSS_DECOMPOSITION: return est.fit(X, y).transform(X, y) return est.fit(X, y).transform(X) def fit_transform(est): return est.fit_transform(X, y) transform_methods = {'transform': fit_then_transform, 'fit_transform': fit_transform} for (name, transform_method) in transform_methods.items(): transformer = clone(transformer) if not hasattr(transformer, name): continue X_trans_no_setting = transform_method(transformer) if name in CROSS_DECOMPOSITION: X_trans_no_setting = X_trans_no_setting[0] transformer.set_output(transform='default') X_trans_default = transform_method(transformer) if name in CROSS_DECOMPOSITION: X_trans_default = X_trans_default[0] assert_allclose_dense_sparse(X_trans_no_setting, X_trans_default)
def check_set_output_transform(name, transformer_orig): tags = transformer_orig._get_tags() if '2darray' not in tags['X_types'] or tags['no_validation']: return rng = np.random.RandomState(0) transformer = clone(transformer_orig) X = rng.uniform(size=(20, 5)) <DeepExtract> if '1darray' in _safe_tags(transformer_orig, key='X_types'): X = X[:, 0] if _safe_tags(transformer_orig, key='requires_positive_X'): X = X - X.min() if 'categorical' in _safe_tags(transformer_orig, key='X_types'): X = (X - X.min()).astype(np.int32) if transformer_orig.__class__.__name__ == 'SkewedChi2Sampler': X = X - X.min() if _is_pairwise_metric(transformer_orig): X = pairwise_distances(X, metric='euclidean') elif _safe_tags(transformer_orig, key='pairwise'): X = kernel(X, X) X = X </DeepExtract> y = rng.randint(0, 2, size=20) <DeepExtract> if _safe_tags(transformer_orig, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(transformer_orig, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(transformer_orig, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y </DeepExtract> set_random_state(transformer) def fit_then_transform(est): if name in CROSS_DECOMPOSITION: return est.fit(X, y).transform(X, y) return est.fit(X, y).transform(X) def fit_transform(est): return est.fit_transform(X, y) transform_methods = {'transform': fit_then_transform, 'fit_transform': fit_transform} for (name, transform_method) in transform_methods.items(): transformer = clone(transformer) if not hasattr(transformer, name): continue X_trans_no_setting = transform_method(transformer) if name in CROSS_DECOMPOSITION: X_trans_no_setting = X_trans_no_setting[0] transformer.set_output(transform='default') X_trans_default = transform_method(transformer) if name in CROSS_DECOMPOSITION: X_trans_default = X_trans_default[0] assert_allclose_dense_sparse(X_trans_no_setting, X_trans_default)
@pytest.mark.filterwarnings('ignore:The max_iter was reached') def test_sag_pobj_matches_ridge_regression(): """tests if the sag pobj matches ridge reg""" n_samples = 100 n_features = 10 alpha = 1.0 n_iter = 100 fit_intercept = False rng = np.random.RandomState(10) X = rng.normal(size=(n_samples, n_features)) true_w = rng.normal(size=n_features) y = X.dot(true_w) clf1 = Ridge(fit_intercept=fit_intercept, tol=1e-11, solver='sag', alpha=alpha, max_iter=n_iter, random_state=42) clf2 = clone(clf1) clf3 = Ridge(fit_intercept=fit_intercept, tol=1e-05, solver='lsqr', alpha=alpha, max_iter=n_iter, random_state=42) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) clf3.fit(X, y) clf1.coef_ = clf1.coef_.ravel() pred = np.dot(X, clf1.coef_) p = squared_loss(pred, y) p += alpha * clf1.coef_.dot(clf1.coef_) / 2.0 pobj1 = p clf2.coef_ = clf2.coef_.ravel() pred = np.dot(X, clf2.coef_) p = squared_loss(pred, y) p += alpha * clf2.coef_.dot(clf2.coef_) / 2.0 pobj2 = p clf3.coef_ = clf3.coef_.ravel() pred = np.dot(X, clf3.coef_) p = squared_loss(pred, y) p += alpha * clf3.coef_.dot(clf3.coef_) / 2.0 pobj3 = p assert_array_almost_equal(pobj1, pobj2, decimal=4) assert_array_almost_equal(pobj1, pobj3, decimal=4) assert_array_almost_equal(pobj3, pobj2, decimal=4)
@pytest.mark.filterwarnings('ignore:The max_iter was reached') def test_sag_pobj_matches_ridge_regression(): """tests if the sag pobj matches ridge reg""" n_samples = 100 n_features = 10 alpha = 1.0 n_iter = 100 fit_intercept = False rng = np.random.RandomState(10) X = rng.normal(size=(n_samples, n_features)) true_w = rng.normal(size=n_features) y = X.dot(true_w) clf1 = Ridge(fit_intercept=fit_intercept, tol=1e-11, solver='sag', alpha=alpha, max_iter=n_iter, random_state=42) clf2 = clone(clf1) clf3 = Ridge(fit_intercept=fit_intercept, tol=1e-05, solver='lsqr', alpha=alpha, max_iter=n_iter, random_state=42) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) clf3.fit(X, y) <DeepExtract> clf1.coef_ = clf1.coef_.ravel() pred = np.dot(X, clf1.coef_) p = squared_loss(pred, y) p += alpha * clf1.coef_.dot(clf1.coef_) / 2.0 pobj1 = p </DeepExtract> <DeepExtract> clf2.coef_ = clf2.coef_.ravel() pred = np.dot(X, clf2.coef_) p = squared_loss(pred, y) p += alpha * clf2.coef_.dot(clf2.coef_) / 2.0 pobj2 = p </DeepExtract> <DeepExtract> clf3.coef_ = clf3.coef_.ravel() pred = np.dot(X, clf3.coef_) p = squared_loss(pred, y) p += alpha * clf3.coef_.dot(clf3.coef_) / 2.0 pobj3 = p </DeepExtract> assert_array_almost_equal(pobj1, pobj2, decimal=4) assert_array_almost_equal(pobj1, pobj3, decimal=4) assert_array_almost_equal(pobj3, pobj2, decimal=4)
def depth_first_collect_leaf_values(node_idx): node = nodes[node_idx] if node['is_leaf']: values.append(node['value']) return node = nodes[node['left']] if node['is_leaf']: values.append(node['value']) return depth_first_collect_leaf_values(node['left']) depth_first_collect_leaf_values(node['right']) node = nodes[node['right']] if node['is_leaf']: values.append(node['value']) return depth_first_collect_leaf_values(node['left']) depth_first_collect_leaf_values(node['right']) </DeepExtract>
def depth_first_collect_leaf_values(node_idx): node = nodes[node_idx] if node['is_leaf']: values.append(node['value']) return <DeepExtract> node = nodes[node['left']] if node['is_leaf']: values.append(node['value']) return depth_first_collect_leaf_values(node['left']) depth_first_collect_leaf_values(node['right']) </DeepExtract> <DeepExtract> node = nodes[node['right']] if node['is_leaf']: values.append(node['value']) return depth_first_collect_leaf_values(node['left']) depth_first_collect_leaf_values(node['right']) </DeepExtract>
def transform(self, X): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) The data to be transformed by subset. Returns ------- X_t : {array-like, sparse matrix} of shape (n_samples, sum_n_components) Horizontally stacked results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. If any result is a sparse matrix, everything will be converted to sparse matrices. """ check_is_fitted(self) if hasattr(X, '__array__') or sparse.issparse(X): X = X X = check_array(X, force_all_finite='allow-nan', dtype=object) fit_dataframe_and_transform_dataframe = hasattr(self, 'feature_names_in_') and hasattr(X, 'columns') if fit_dataframe_and_transform_dataframe: named_transformers = self.named_transformers_ non_dropped_indices = [ind for (name, ind) in self._transformer_to_input_indices.items() if name in named_transformers and isinstance(named_transformers[name], str) and (named_transformers[name] != 'drop')] all_indices = set(chain(*non_dropped_indices)) all_names = set((self.feature_names_in_[ind] for ind in all_indices)) diff = all_names - set(X.columns) if diff: raise ValueError(f'columns are missing: {diff}') else: self._check_n_features(X, reset=False) transformers = list(self._iter(fitted=True, replace_strings=True, column_as_strings=fit_dataframe_and_transform_dataframe)) try: Xs = Parallel(n_jobs=self.n_jobs)((delayed(_transform_one)(transformer=clone(trans) if not True else trans, X=_safe_indexing(X, column, axis=1), y=None, weight=weight, message_clsname='ColumnTransformer', message=self._log_message(name, idx, len(transformers))) for (idx, (name, trans, column, weight)) in enumerate(transformers, 1))) except ValueError as e: if 'Expected 2D array, got 1D array instead' in str(e): raise ValueError(_ERR_MSG_1DCOLUMN) from e else: raise names = [name for (name, _, _, _) in self._iter(fitted=True, replace_strings=True)] for (Xs, name) in zip(Xs, names): if not getattr(Xs, 'ndim', 0) == 2: raise ValueError("The output of the '{0}' transformer should be 2D (scipy matrix, array, or pandas DataFrame).".format(name)) if not Xs: return np.zeros((X.shape[0], 0)) return self._hstack(list(Xs))
def transform(self, X): """Transform X separately by each transformer, concatenate results. Parameters ---------- X : {array-like, dataframe} of shape (n_samples, n_features) The data to be transformed by subset. Returns ------- X_t : {array-like, sparse matrix} of shape (n_samples, sum_n_components) Horizontally stacked results of transformers. sum_n_components is the sum of n_components (output dimension) over transformers. If any result is a sparse matrix, everything will be converted to sparse matrices. """ check_is_fitted(self) <DeepExtract> if hasattr(X, '__array__') or sparse.issparse(X): X = X X = check_array(X, force_all_finite='allow-nan', dtype=object) </DeepExtract> fit_dataframe_and_transform_dataframe = hasattr(self, 'feature_names_in_') and hasattr(X, 'columns') if fit_dataframe_and_transform_dataframe: named_transformers = self.named_transformers_ non_dropped_indices = [ind for (name, ind) in self._transformer_to_input_indices.items() if name in named_transformers and isinstance(named_transformers[name], str) and (named_transformers[name] != 'drop')] all_indices = set(chain(*non_dropped_indices)) all_names = set((self.feature_names_in_[ind] for ind in all_indices)) diff = all_names - set(X.columns) if diff: raise ValueError(f'columns are missing: {diff}') else: self._check_n_features(X, reset=False) <DeepExtract> transformers = list(self._iter(fitted=True, replace_strings=True, column_as_strings=fit_dataframe_and_transform_dataframe)) try: Xs = Parallel(n_jobs=self.n_jobs)((delayed(_transform_one)(transformer=clone(trans) if not True else trans, X=_safe_indexing(X, column, axis=1), y=None, weight=weight, message_clsname='ColumnTransformer', message=self._log_message(name, idx, len(transformers))) for (idx, (name, trans, column, weight)) in enumerate(transformers, 1))) except ValueError as e: if 'Expected 2D array, got 1D array instead' in str(e): raise ValueError(_ERR_MSG_1DCOLUMN) from e else: raise </DeepExtract> <DeepExtract> names = [name for (name, _, _, _) in self._iter(fitted=True, replace_strings=True)] for (Xs, name) in zip(Xs, names): if not getattr(Xs, 'ndim', 0) == 2: raise ValueError("The output of the '{0}' transformer should be 2D (scipy matrix, array, or pandas DataFrame).".format(name)) </DeepExtract> if not Xs: return np.zeros((X.shape[0], 0)) return self._hstack(list(Xs))
def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None): """Compute incremental mean and variance along an axis 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-arrays of the proper size, i.e. the number of features in X. last_n is the number of samples encountered until now. Parameters ---------- X : CSR or CSC sparse matrix of shape (n_samples, n_features) Input data. axis : {0, 1} Axis along which the axis should be computed. last_mean : ndarray of shape (n_features,) or (n_samples,), dtype=floating Array of means to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. last_var : ndarray of shape (n_features,) or (n_samples,), dtype=floating Array of variances to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. last_n : float or ndarray of shape (n_features,) or (n_samples,), dtype=floating Sum of the weights seen so far, excluding the current weights If not float, it should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. If float it corresponds to having same weights for all samples (or features). weights : ndarray of shape (n_samples,) or (n_features,), default=None If axis is set to 0 shape is (n_samples,) or if axis is set to 1 shape is (n_features,). If it is set to None, then samples are equally weighted. .. versionadded:: 0.24 Returns ------- means : ndarray of shape (n_features,) or (n_samples,), dtype=floating Updated feature-wise means if axis = 0 or sample-wise means if axis = 1. variances : ndarray of shape (n_features,) or (n_samples,), dtype=floating Updated feature-wise variances if axis = 0 or sample-wise variances if axis = 1. n : ndarray of shape (n_features,) or (n_samples,), dtype=integral Updated number of seen samples per feature if axis=0 or number of seen features per sample if axis=1. If weights is not None, n is a sum of the weights of the seen samples or features instead of the actual number of seen samples or features. Notes ----- NaNs are ignored in the algorithm. """ if axis not in (0, 1): raise ValueError('Unknown axis value: %d. Use 0 for rows, or 1 for columns' % axis) if not isinstance(X, (sp.csr_matrix, sp.csc_matrix)): input_type = X.format if sp.issparse(X) else type(X) err = 'Expected a CSR or CSC sparse matrix, got %s.' % input_type raise TypeError(err) if np.size(last_n) == 1: last_n = np.full(last_mean.shape, last_n, dtype=last_mean.dtype) if not np.size(last_mean) == np.size(last_var) == np.size(last_n): raise ValueError('last_mean, last_var, last_n do not have the same shapes.') if axis == 1: if np.size(last_mean) != X.shape[0]: raise ValueError(f'If axis=1, then last_mean, last_n, last_var should be of size n_samples {X.shape[0]} (Got {np.size(last_mean)}).') elif np.size(last_mean) != X.shape[1]: raise ValueError(f'If axis=0, then last_mean, last_n, last_var should be of size n_features {X.shape[1]} (Got {np.size(last_mean)}).') X = X.T if axis == 1 else X if weights is not None: weights = _check_sample_weight(weights, X, dtype=X.dtype) return _incr_mean_var_axis0(X, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights)
def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None): """Compute incremental mean and variance along an axis 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-arrays of the proper size, i.e. the number of features in X. last_n is the number of samples encountered until now. Parameters ---------- X : CSR or CSC sparse matrix of shape (n_samples, n_features) Input data. axis : {0, 1} Axis along which the axis should be computed. last_mean : ndarray of shape (n_features,) or (n_samples,), dtype=floating Array of means to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. last_var : ndarray of shape (n_features,) or (n_samples,), dtype=floating Array of variances to update with the new data X. Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. last_n : float or ndarray of shape (n_features,) or (n_samples,), dtype=floating Sum of the weights seen so far, excluding the current weights If not float, it should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. If float it corresponds to having same weights for all samples (or features). weights : ndarray of shape (n_samples,) or (n_features,), default=None If axis is set to 0 shape is (n_samples,) or if axis is set to 1 shape is (n_features,). If it is set to None, then samples are equally weighted. .. versionadded:: 0.24 Returns ------- means : ndarray of shape (n_features,) or (n_samples,), dtype=floating Updated feature-wise means if axis = 0 or sample-wise means if axis = 1. variances : ndarray of shape (n_features,) or (n_samples,), dtype=floating Updated feature-wise variances if axis = 0 or sample-wise variances if axis = 1. n : ndarray of shape (n_features,) or (n_samples,), dtype=integral Updated number of seen samples per feature if axis=0 or number of seen features per sample if axis=1. If weights is not None, n is a sum of the weights of the seen samples or features instead of the actual number of seen samples or features. Notes ----- NaNs are ignored in the algorithm. """ <DeepExtract> if axis not in (0, 1): raise ValueError('Unknown axis value: %d. Use 0 for rows, or 1 for columns' % axis) </DeepExtract> if not isinstance(X, (sp.csr_matrix, sp.csc_matrix)): <DeepExtract> input_type = X.format if sp.issparse(X) else type(X) err = 'Expected a CSR or CSC sparse matrix, got %s.' % input_type raise TypeError(err) </DeepExtract> if np.size(last_n) == 1: last_n = np.full(last_mean.shape, last_n, dtype=last_mean.dtype) if not np.size(last_mean) == np.size(last_var) == np.size(last_n): raise ValueError('last_mean, last_var, last_n do not have the same shapes.') if axis == 1: if np.size(last_mean) != X.shape[0]: raise ValueError(f'If axis=1, then last_mean, last_n, last_var should be of size n_samples {X.shape[0]} (Got {np.size(last_mean)}).') elif np.size(last_mean) != X.shape[1]: raise ValueError(f'If axis=0, then last_mean, last_n, last_var should be of size n_features {X.shape[1]} (Got {np.size(last_mean)}).') X = X.T if axis == 1 else X if weights is not None: weights = _check_sample_weight(weights, X, dtype=X.dtype) return _incr_mean_var_axis0(X, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights)
def test_dump_query_id(): with _open_binary(TEST_DATA_MODULE, datafile) as f: (X, y) = load_svmlight_file(f, **kwargs) X = X.toarray() query_id = np.arange(X.shape[0]) // 2 f = BytesIO() dump_svmlight_file(X, y, f, query_id=query_id, zero_based=True) f.seek(0) (X1, y1, query_id1) = load_svmlight_file(f, query_id=True, zero_based=True) assert_array_almost_equal(X, X1.toarray()) assert_array_almost_equal(y, y1) assert_array_almost_equal(query_id, query_id1)
def test_dump_query_id(): <DeepExtract> with _open_binary(TEST_DATA_MODULE, datafile) as f: (X, y) = load_svmlight_file(f, **kwargs) </DeepExtract> X = X.toarray() query_id = np.arange(X.shape[0]) // 2 f = BytesIO() dump_svmlight_file(X, y, f, query_id=query_id, zero_based=True) f.seek(0) (X1, y1, query_id1) = load_svmlight_file(f, query_id=True, zero_based=True) assert_array_almost_equal(X, X1.toarray()) assert_array_almost_equal(y, y1) assert_array_almost_equal(query_id, query_id1)
def _staged_raw_predict(X, check_input=True): """Compute raw predictions of ``X`` for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True If False, the input arrays X will not be checked. Returns ------- raw_predictions : generator of ndarray of shape (n_samples, k) The raw predictions of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. Regression and binary classification are special cases with ``k == 1``, otherwise ``k==n_classes``. """ if check_input: X = self._validate_data(X, dtype=DTYPE, order='C', accept_sparse='csr', reset=False) self._check_initialized() X = self.estimators_[0, 0]._validate_X_predict(X, check_input=True) if self.init_ == 'zero': raw_predictions = np.zeros(shape=(X.shape[0], self._loss.K), dtype=np.float64) else: raw_predictions = self._loss.get_init_raw_predictions(X, self.init_).astype(np.float64) raw_predictions = raw_predictions for i in range(self.estimators_.shape[0]): predict_stage(self.estimators_, i, X, self.learning_rate, raw_predictions) yield raw_predictions.copy()
def _staged_raw_predict(X, check_input=True): """Compute raw predictions of ``X`` for each iteration. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True If False, the input arrays X will not be checked. Returns ------- raw_predictions : generator of ndarray of shape (n_samples, k) The raw predictions of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. Regression and binary classification are special cases with ``k == 1``, otherwise ``k==n_classes``. """ if check_input: X = self._validate_data(X, dtype=DTYPE, order='C', accept_sparse='csr', reset=False) <DeepExtract> self._check_initialized() X = self.estimators_[0, 0]._validate_X_predict(X, check_input=True) if self.init_ == 'zero': raw_predictions = np.zeros(shape=(X.shape[0], self._loss.K), dtype=np.float64) else: raw_predictions = self._loss.get_init_raw_predictions(X, self.init_).astype(np.float64) raw_predictions = raw_predictions </DeepExtract> for i in range(self.estimators_.shape[0]): predict_stage(self.estimators_, i, X, self.learning_rate, raw_predictions) yield raw_predictions.copy()
@pytest.mark.parametrize('gzip_response', [True, False]) def test_warn_ignore_attribute(monkeypatch, gzip_response): data_id = 40966 expected_row_id_msg = "target_column='{}' has flag is_row_identifier." expected_ignore_msg = "target_column='{}' has flag is_ignore." url_prefix_data_description = 'https://openml.org/api/v1/json/data/' url_prefix_data_features = 'https://openml.org/api/v1/json/data/features/' url_prefix_download_data = 'https://openml.org/data/v1/' url_prefix_data_list = 'https://openml.org/api/v1/json/data/list/' path_suffix = '.gz' read_fn = gzip.open data_module = OPENML_TEST_DATA_MODULE + '.' + f'id_{data_id}' def _file_name(url, suffix): output = re.sub('\\W', '-', url[len('https://openml.org/'):]) + suffix + path_suffix return output.replace('-json-data-list', '-jdl').replace('-json-data-features', '-jdf').replace('-json-data-qualities', '-jdq').replace('-json-data', '-jd').replace('-data_name', '-dn').replace('-download', '-dl').replace('-limit', '-l').replace('-data_version', '-dv').replace('-status', '-s').replace('-deactivated', '-dact').replace('-active', '-act') def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix): assert url.startswith(expected_prefix) data_file_name = _file_name(url, suffix) with _open_binary(data_module, data_file_name) as f: if has_gzip_header and gzip_response: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen_data_description(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_description, suffix='.json') def _mock_urlopen_data_features(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_features, suffix='.json') def _mock_urlopen_download_data(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_download_data, suffix='.arff') def _mock_urlopen_data_list(url, has_gzip_header): assert url.startswith(url_prefix_data_list) data_file_name = _file_name(url, '.json') with _open_binary(data_module, data_file_name) as f: decompressed_f = read_fn(f, 'rb') decoded_s = decompressed_f.read().decode('utf-8') json_data = json.loads(decoded_s) if 'error' in json_data: raise HTTPError(url=None, code=412, msg='Simulated mock error', hdrs=None, fp=None) with _open_binary(data_module, data_file_name) as f: if has_gzip_header: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen(request, *args, **kwargs): url = request.get_full_url() has_gzip_header = request.get_header('Accept-encoding') == 'gzip' if url.startswith(url_prefix_data_list): return _mock_urlopen_data_list(url, has_gzip_header) elif url.startswith(url_prefix_data_features): return _mock_urlopen_data_features(url, has_gzip_header) elif url.startswith(url_prefix_download_data): return _mock_urlopen_download_data(url, has_gzip_header) elif url.startswith(url_prefix_data_description): return _mock_urlopen_data_description(url, has_gzip_header) else: raise ValueError('Unknown mocking URL pattern: %s' % url) if test_offline: monkeypatch.setattr(sklearn.datasets._openml, 'urlopen', _mock_urlopen) target_col = 'MouseID' msg = expected_row_id_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=target_col, cache=False, as_frame=False, parser='liac-arff') target_col = 'Genotype' msg = expected_ignore_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=target_col, cache=False, as_frame=False, parser='liac-arff') target_col = 'MouseID' msg = expected_row_id_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=[target_col, 'class'], cache=False, as_frame=False, parser='liac-arff') target_col = 'Genotype' msg = expected_ignore_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=[target_col, 'class'], cache=False, as_frame=False, parser='liac-arff')
@pytest.mark.parametrize('gzip_response', [True, False]) def test_warn_ignore_attribute(monkeypatch, gzip_response): data_id = 40966 expected_row_id_msg = "target_column='{}' has flag is_row_identifier." expected_ignore_msg = "target_column='{}' has flag is_ignore." <DeepExtract> url_prefix_data_description = 'https://openml.org/api/v1/json/data/' url_prefix_data_features = 'https://openml.org/api/v1/json/data/features/' url_prefix_download_data = 'https://openml.org/data/v1/' url_prefix_data_list = 'https://openml.org/api/v1/json/data/list/' path_suffix = '.gz' read_fn = gzip.open data_module = OPENML_TEST_DATA_MODULE + '.' + f'id_{data_id}' def _file_name(url, suffix): output = re.sub('\\W', '-', url[len('https://openml.org/'):]) + suffix + path_suffix return output.replace('-json-data-list', '-jdl').replace('-json-data-features', '-jdf').replace('-json-data-qualities', '-jdq').replace('-json-data', '-jd').replace('-data_name', '-dn').replace('-download', '-dl').replace('-limit', '-l').replace('-data_version', '-dv').replace('-status', '-s').replace('-deactivated', '-dact').replace('-active', '-act') def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix): assert url.startswith(expected_prefix) data_file_name = _file_name(url, suffix) with _open_binary(data_module, data_file_name) as f: if has_gzip_header and gzip_response: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen_data_description(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_description, suffix='.json') def _mock_urlopen_data_features(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_features, suffix='.json') def _mock_urlopen_download_data(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_download_data, suffix='.arff') def _mock_urlopen_data_list(url, has_gzip_header): assert url.startswith(url_prefix_data_list) data_file_name = _file_name(url, '.json') with _open_binary(data_module, data_file_name) as f: decompressed_f = read_fn(f, 'rb') decoded_s = decompressed_f.read().decode('utf-8') json_data = json.loads(decoded_s) if 'error' in json_data: raise HTTPError(url=None, code=412, msg='Simulated mock error', hdrs=None, fp=None) with _open_binary(data_module, data_file_name) as f: if has_gzip_header: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen(request, *args, **kwargs): url = request.get_full_url() has_gzip_header = request.get_header('Accept-encoding') == 'gzip' if url.startswith(url_prefix_data_list): return _mock_urlopen_data_list(url, has_gzip_header) elif url.startswith(url_prefix_data_features): return _mock_urlopen_data_features(url, has_gzip_header) elif url.startswith(url_prefix_download_data): return _mock_urlopen_download_data(url, has_gzip_header) elif url.startswith(url_prefix_data_description): return _mock_urlopen_data_description(url, has_gzip_header) else: raise ValueError('Unknown mocking URL pattern: %s' % url) if test_offline: monkeypatch.setattr(sklearn.datasets._openml, 'urlopen', _mock_urlopen) </DeepExtract> target_col = 'MouseID' msg = expected_row_id_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=target_col, cache=False, as_frame=False, parser='liac-arff') target_col = 'Genotype' msg = expected_ignore_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=target_col, cache=False, as_frame=False, parser='liac-arff') target_col = 'MouseID' msg = expected_row_id_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=[target_col, 'class'], cache=False, as_frame=False, parser='liac-arff') target_col = 'Genotype' msg = expected_ignore_msg.format(target_col) with pytest.warns(UserWarning, match=msg): fetch_openml(data_id=data_id, target_column=[target_col, 'class'], cache=False, as_frame=False, parser='liac-arff')
def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False): """ Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.) """ if isinstance(tests, basestring): tests = list(map(str.strip, tests.rstrip().splitlines())) if isinstance(comment, basestring): comment = Literal(comment) allResults = [] comments = [] success = True for t in tests: if comment is not None and comment.matches(t, False) or (comments and (not t)): comments.append(t) continue if not t: continue out = ['\n'.join(comments), t] comments = [] try: t = t.replace('\\n', '\n') ParserElement.resetCache() if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: t = t.expandtabs() try: (loc, tokens) = self._parse(t, 0) if parseAll: loc = self.preParse(t, loc) se = Empty() + StringEnd() se._parse(t, loc) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: raise exc else: result = tokens out.append(result.dump(full=fullDump)) success = success and (not failureTests) except ParseBaseException as pe: fatal = '(FATAL)' if isinstance(pe, ParseFatalException) else '' if '\n' in t: out.append(line(pe.loc, t)) out.append(' ' * (col(pe.loc, t) - 1) + '^' + fatal) else: out.append(' ' * pe.loc + '^' + fatal) out.append('FAIL: ' + str(pe)) success = success and failureTests result = pe except Exception as exc: out.append('FAIL-EXCEPTION: ' + str(exc)) success = success and failureTests result = exc if printResults: if fullDump: out.append('') print('\n'.join(out)) allResults.append((t, result)) return (success, allResults)
def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False): """ Execute the parse expression on a series of test strings, showing each test, the parsed results or where the parse failed. Quick and easy way to run a parse expression against a list of sample strings. Parameters: - tests - a list of separate test strings, or a multiline string of test strings - parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests - comment - (default=C{'#'}) - expression for indicating embedded comments in the test string; pass None to disable comment filtering - fullDump - (default=C{True}) - dump results as list followed by results names in nested outline; if False, only dump nested list - printResults - (default=C{True}) prints test output to stdout - failureTests - (default=C{False}) indicates if these tests are expected to fail parsing Returns: a (success, results) tuple, where success indicates that all tests succeeded (or failed if C{failureTests} is True), and the results contain a list of lines of each test's output Example:: number_expr = pyparsing_common.number.copy() result = number_expr.runTests(''' # unsigned integer 100 # negative integer -100 # float with scientific notation 6.02e23 # integer with scientific notation 1e-12 ''') print("Success" if result[0] else "Failed!") result = number_expr.runTests(''' # stray character 100Z # missing leading digit before '.' -.100 # too many '.' 3.14.159 ''', failureTests=True) print("Success" if result[0] else "Failed!") prints:: # unsigned integer 100 [100] # negative integer -100 [-100] # float with scientific notation 6.02e23 [6.02e+23] # integer with scientific notation 1e-12 [1e-12] Success # stray character 100Z ^ FAIL: Expected end of text (at char 3), (line:1, col:4) # missing leading digit before '.' -.100 ^ FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1) # too many '.' 3.14.159 ^ FAIL: Expected end of text (at char 4), (line:1, col:5) Success Each test string must be on a single line. If you want to test a string that spans multiple lines, create a test like this:: expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines") (Note that this is a raw string literal, you must include the leading 'r'.) """ if isinstance(tests, basestring): tests = list(map(str.strip, tests.rstrip().splitlines())) if isinstance(comment, basestring): comment = Literal(comment) allResults = [] comments = [] success = True for t in tests: if comment is not None and comment.matches(t, False) or (comments and (not t)): comments.append(t) continue if not t: continue out = ['\n'.join(comments), t] comments = [] try: t = t.replace('\\n', '\n') <DeepExtract> ParserElement.resetCache() if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: t = t.expandtabs() try: (loc, tokens) = self._parse(t, 0) if parseAll: loc = self.preParse(t, loc) se = Empty() + StringEnd() se._parse(t, loc) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: raise else: raise exc else: result = tokens </DeepExtract> out.append(result.dump(full=fullDump)) success = success and (not failureTests) except ParseBaseException as pe: fatal = '(FATAL)' if isinstance(pe, ParseFatalException) else '' if '\n' in t: out.append(line(pe.loc, t)) out.append(' ' * (col(pe.loc, t) - 1) + '^' + fatal) else: out.append(' ' * pe.loc + '^' + fatal) out.append('FAIL: ' + str(pe)) success = success and failureTests result = pe except Exception as exc: out.append('FAIL-EXCEPTION: ' + str(exc)) success = success and failureTests result = exc if printResults: if fullDump: out.append('') print('\n'.join(out)) allResults.append((t, result)) return (success, allResults)
def predict_log_proba(self, X): """Estimate log probability. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. Returns ------- C : ndarray of shape (n_samples, n_classes) Estimated log probabilities. """ (xp, _) = get_namespace(X) check_is_fitted(self) (xp, is_array_api) = get_namespace(X) decision = self.decision_function(X) if self.classes_.size == 2: proba = _expit(decision) prediction = xp.stack([1 - proba, proba], axis=1) else: prediction = softmax(decision) info = xp.finfo(prediction.dtype) if hasattr(info, 'smallest_normal'): smallest_normal = info.smallest_normal else: smallest_normal = info.tiny prediction[prediction == 0.0] += smallest_normal return xp.log(prediction)
def predict_log_proba(self, X): """Estimate log probability. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. Returns ------- C : ndarray of shape (n_samples, n_classes) Estimated log probabilities. """ (xp, _) = get_namespace(X) <DeepExtract> check_is_fitted(self) (xp, is_array_api) = get_namespace(X) decision = self.decision_function(X) if self.classes_.size == 2: proba = _expit(decision) prediction = xp.stack([1 - proba, proba], axis=1) else: prediction = softmax(decision) </DeepExtract> info = xp.finfo(prediction.dtype) if hasattr(info, 'smallest_normal'): smallest_normal = info.smallest_normal else: smallest_normal = info.tiny prediction[prediction == 0.0] += smallest_normal return xp.log(prediction)
def staged_decision_function(self, X): """Compute decision function of ``X`` for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ score : generator of ndarray of shape (n_samples, k) The decision function of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute. Binary classification is a special cases with ``k == 1``, otherwise ``k==n_classes``. For binary classification, values closer to -1 or 1 mean more like the first or second class in ``classes_``, respectively. """ check_is_fitted(self) X = self._validate_data(X, accept_sparse=['csr', 'csc'], ensure_2d=True, allow_nd=True, dtype=None, reset=False) n_classes = self.n_classes_ classes = self.classes_[:, np.newaxis] pred = None norm = 0.0 for (weight, estimator) in zip(self.estimator_weights_, self.estimators_): norm += weight if self.algorithm == 'SAMME.R': proba = estimator.predict_proba(X) np.clip(proba, np.finfo(proba.dtype).eps, None, out=proba) log_proba = np.log(proba) current_pred = (n_classes - 1) * (log_proba - 1.0 / n_classes * log_proba.sum(axis=1)[:, np.newaxis]) else: current_pred = estimator.predict(X) current_pred = (current_pred == classes).T * weight if pred is None: pred = current_pred else: pred += current_pred if n_classes == 2: tmp_pred = np.copy(pred) tmp_pred[:, 0] *= -1 yield (tmp_pred / norm).sum(axis=1) else: yield (pred / norm)
def staged_decision_function(self, X): """Compute decision function of ``X`` for each boosting iteration. This method allows monitoring (i.e. determine error on testing set) after each boosting iteration. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. Yields ------ score : generator of ndarray of shape (n_samples, k) The decision function of the input samples. The order of outputs is the same of that of the :term:`classes_` attribute. Binary classification is a special cases with ``k == 1``, otherwise ``k==n_classes``. For binary classification, values closer to -1 or 1 mean more like the first or second class in ``classes_``, respectively. """ check_is_fitted(self) <DeepExtract> X = self._validate_data(X, accept_sparse=['csr', 'csc'], ensure_2d=True, allow_nd=True, dtype=None, reset=False) </DeepExtract> n_classes = self.n_classes_ classes = self.classes_[:, np.newaxis] pred = None norm = 0.0 for (weight, estimator) in zip(self.estimator_weights_, self.estimators_): norm += weight if self.algorithm == 'SAMME.R': <DeepExtract> proba = estimator.predict_proba(X) np.clip(proba, np.finfo(proba.dtype).eps, None, out=proba) log_proba = np.log(proba) current_pred = (n_classes - 1) * (log_proba - 1.0 / n_classes * log_proba.sum(axis=1)[:, np.newaxis]) </DeepExtract> else: current_pred = estimator.predict(X) current_pred = (current_pred == classes).T * weight if pred is None: pred = current_pred else: pred += current_pred if n_classes == 2: tmp_pred = np.copy(pred) tmp_pred[:, 0] *= -1 yield (tmp_pred / norm).sum(axis=1) else: yield (pred / norm)
def predict_proba(self, X): """Evaluate the components' density for each sample. Parameters ---------- X : array-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- resp : array, shape (n_samples, n_components) Density of each Gaussian component for each sample in X. """ check_is_fitted(self) X = self._validate_data(X, reset=False) weighted_log_prob = self._estimate_weighted_log_prob(X) log_prob_norm = logsumexp(weighted_log_prob, axis=1) with np.errstate(under='ignore'): log_resp = weighted_log_prob - log_prob_norm[:, np.newaxis] (_, log_resp) = (log_prob_norm, log_resp) return np.exp(log_resp)
def predict_proba(self, X): """Evaluate the components' density for each sample. Parameters ---------- X : array-like of shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. Returns ------- resp : array, shape (n_samples, n_components) Density of each Gaussian component for each sample in X. """ check_is_fitted(self) X = self._validate_data(X, reset=False) <DeepExtract> weighted_log_prob = self._estimate_weighted_log_prob(X) log_prob_norm = logsumexp(weighted_log_prob, axis=1) with np.errstate(under='ignore'): log_resp = weighted_log_prob - log_prob_norm[:, np.newaxis] (_, log_resp) = (log_prob_norm, log_resp) </DeepExtract> return np.exp(log_resp)
def staged_score(self, X, y, sample_weight=None): """Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. y : array-like of shape (n_samples,) Labels for X. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Yields ------ z : float """ X = self._validate_data(X, accept_sparse=['csr', 'csc'], ensure_2d=True, allow_nd=True, dtype=None, reset=False) for y_pred in self.staged_predict(X): if is_classifier(self): yield accuracy_score(y, y_pred, sample_weight=sample_weight) else: yield r2_score(y, y_pred, sample_weight=sample_weight)
def staged_score(self, X, y, sample_weight=None): """Return staged scores for X, y. This generator method yields the ensemble score after each iteration of boosting and therefore allows monitoring, such as to determine the score on a test set after each boost. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Sparse matrix can be CSC, CSR, COO, DOK, or LIL. COO, DOK, and LIL are converted to CSR. y : array-like of shape (n_samples,) Labels for X. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Yields ------ z : float """ <DeepExtract> X = self._validate_data(X, accept_sparse=['csr', 'csc'], ensure_2d=True, allow_nd=True, dtype=None, reset=False) </DeepExtract> for y_pred in self.staged_predict(X): if is_classifier(self): yield accuracy_score(y, y_pred, sample_weight=sample_weight) else: yield r2_score(y, y_pred, sample_weight=sample_weight)
def fit(self, X, y=None): """Fit the imputer on `X` and return self. Parameters ---------- X : array-like, shape (n_samples, n_features) Input data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Fitted estimator. """ self._validate_params() self.random_state_ = getattr(self, 'random_state_', check_random_state(self.random_state)) if self.estimator is None: from ..linear_model import BayesianRidge self._estimator = BayesianRidge() else: self._estimator = clone(self.estimator) self.imputation_sequence_ = [] self.initial_imputer_ = None (X, Xt, mask_missing_values, complete_mask) = self._initial_imputation(X, in_fit=True) super()._fit_indicator(complete_mask) X_indicator = super()._transform_indicator(complete_mask) if self.max_iter == 0 or np.all(mask_missing_values): self.n_iter_ = 0 return super()._concatenate_indicator(Xt, X_indicator) if Xt.shape[1] == 1: self.n_iter_ = 0 return super()._concatenate_indicator(Xt, X_indicator) self._min_value = self._validate_limit(self.min_value, 'min', X.shape[1]) self._max_value = self._validate_limit(self.max_value, 'max', X.shape[1]) if not np.all(np.greater(self._max_value, self._min_value)): raise ValueError('One (or more) features have min_value >= max_value.') ordered_idx = self._get_ordered_idx(mask_missing_values) self.n_features_with_missing_ = len(ordered_idx) abs_corr_mat = self._get_abs_corr_mat(Xt) (n_samples, n_features) = Xt.shape if self.verbose > 0: print('[IterativeImputer] Completing matrix with shape %s' % (X.shape,)) start_t = time() if not self.sample_posterior: Xt_previous = Xt.copy() normalized_tol = self.tol * np.max(np.abs(X[~mask_missing_values])) for self.n_iter_ in range(1, self.max_iter + 1): if self.imputation_order == 'random': ordered_idx = self._get_ordered_idx(mask_missing_values) for feat_idx in ordered_idx: neighbor_feat_idx = self._get_neighbor_feat_idx(n_features, feat_idx, abs_corr_mat) (Xt, estimator) = self._impute_one_feature(Xt, mask_missing_values, feat_idx, neighbor_feat_idx, estimator=None, fit_mode=True) estimator_triplet = _ImputerTriplet(feat_idx, neighbor_feat_idx, estimator) self.imputation_sequence_.append(estimator_triplet) if self.verbose > 1: print('[IterativeImputer] Ending imputation round %d/%d, elapsed time %0.2f' % (self.n_iter_, self.max_iter, time() - start_t)) if not self.sample_posterior: inf_norm = np.linalg.norm(Xt - Xt_previous, ord=np.inf, axis=None) if self.verbose > 0: print('[IterativeImputer] Change: {}, scaled tolerance: {} '.format(inf_norm, normalized_tol)) if inf_norm < normalized_tol: if self.verbose > 0: print('[IterativeImputer] Early stopping criterion reached.') break Xt_previous = Xt.copy() else: if not self.sample_posterior: warnings.warn('[IterativeImputer] Early stopping criterion not reached.', ConvergenceWarning) _assign_where(Xt, X, cond=~mask_missing_values) return super()._concatenate_indicator(Xt, X_indicator) return self
def fit(self, X, y=None): """Fit the imputer on `X` and return self. Parameters ---------- X : array-like, shape (n_samples, n_features) Input data, where `n_samples` is the number of samples and `n_features` is the number of features. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Fitted estimator. """ <DeepExtract> self._validate_params() self.random_state_ = getattr(self, 'random_state_', check_random_state(self.random_state)) if self.estimator is None: from ..linear_model import BayesianRidge self._estimator = BayesianRidge() else: self._estimator = clone(self.estimator) self.imputation_sequence_ = [] self.initial_imputer_ = None (X, Xt, mask_missing_values, complete_mask) = self._initial_imputation(X, in_fit=True) super()._fit_indicator(complete_mask) X_indicator = super()._transform_indicator(complete_mask) if self.max_iter == 0 or np.all(mask_missing_values): self.n_iter_ = 0 return super()._concatenate_indicator(Xt, X_indicator) if Xt.shape[1] == 1: self.n_iter_ = 0 return super()._concatenate_indicator(Xt, X_indicator) self._min_value = self._validate_limit(self.min_value, 'min', X.shape[1]) self._max_value = self._validate_limit(self.max_value, 'max', X.shape[1]) if not np.all(np.greater(self._max_value, self._min_value)): raise ValueError('One (or more) features have min_value >= max_value.') ordered_idx = self._get_ordered_idx(mask_missing_values) self.n_features_with_missing_ = len(ordered_idx) abs_corr_mat = self._get_abs_corr_mat(Xt) (n_samples, n_features) = Xt.shape if self.verbose > 0: print('[IterativeImputer] Completing matrix with shape %s' % (X.shape,)) start_t = time() if not self.sample_posterior: Xt_previous = Xt.copy() normalized_tol = self.tol * np.max(np.abs(X[~mask_missing_values])) for self.n_iter_ in range(1, self.max_iter + 1): if self.imputation_order == 'random': ordered_idx = self._get_ordered_idx(mask_missing_values) for feat_idx in ordered_idx: neighbor_feat_idx = self._get_neighbor_feat_idx(n_features, feat_idx, abs_corr_mat) (Xt, estimator) = self._impute_one_feature(Xt, mask_missing_values, feat_idx, neighbor_feat_idx, estimator=None, fit_mode=True) estimator_triplet = _ImputerTriplet(feat_idx, neighbor_feat_idx, estimator) self.imputation_sequence_.append(estimator_triplet) if self.verbose > 1: print('[IterativeImputer] Ending imputation round %d/%d, elapsed time %0.2f' % (self.n_iter_, self.max_iter, time() - start_t)) if not self.sample_posterior: inf_norm = np.linalg.norm(Xt - Xt_previous, ord=np.inf, axis=None) if self.verbose > 0: print('[IterativeImputer] Change: {}, scaled tolerance: {} '.format(inf_norm, normalized_tol)) if inf_norm < normalized_tol: if self.verbose > 0: print('[IterativeImputer] Early stopping criterion reached.') break Xt_previous = Xt.copy() else: if not self.sample_posterior: warnings.warn('[IterativeImputer] Early stopping criterion not reached.', ConvergenceWarning) _assign_where(Xt, X, cond=~mask_missing_values) return super()._concatenate_indicator(Xt, X_indicator) </DeepExtract> return self
def _pandas_arff_parser(gzip_file, output_arrays_type, openml_columns_info, feature_names_to_select, target_names_to_select, read_csv_kwargs=None): """ARFF parser using `pandas.read_csv`. This parser uses the metadata fetched directly from OpenML and skips the metadata headers of ARFF file itself. The data is loaded as a CSV file. Parameters ---------- gzip_file : GzipFile instance The GZip compressed file with the ARFF formatted payload. output_arrays_type : {"numpy", "sparse", "pandas"} The type of the arrays that will be returned. The possibilities are: - `"numpy"`: both `X` and `y` will be NumPy arrays; - `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array; - `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a pandas Series or DataFrame. openml_columns_info : dict The information provided by OpenML regarding the columns of the ARFF file. feature_names_to_select : list of str A list of the feature names to be selected to build `X`. target_names_to_select : list of str A list of the target names to be selected to build `y`. read_csv_kwargs : dict, default=None Keyword arguments to pass to `pandas.read_csv`. It allows to overwrite the default options. Returns ------- X : {ndarray, sparse matrix, dataframe} The data matrix. y : {ndarray, dataframe, series} The target. frame : dataframe or None A dataframe containing both `X` and `y`. `None` if `output_array_type != "pandas"`. categories : list of str or None The names of the features that are categorical. `None` if `output_array_type == "pandas"`. """ import pandas as pd for line in gzip_file: if line.decode('utf-8').lower().startswith('@data'): break dtypes = {} for name in openml_columns_info: column_dtype = openml_columns_info[name]['data_type'] if column_dtype.lower() == 'integer': dtypes[name] = 'Int64' elif column_dtype.lower() == 'nominal': dtypes[name] = 'category' dtypes_positional = {col_idx: dtypes[name] for (col_idx, name) in enumerate(openml_columns_info) if name in dtypes} default_read_csv_kwargs = {'header': None, 'index_col': False, 'na_values': ['?'], 'comment': '%', 'quotechar': '"', 'skipinitialspace': True, 'escapechar': '\\', 'dtype': dtypes_positional} read_csv_kwargs = {**default_read_csv_kwargs, **(read_csv_kwargs or {})} frame = pd.read_csv(gzip_file, **read_csv_kwargs) try: frame.columns = [name for name in openml_columns_info] except ValueError as exc: raise pd.errors.ParserError('The number of columns provided by OpenML does not match the number of columns inferred by pandas when reading the file.') from exc columns_to_select = feature_names_to_select + target_names_to_select columns_to_keep = [col for col in frame.columns if col in columns_to_select] frame = frame[columns_to_keep] single_quote_pattern = re.compile("^'(?P<contents>.*)'$") def strip_single_quotes(input_string): match = re.search(single_quote_pattern, input_string) if match is None: return input_string return match.group('contents') categorical_columns = [name for (name, dtype) in frame.dtypes.items() if pd.api.types.is_categorical_dtype(dtype)] for col in categorical_columns: frame[col] = frame[col].cat.rename_categories(strip_single_quotes) X = frame[feature_names_to_select] if len(target_names_to_select) >= 2: y = frame[target_names_to_select] elif len(target_names_to_select) == 1: y = frame[target_names_to_select[0]] else: y = None (X, y) = (X, y) if output_arrays_type == 'pandas': return (X, y, frame, None) else: (X, y) = (X.to_numpy(), y.to_numpy()) categories = {name: dtype.categories.tolist() for (name, dtype) in frame.dtypes.items() if pd.api.types.is_categorical_dtype(dtype)} return (X, y, None, categories)
def _pandas_arff_parser(gzip_file, output_arrays_type, openml_columns_info, feature_names_to_select, target_names_to_select, read_csv_kwargs=None): """ARFF parser using `pandas.read_csv`. This parser uses the metadata fetched directly from OpenML and skips the metadata headers of ARFF file itself. The data is loaded as a CSV file. Parameters ---------- gzip_file : GzipFile instance The GZip compressed file with the ARFF formatted payload. output_arrays_type : {"numpy", "sparse", "pandas"} The type of the arrays that will be returned. The possibilities are: - `"numpy"`: both `X` and `y` will be NumPy arrays; - `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array; - `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a pandas Series or DataFrame. openml_columns_info : dict The information provided by OpenML regarding the columns of the ARFF file. feature_names_to_select : list of str A list of the feature names to be selected to build `X`. target_names_to_select : list of str A list of the target names to be selected to build `y`. read_csv_kwargs : dict, default=None Keyword arguments to pass to `pandas.read_csv`. It allows to overwrite the default options. Returns ------- X : {ndarray, sparse matrix, dataframe} The data matrix. y : {ndarray, dataframe, series} The target. frame : dataframe or None A dataframe containing both `X` and `y`. `None` if `output_array_type != "pandas"`. categories : list of str or None The names of the features that are categorical. `None` if `output_array_type == "pandas"`. """ import pandas as pd for line in gzip_file: if line.decode('utf-8').lower().startswith('@data'): break dtypes = {} for name in openml_columns_info: column_dtype = openml_columns_info[name]['data_type'] if column_dtype.lower() == 'integer': dtypes[name] = 'Int64' elif column_dtype.lower() == 'nominal': dtypes[name] = 'category' dtypes_positional = {col_idx: dtypes[name] for (col_idx, name) in enumerate(openml_columns_info) if name in dtypes} default_read_csv_kwargs = {'header': None, 'index_col': False, 'na_values': ['?'], 'comment': '%', 'quotechar': '"', 'skipinitialspace': True, 'escapechar': '\\', 'dtype': dtypes_positional} read_csv_kwargs = {**default_read_csv_kwargs, **(read_csv_kwargs or {})} frame = pd.read_csv(gzip_file, **read_csv_kwargs) try: frame.columns = [name for name in openml_columns_info] except ValueError as exc: raise pd.errors.ParserError('The number of columns provided by OpenML does not match the number of columns inferred by pandas when reading the file.') from exc columns_to_select = feature_names_to_select + target_names_to_select columns_to_keep = [col for col in frame.columns if col in columns_to_select] frame = frame[columns_to_keep] single_quote_pattern = re.compile("^'(?P<contents>.*)'$") def strip_single_quotes(input_string): match = re.search(single_quote_pattern, input_string) if match is None: return input_string return match.group('contents') categorical_columns = [name for (name, dtype) in frame.dtypes.items() if pd.api.types.is_categorical_dtype(dtype)] for col in categorical_columns: frame[col] = frame[col].cat.rename_categories(strip_single_quotes) <DeepExtract> X = frame[feature_names_to_select] if len(target_names_to_select) >= 2: y = frame[target_names_to_select] elif len(target_names_to_select) == 1: y = frame[target_names_to_select[0]] else: y = None (X, y) = (X, y) </DeepExtract> if output_arrays_type == 'pandas': return (X, y, frame, None) else: (X, y) = (X.to_numpy(), y.to_numpy()) categories = {name: dtype.categories.tolist() for (name, dtype) in frame.dtypes.items() if pd.api.types.is_categorical_dtype(dtype)} return (X, y, None, categories)
def _partial_fit(self, X, y, classes=None, _refit=False, sample_weight=None): """Actual implementation of Gaussian NB fitting. Parameters ---------- X : array-like of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. classes : array-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. _refit : bool, default=False If true, act as though this were the first time we called _partial_fit (ie, throw away any past fitting and start over). sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- self : object """ if _refit: self.classes_ = None first_call = _check_partial_fit_first_call(self, classes) (X, y) = self._validate_data(X, y, reset=first_call) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X) self.epsilon_ = self.var_smoothing * np.var(X, axis=0).max() if first_call: n_features = X.shape[1] n_classes = len(self.classes_) self.theta_ = np.zeros((n_classes, n_features)) self.var_ = np.zeros((n_classes, n_features)) self.class_count_ = np.zeros(n_classes, dtype=np.float64) if self.priors is not None: priors = np.asarray(self.priors) if len(priors) != n_classes: raise ValueError('Number of priors must match number of classes.') if not np.isclose(priors.sum(), 1.0): raise ValueError('The sum of the priors should be 1.') if (priors < 0).any(): raise ValueError('Priors must be non-negative.') self.class_prior_ = priors else: self.class_prior_ = np.zeros(len(self.classes_), dtype=np.float64) else: if X.shape[1] != self.theta_.shape[1]: msg = 'Number of features %d does not match previous data %d.' raise ValueError(msg % (X.shape[1], self.theta_.shape[1])) self.var_[:, :] -= self.epsilon_ classes = self.classes_ unique_y = np.unique(y) unique_y_in_classes = np.in1d(unique_y, classes) if not np.all(unique_y_in_classes): raise ValueError('The target label(s) %s in y do not exist in the initial classes %s' % (unique_y[~unique_y_in_classes], classes)) for y_i in unique_y: i = classes.searchsorted(y_i) X_i = X[y == y_i, :] if sample_weight is not None: sw_i = sample_weight[y == y_i] N_i = sw_i.sum() else: sw_i = None N_i = X_i.shape[0] if X_i.shape[0] == 0: (new_theta, new_sigma) = (self.theta_[i, :], self.var_[i, :]) if sw_i is not None: n_new = float(sw_i.sum()) if np.isclose(n_new, 0.0): (new_theta, new_sigma) = (self.theta_[i, :], self.var_[i, :]) new_mu = np.average(X_i, axis=0, weights=sw_i) new_var = np.average((X_i - new_mu) ** 2, axis=0, weights=sw_i) else: n_new = X_i.shape[0] new_var = np.var(X_i, axis=0) new_mu = np.mean(X_i, axis=0) if self.class_count_[i] == 0: (new_theta, new_sigma) = (new_mu, new_var) n_total = float(self.class_count_[i] + n_new) total_mu = (n_new * new_mu + self.class_count_[i] * self.theta_[i, :]) / n_total old_ssd = self.class_count_[i] * self.var_[i, :] new_ssd = n_new * new_var total_ssd = old_ssd + new_ssd + n_new * self.class_count_[i] / n_total * (self.theta_[i, :] - new_mu) ** 2 total_var = total_ssd / n_total (new_theta, new_sigma) = (total_mu, total_var) self.theta_[i, :] = new_theta self.var_[i, :] = new_sigma self.class_count_[i] += N_i self.var_[:, :] += self.epsilon_ if self.priors is None: self.class_prior_ = self.class_count_ / self.class_count_.sum() return self
def _partial_fit(self, X, y, classes=None, _refit=False, sample_weight=None): """Actual implementation of Gaussian NB fitting. Parameters ---------- X : array-like of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. classes : array-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. _refit : bool, default=False If true, act as though this were the first time we called _partial_fit (ie, throw away any past fitting and start over). sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- self : object """ if _refit: self.classes_ = None first_call = _check_partial_fit_first_call(self, classes) (X, y) = self._validate_data(X, y, reset=first_call) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X) self.epsilon_ = self.var_smoothing * np.var(X, axis=0).max() if first_call: n_features = X.shape[1] n_classes = len(self.classes_) self.theta_ = np.zeros((n_classes, n_features)) self.var_ = np.zeros((n_classes, n_features)) self.class_count_ = np.zeros(n_classes, dtype=np.float64) if self.priors is not None: priors = np.asarray(self.priors) if len(priors) != n_classes: raise ValueError('Number of priors must match number of classes.') if not np.isclose(priors.sum(), 1.0): raise ValueError('The sum of the priors should be 1.') if (priors < 0).any(): raise ValueError('Priors must be non-negative.') self.class_prior_ = priors else: self.class_prior_ = np.zeros(len(self.classes_), dtype=np.float64) else: if X.shape[1] != self.theta_.shape[1]: msg = 'Number of features %d does not match previous data %d.' raise ValueError(msg % (X.shape[1], self.theta_.shape[1])) self.var_[:, :] -= self.epsilon_ classes = self.classes_ unique_y = np.unique(y) unique_y_in_classes = np.in1d(unique_y, classes) if not np.all(unique_y_in_classes): raise ValueError('The target label(s) %s in y do not exist in the initial classes %s' % (unique_y[~unique_y_in_classes], classes)) for y_i in unique_y: i = classes.searchsorted(y_i) X_i = X[y == y_i, :] if sample_weight is not None: sw_i = sample_weight[y == y_i] N_i = sw_i.sum() else: sw_i = None N_i = X_i.shape[0] <DeepExtract> if X_i.shape[0] == 0: (new_theta, new_sigma) = (self.theta_[i, :], self.var_[i, :]) if sw_i is not None: n_new = float(sw_i.sum()) if np.isclose(n_new, 0.0): (new_theta, new_sigma) = (self.theta_[i, :], self.var_[i, :]) new_mu = np.average(X_i, axis=0, weights=sw_i) new_var = np.average((X_i - new_mu) ** 2, axis=0, weights=sw_i) else: n_new = X_i.shape[0] new_var = np.var(X_i, axis=0) new_mu = np.mean(X_i, axis=0) if self.class_count_[i] == 0: (new_theta, new_sigma) = (new_mu, new_var) n_total = float(self.class_count_[i] + n_new) total_mu = (n_new * new_mu + self.class_count_[i] * self.theta_[i, :]) / n_total old_ssd = self.class_count_[i] * self.var_[i, :] new_ssd = n_new * new_var total_ssd = old_ssd + new_ssd + n_new * self.class_count_[i] / n_total * (self.theta_[i, :] - new_mu) ** 2 total_var = total_ssd / n_total (new_theta, new_sigma) = (total_mu, total_var) </DeepExtract> self.theta_[i, :] = new_theta self.var_[i, :] = new_sigma self.class_count_[i] += N_i self.var_[:, :] += self.epsilon_ if self.priors is None: self.class_prior_ = self.class_count_ / self.class_count_.sum() return self
def score_samples(self, X): """Compute the log-likelihood of each sample. Parameters ---------- X : ndarray of shape (n_samples, n_features) The data. Returns ------- ll : ndarray of shape (n_samples,) Log-likelihood of each sample under the current model. """ check_is_fitted(self) X = self._validate_data(X, reset=False) Xr = X - self.mean_ check_is_fitted(self) n_features = self.components_.shape[1] if self.n_components == 0: precision = np.diag(1.0 / self.noise_variance_) if self.n_components == n_features: precision = linalg.inv(self.get_covariance()) components_ = self.components_ precision = np.dot(components_ / self.noise_variance_, components_.T) precision.flat[::len(precision) + 1] += 1.0 precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_)) precision /= self.noise_variance_[:, np.newaxis] precision /= -self.noise_variance_[np.newaxis, :] precision.flat[::len(precision) + 1] += 1.0 / self.noise_variance_ precision = precision n_features = X.shape[1] log_like = -0.5 * (Xr * np.dot(Xr, precision)).sum(axis=1) log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision)) return log_like
def score_samples(self, X): """Compute the log-likelihood of each sample. Parameters ---------- X : ndarray of shape (n_samples, n_features) The data. Returns ------- ll : ndarray of shape (n_samples,) Log-likelihood of each sample under the current model. """ check_is_fitted(self) X = self._validate_data(X, reset=False) Xr = X - self.mean_ <DeepExtract> check_is_fitted(self) n_features = self.components_.shape[1] if self.n_components == 0: precision = np.diag(1.0 / self.noise_variance_) if self.n_components == n_features: precision = linalg.inv(self.get_covariance()) components_ = self.components_ precision = np.dot(components_ / self.noise_variance_, components_.T) precision.flat[::len(precision) + 1] += 1.0 precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_)) precision /= self.noise_variance_[:, np.newaxis] precision /= -self.noise_variance_[np.newaxis, :] precision.flat[::len(precision) + 1] += 1.0 / self.noise_variance_ precision = precision </DeepExtract> n_features = X.shape[1] log_like = -0.5 * (Xr * np.dot(Xr, precision)).sum(axis=1) log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision)) return log_like
def transform(self, X): """Transform the data X according to the fitted NMF model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. """ check_is_fitted(self) X = self._validate_data(X, accept_sparse=('csr', 'csc'), dtype=[np.float64, np.float32], reset=False) with config_context(assume_finite=True): check_non_negative(X, 'NMF (input X)') self._check_params(X) if X.min() == 0 and self._beta_loss <= 0: raise ValueError('When beta_loss <= 0 and X contains zeros, the solver may diverge. Please add small values to X, or use a positive beta_loss.') (W, self.components_) = self._check_w_h(X, W, self.components_, False) (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) = self._compute_regularization(X) if self.solver == 'cd': (W, self.components_, n_iter) = _fit_coordinate_descent(X, W, self.components_, self.tol, self.max_iter, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H=False, verbose=self.verbose, shuffle=self.shuffle, random_state=self.random_state) elif self.solver == 'mu': (W, self.components_, n_iter, *_) = _fit_multiplicative_update(X, W, self.components_, self._beta_loss, self.max_iter, self.tol, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, False, self.verbose) else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iterations %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) (W, *_) = (W, self.components_, n_iter) return W
def transform(self, X): """Transform the data X according to the fitted NMF model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. """ check_is_fitted(self) X = self._validate_data(X, accept_sparse=('csr', 'csc'), dtype=[np.float64, np.float32], reset=False) with config_context(assume_finite=True): <DeepExtract> check_non_negative(X, 'NMF (input X)') self._check_params(X) if X.min() == 0 and self._beta_loss <= 0: raise ValueError('When beta_loss <= 0 and X contains zeros, the solver may diverge. Please add small values to X, or use a positive beta_loss.') (W, self.components_) = self._check_w_h(X, W, self.components_, False) (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) = self._compute_regularization(X) if self.solver == 'cd': (W, self.components_, n_iter) = _fit_coordinate_descent(X, W, self.components_, self.tol, self.max_iter, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H=False, verbose=self.verbose, shuffle=self.shuffle, random_state=self.random_state) elif self.solver == 'mu': (W, self.components_, n_iter, *_) = _fit_multiplicative_update(X, W, self.components_, self._beta_loss, self.max_iter, self.tol, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, False, self.verbose) else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iterations %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) (W, *_) = (W, self.components_, n_iter) </DeepExtract> return W
def indentedBlock(blockStatementExpr, indentStack, indent=True): """ Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=C{True}) A valid block must contain at least one C{blockStatement}. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group( funcDecl + func_body ) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << ( funcDef | assignment | identifier ) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] """ def checkPeerIndent(s, l, t): if l >= len(s): return s = s curCol = 1 if 0 < l < len(s) and s[l - 1] == '\n' else l - s.rfind('\n', 0, l) if curCol != indentStack[-1]: if curCol > indentStack[-1]: raise ParseFatalException(s, l, 'illegal nesting') raise ParseException(s, l, 'not a peer entry') def checkSubIndent(s, l, t): s = s curCol = 1 if 0 < l < len(s) and s[l - 1] == '\n' else l - s.rfind('\n', 0, l) if curCol > indentStack[-1]: indentStack.append(curCol) else: raise ParseException(s, l, 'not a subentry') def checkUnindent(s, l, t): if l >= len(s): return s = s curCol = 1 if 0 < l < len(s) and s[l - 1] == '\n' else l - s.rfind('\n', 0, l) if not (indentStack and curCol < indentStack[-1] and (curCol <= indentStack[-2])): raise ParseException(s, l, 'not an unindent') indentStack.pop() NL = OneOrMore(LineEnd().setWhitespaceChars('\t ').suppress()) INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT') PEER = Empty().setParseAction(checkPeerIndent).setName('') UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT') if indent: smExpr = Group(Optional(NL) + INDENT + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL)) + UNDENT) else: smExpr = Group(Optional(NL) + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL))) blockStatementExpr.ignore(_bslash + LineEnd()) return smExpr.setName('indented block')
def indentedBlock(blockStatementExpr, indentStack, indent=True): """ Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack (multiple statementWithIndentedBlock expressions within a single grammar should share a common indentStack) - indent - boolean indicating whether block must be indented beyond the the current level; set to False for block of left-most statements (default=C{True}) A valid block must contain at least one C{blockStatement}. Example:: data = ''' def A(z): A1 B = 100 G = A2 A2 A3 B def BB(a,b,c): BB1 def BBA(): bba1 bba2 bba3 C D def spam(x,y): def eggs(z): pass ''' indentStack = [1] stmt = Forward() identifier = Word(alphas, alphanums) funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":") func_body = indentedBlock(stmt, indentStack) funcDef = Group( funcDecl + func_body ) rvalue = Forward() funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")") rvalue << (funcCall | identifier | Word(nums)) assignment = Group(identifier + "=" + rvalue) stmt << ( funcDef | assignment | identifier ) module_body = OneOrMore(stmt) parseTree = module_body.parseString(data) parseTree.pprint() prints:: [['def', 'A', ['(', 'z', ')'], ':', [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]], 'B', ['def', 'BB', ['(', 'a', 'b', 'c', ')'], ':', [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]], 'C', 'D', ['def', 'spam', ['(', 'x', 'y', ')'], ':', [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]] """ def checkPeerIndent(s, l, t): if l >= len(s): return <DeepExtract> s = s curCol = 1 if 0 < l < len(s) and s[l - 1] == '\n' else l - s.rfind('\n', 0, l) </DeepExtract> if curCol != indentStack[-1]: if curCol > indentStack[-1]: raise ParseFatalException(s, l, 'illegal nesting') raise ParseException(s, l, 'not a peer entry') def checkSubIndent(s, l, t): <DeepExtract> s = s curCol = 1 if 0 < l < len(s) and s[l - 1] == '\n' else l - s.rfind('\n', 0, l) </DeepExtract> if curCol > indentStack[-1]: indentStack.append(curCol) else: raise ParseException(s, l, 'not a subentry') def checkUnindent(s, l, t): if l >= len(s): return <DeepExtract> s = s curCol = 1 if 0 < l < len(s) and s[l - 1] == '\n' else l - s.rfind('\n', 0, l) </DeepExtract> if not (indentStack and curCol < indentStack[-1] and (curCol <= indentStack[-2])): raise ParseException(s, l, 'not an unindent') indentStack.pop() NL = OneOrMore(LineEnd().setWhitespaceChars('\t ').suppress()) INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT') PEER = Empty().setParseAction(checkPeerIndent).setName('') UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT') if indent: smExpr = Group(Optional(NL) + INDENT + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL)) + UNDENT) else: smExpr = Group(Optional(NL) + OneOrMore(PEER + Group(blockStatementExpr) + Optional(NL))) blockStatementExpr.ignore(_bslash + LineEnd()) return smExpr.setName('indented block')
def _fit_stochastic(X, y, activations, deltas, coef_grads, intercept_grads, layer_units, incremental): params = self.coefs_ + self.intercepts_ if not incremental or not hasattr(self, '_optimizer'): if self.solver == 'sgd': self._optimizer = SGDOptimizer(params, self.learning_rate_init, self.learning_rate, self.momentum, self.nesterovs_momentum, self.power_t) elif self.solver == 'adam': self._optimizer = AdamOptimizer(params, self.learning_rate_init, self.beta_1, self.beta_2, self.epsilon) if self.early_stopping and incremental: raise ValueError('partial_fit does not support early_stopping=True') early_stopping = self.early_stopping if early_stopping: should_stratify = is_classifier(self) and self.n_outputs_ == 1 stratify = y if should_stratify else None (X, X_val, y, y_val) = train_test_split(X, y, random_state=self._random_state, test_size=self.validation_fraction, stratify=stratify) if is_classifier(self): y_val = self._label_binarizer.inverse_transform(y_val) else: X_val = None y_val = None n_samples = X.shape[0] sample_idx = np.arange(n_samples, dtype=int) if self.batch_size == 'auto': batch_size = min(200, n_samples) else: if self.batch_size > n_samples: warnings.warn('Got `batch_size` less than 1 or larger than sample size. It is going to be clipped') batch_size = np.clip(self.batch_size, 1, n_samples) try: self.n_iter_ = 0 for it in range(self.max_iter): if self.shuffle: sample_idx = shuffle(sample_idx, random_state=self._random_state) accumulated_loss = 0.0 for batch_slice in gen_batches(n_samples, batch_size): if self.shuffle: X_batch = _safe_indexing(X, sample_idx[batch_slice]) y_batch = y[sample_idx[batch_slice]] else: X_batch = X[batch_slice] y_batch = y[batch_slice] activations[0] = X_batch n_samples = X_batch.shape[0] activations = self._forward_pass(activations) loss_func_name = self.loss if loss_func_name == 'log_loss' and self.out_activation_ == 'logistic': loss_func_name = 'binary_log_loss' loss = LOSS_FUNCTIONS[loss_func_name](y_batch, activations[-1]) values = 0 for s in self.coefs_: s = s.ravel() values += np.dot(s, s) loss += 0.5 * self.alpha * values / n_samples last = self.n_layers_ - 2 deltas[last] = activations[-1] - y_batch self._compute_loss_grad(last, n_samples, activations, deltas, coef_grads, intercept_grads) inplace_derivative = DERIVATIVES[self.activation] for i in range(self.n_layers_ - 2, 0, -1): deltas[i - 1] = safe_sparse_dot(deltas[i], self.coefs_[i].T) inplace_derivative(activations[i], deltas[i - 1]) self._compute_loss_grad(i - 1, n_samples, activations, deltas, coef_grads, intercept_grads) (batch_loss, coef_grads, intercept_grads) = (loss, coef_grads, intercept_grads) accumulated_loss += batch_loss * (batch_slice.stop - batch_slice.start) grads = coef_grads + intercept_grads self._optimizer.update_params(params, grads) self.n_iter_ += 1 self.loss_ = accumulated_loss / X.shape[0] self.t_ += n_samples self.loss_curve_.append(self.loss_) if self.verbose: print('Iteration %d, loss = %.8f' % (self.n_iter_, self.loss_)) if early_stopping: self.validation_scores_.append(self._score(X_val, y_val)) if self.verbose: print('Validation score: %f' % self.validation_scores_[-1]) last_valid_score = self.validation_scores_[-1] if last_valid_score < self.best_validation_score_ + self.tol: self._no_improvement_count += 1 else: self._no_improvement_count = 0 if last_valid_score > self.best_validation_score_: self.best_validation_score_ = last_valid_score self._best_coefs = [c.copy() for c in self.coefs_] self._best_intercepts = [i.copy() for i in self.intercepts_] else: if self.loss_curve_[-1] > self.best_loss_ - self.tol: self._no_improvement_count += 1 else: self._no_improvement_count = 0 if self.loss_curve_[-1] < self.best_loss_: self.best_loss_ = self.loss_curve_[-1] self._optimizer.iteration_ends(self.t_) if self._no_improvement_count > self.n_iter_no_change: if early_stopping: msg = 'Validation score did not improve more than tol=%f for %d consecutive epochs.' % (self.tol, self.n_iter_no_change) else: msg = 'Training loss did not improve more than tol=%f for %d consecutive epochs.' % (self.tol, self.n_iter_no_change) is_stopping = self._optimizer.trigger_stopping(msg, self.verbose) if is_stopping: break else: self._no_improvement_count = 0 if incremental: break if self.n_iter_ == self.max_iter: warnings.warn("Stochastic Optimizer: Maximum iterations (%d) reached and the optimization hasn't converged yet." % self.max_iter, ConvergenceWarning) except KeyboardInterrupt: warnings.warn('Training interrupted by user.') if early_stopping: self.coefs_ = self._best_coefs self.intercepts_ = self._best_intercepts self.validation_scores_ = self.validation_scores_
def _fit_stochastic(X, y, activations, deltas, coef_grads, intercept_grads, layer_units, incremental): params = self.coefs_ + self.intercepts_ if not incremental or not hasattr(self, '_optimizer'): if self.solver == 'sgd': self._optimizer = SGDOptimizer(params, self.learning_rate_init, self.learning_rate, self.momentum, self.nesterovs_momentum, self.power_t) elif self.solver == 'adam': self._optimizer = AdamOptimizer(params, self.learning_rate_init, self.beta_1, self.beta_2, self.epsilon) if self.early_stopping and incremental: raise ValueError('partial_fit does not support early_stopping=True') early_stopping = self.early_stopping if early_stopping: should_stratify = is_classifier(self) and self.n_outputs_ == 1 stratify = y if should_stratify else None (X, X_val, y, y_val) = train_test_split(X, y, random_state=self._random_state, test_size=self.validation_fraction, stratify=stratify) if is_classifier(self): y_val = self._label_binarizer.inverse_transform(y_val) else: X_val = None y_val = None n_samples = X.shape[0] sample_idx = np.arange(n_samples, dtype=int) if self.batch_size == 'auto': batch_size = min(200, n_samples) else: if self.batch_size > n_samples: warnings.warn('Got `batch_size` less than 1 or larger than sample size. It is going to be clipped') batch_size = np.clip(self.batch_size, 1, n_samples) try: self.n_iter_ = 0 for it in range(self.max_iter): if self.shuffle: sample_idx = shuffle(sample_idx, random_state=self._random_state) accumulated_loss = 0.0 for batch_slice in gen_batches(n_samples, batch_size): if self.shuffle: X_batch = _safe_indexing(X, sample_idx[batch_slice]) y_batch = y[sample_idx[batch_slice]] else: X_batch = X[batch_slice] y_batch = y[batch_slice] activations[0] = X_batch <DeepExtract> n_samples = X_batch.shape[0] activations = self._forward_pass(activations) loss_func_name = self.loss if loss_func_name == 'log_loss' and self.out_activation_ == 'logistic': loss_func_name = 'binary_log_loss' loss = LOSS_FUNCTIONS[loss_func_name](y_batch, activations[-1]) values = 0 for s in self.coefs_: s = s.ravel() values += np.dot(s, s) loss += 0.5 * self.alpha * values / n_samples last = self.n_layers_ - 2 deltas[last] = activations[-1] - y_batch self._compute_loss_grad(last, n_samples, activations, deltas, coef_grads, intercept_grads) inplace_derivative = DERIVATIVES[self.activation] for i in range(self.n_layers_ - 2, 0, -1): deltas[i - 1] = safe_sparse_dot(deltas[i], self.coefs_[i].T) inplace_derivative(activations[i], deltas[i - 1]) self._compute_loss_grad(i - 1, n_samples, activations, deltas, coef_grads, intercept_grads) (batch_loss, coef_grads, intercept_grads) = (loss, coef_grads, intercept_grads) </DeepExtract> accumulated_loss += batch_loss * (batch_slice.stop - batch_slice.start) grads = coef_grads + intercept_grads self._optimizer.update_params(params, grads) self.n_iter_ += 1 self.loss_ = accumulated_loss / X.shape[0] self.t_ += n_samples self.loss_curve_.append(self.loss_) if self.verbose: print('Iteration %d, loss = %.8f' % (self.n_iter_, self.loss_)) <DeepExtract> if early_stopping: self.validation_scores_.append(self._score(X_val, y_val)) if self.verbose: print('Validation score: %f' % self.validation_scores_[-1]) last_valid_score = self.validation_scores_[-1] if last_valid_score < self.best_validation_score_ + self.tol: self._no_improvement_count += 1 else: self._no_improvement_count = 0 if last_valid_score > self.best_validation_score_: self.best_validation_score_ = last_valid_score self._best_coefs = [c.copy() for c in self.coefs_] self._best_intercepts = [i.copy() for i in self.intercepts_] else: if self.loss_curve_[-1] > self.best_loss_ - self.tol: self._no_improvement_count += 1 else: self._no_improvement_count = 0 if self.loss_curve_[-1] < self.best_loss_: self.best_loss_ = self.loss_curve_[-1] </DeepExtract> self._optimizer.iteration_ends(self.t_) if self._no_improvement_count > self.n_iter_no_change: if early_stopping: msg = 'Validation score did not improve more than tol=%f for %d consecutive epochs.' % (self.tol, self.n_iter_no_change) else: msg = 'Training loss did not improve more than tol=%f for %d consecutive epochs.' % (self.tol, self.n_iter_no_change) is_stopping = self._optimizer.trigger_stopping(msg, self.verbose) if is_stopping: break else: self._no_improvement_count = 0 if incremental: break if self.n_iter_ == self.max_iter: warnings.warn("Stochastic Optimizer: Maximum iterations (%d) reached and the optimization hasn't converged yet." % self.max_iter, ConvergenceWarning) except KeyboardInterrupt: warnings.warn('Training interrupted by user.') if early_stopping: self.coefs_ = self._best_coefs self.intercepts_ = self._best_intercepts self.validation_scores_ = self.validation_scores_
def predict(self, X): """Predict the class labels for the provided data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed' Test samples. Returns ------- y : ndarray of shape (n_queries,) or (n_queries, n_outputs) Class labels for each data sample. """ check_is_fitted(self, '_fit_method') if self.weights == 'uniform': if self._fit_method == 'brute' and ArgKminClassMode.is_usable_for(X, self._fit_X, self.metric): check_is_fitted(self, '_fit_method') if self.weights == 'uniform': (metric, metric_kwargs) = _adjusted_metric(metric=self.metric, metric_kwargs=self.metric_params, p=self.p) if self._fit_method == 'brute' and ArgKminClassMode.is_usable_for(X, self._fit_X, metric) and (not self.outputs_2d_): if self.metric == 'precomputed': X = _check_precomputed(X) else: X = self._validate_data(X, accept_sparse='csr', reset=False, order='C') probabilities = ArgKminClassMode.compute(X, self._fit_X, k=self.n_neighbors, weights=self.weights, labels=self._y, unique_labels=self.classes_, metric=metric, metric_kwargs=metric_kwargs, strategy='parallel_on_X') probabilities = probabilities neigh_ind = self.kneighbors(X, return_distance=False) neigh_dist = None else: (neigh_dist, neigh_ind) = self.kneighbors(X) classes_ = self.classes_ _y = self._y if not self.outputs_2d_: _y = self._y.reshape((-1, 1)) classes_ = [self.classes_] n_queries = _num_samples(X) weights = _get_weights(neigh_dist, self.weights) if weights is None: weights = np.ones_like(neigh_ind) all_rows = np.arange(n_queries) probabilities = [] for (k, classes_k) in enumerate(classes_): pred_labels = _y[:, k][neigh_ind] proba_k = np.zeros((n_queries, classes_k.size)) for (i, idx) in enumerate(pred_labels.T): proba_k[all_rows, idx] += weights[:, i] normalizer = proba_k.sum(axis=1)[:, np.newaxis] normalizer[normalizer == 0.0] = 1.0 proba_k /= normalizer probabilities.append(proba_k) if not self.outputs_2d_: probabilities = probabilities[0] probabilities = probabilities if self.outputs_2d_: return np.stack([self.classes_[idx][np.argmax(probas, axis=1)] for (idx, probas) in enumerate(probabilities)], axis=1) return self.classes_[np.argmax(probabilities, axis=1)] neigh_ind = self.kneighbors(X, return_distance=False) neigh_dist = None else: (neigh_dist, neigh_ind) = self.kneighbors(X) classes_ = self.classes_ _y = self._y if not self.outputs_2d_: _y = self._y.reshape((-1, 1)) classes_ = [self.classes_] n_outputs = len(classes_) n_queries = _num_samples(X) weights = _get_weights(neigh_dist, self.weights) y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype) for (k, classes_k) in enumerate(classes_): if weights is None: (mode, _) = _mode(_y[neigh_ind, k], axis=1) else: (mode, _) = weighted_mode(_y[neigh_ind, k], weights, axis=1) mode = np.asarray(mode.ravel(), dtype=np.intp) y_pred[:, k] = classes_k.take(mode) if not self.outputs_2d_: y_pred = y_pred.ravel() return y_pred
def predict(self, X): """Predict the class labels for the provided data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_queries, n_features), or (n_queries, n_indexed) if metric == 'precomputed' Test samples. Returns ------- y : ndarray of shape (n_queries,) or (n_queries, n_outputs) Class labels for each data sample. """ check_is_fitted(self, '_fit_method') if self.weights == 'uniform': if self._fit_method == 'brute' and ArgKminClassMode.is_usable_for(X, self._fit_X, self.metric): <DeepExtract> check_is_fitted(self, '_fit_method') if self.weights == 'uniform': (metric, metric_kwargs) = _adjusted_metric(metric=self.metric, metric_kwargs=self.metric_params, p=self.p) if self._fit_method == 'brute' and ArgKminClassMode.is_usable_for(X, self._fit_X, metric) and (not self.outputs_2d_): if self.metric == 'precomputed': X = _check_precomputed(X) else: X = self._validate_data(X, accept_sparse='csr', reset=False, order='C') probabilities = ArgKminClassMode.compute(X, self._fit_X, k=self.n_neighbors, weights=self.weights, labels=self._y, unique_labels=self.classes_, metric=metric, metric_kwargs=metric_kwargs, strategy='parallel_on_X') probabilities = probabilities neigh_ind = self.kneighbors(X, return_distance=False) neigh_dist = None else: (neigh_dist, neigh_ind) = self.kneighbors(X) classes_ = self.classes_ _y = self._y if not self.outputs_2d_: _y = self._y.reshape((-1, 1)) classes_ = [self.classes_] n_queries = _num_samples(X) weights = _get_weights(neigh_dist, self.weights) if weights is None: weights = np.ones_like(neigh_ind) all_rows = np.arange(n_queries) probabilities = [] for (k, classes_k) in enumerate(classes_): pred_labels = _y[:, k][neigh_ind] proba_k = np.zeros((n_queries, classes_k.size)) for (i, idx) in enumerate(pred_labels.T): proba_k[all_rows, idx] += weights[:, i] normalizer = proba_k.sum(axis=1)[:, np.newaxis] normalizer[normalizer == 0.0] = 1.0 proba_k /= normalizer probabilities.append(proba_k) if not self.outputs_2d_: probabilities = probabilities[0] probabilities = probabilities </DeepExtract> if self.outputs_2d_: return np.stack([self.classes_[idx][np.argmax(probas, axis=1)] for (idx, probas) in enumerate(probabilities)], axis=1) return self.classes_[np.argmax(probabilities, axis=1)] neigh_ind = self.kneighbors(X, return_distance=False) neigh_dist = None else: (neigh_dist, neigh_ind) = self.kneighbors(X) classes_ = self.classes_ _y = self._y if not self.outputs_2d_: _y = self._y.reshape((-1, 1)) classes_ = [self.classes_] n_outputs = len(classes_) n_queries = _num_samples(X) weights = _get_weights(neigh_dist, self.weights) y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype) for (k, classes_k) in enumerate(classes_): if weights is None: (mode, _) = _mode(_y[neigh_ind, k], axis=1) else: (mode, _) = weighted_mode(_y[neigh_ind, k], weights, axis=1) mode = np.asarray(mode.ravel(), dtype=np.intp) y_pred[:, k] = classes_k.take(mode) if not self.outputs_2d_: y_pred = y_pred.ravel() return y_pred
def _fit_inverse_transform(self, X_transformed, X): if hasattr(X, 'tocsr'): raise NotImplementedError('Inverse transform not implemented for sparse matrices!') n_samples = X_transformed.shape[0] if callable(self.kernel): params = self.kernel_params or {} else: params = {'gamma': self.gamma, 'degree': self.degree, 'coef0': self.coef0} K = pairwise_kernels(X_transformed, Y, metric=self.kernel, filter_params=True, n_jobs=self.n_jobs, **params) K.flat[::n_samples + 1] += self.alpha self.dual_coef_ = linalg.solve(K, X, assume_a='pos', overwrite_a=True) self.X_transformed_fit_ = X_transformed
def _fit_inverse_transform(self, X_transformed, X): if hasattr(X, 'tocsr'): raise NotImplementedError('Inverse transform not implemented for sparse matrices!') n_samples = X_transformed.shape[0] <DeepExtract> if callable(self.kernel): params = self.kernel_params or {} else: params = {'gamma': self.gamma, 'degree': self.degree, 'coef0': self.coef0} K = pairwise_kernels(X_transformed, Y, metric=self.kernel, filter_params=True, n_jobs=self.n_jobs, **params) </DeepExtract> K.flat[::n_samples + 1] += self.alpha self.dual_coef_ = linalg.solve(K, X, assume_a='pos', overwrite_a=True) self.X_transformed_fit_ = X_transformed
def fit_single(solver, X, y, penalty='l2', single_target=True, C=1, max_iter=10, skip_slow=False, dtype=np.float64): if skip_slow and solver == 'lightning' and (penalty == 'l1'): print('skip_slowping l1 logistic regression with solver lightning.') return print('Solving %s logistic regression with penalty %s, solver %s.' % ('binary' if single_target else 'multinomial', penalty, solver)) if solver == 'lightning': from lightning.classification import SAGAClassifier if single_target or solver not in ['sag', 'saga']: multi_class = 'ovr' else: multi_class = 'multinomial' X = X.astype(dtype) y = y.astype(dtype) (X_train, X_test, y_train, y_test) = train_test_split(X, y, random_state=42, stratify=y) n_samples = X_train.shape[0] n_classes = np.unique(y_train).shape[0] test_scores = [1] train_scores = [1] accuracies = [1 / n_classes] times = [0] if penalty == 'l2': alpha = 1.0 / (C * n_samples) beta = 0 lightning_penalty = None else: alpha = 0.0 beta = 1.0 / (C * n_samples) lightning_penalty = 'l1' for this_max_iter in range(1, max_iter + 1, 2): print('[%s, %s, %s] Max iter: %s' % ('binary' if single_target else 'multinomial', penalty, solver, this_max_iter)) if solver == 'lightning': lr = SAGAClassifier(loss='log', alpha=alpha, beta=beta, penalty=lightning_penalty, tol=-1, max_iter=this_max_iter) else: lr = LogisticRegression(solver=solver, multi_class=multi_class, C=C, penalty=penalty, fit_intercept=False, tol=0, max_iter=this_max_iter, random_state=42) X_train.max() t0 = time.clock() lr.fit(X_train, y_train) train_time = time.clock() - t0 scores = [] for (X, y) in [(X_train, y_train), (X_test, y_test)]: try: y_pred = lr.predict_proba(X) except NotImplementedError: pred = safe_sparse_dot(X, lr.coef_.T) if hasattr(lr, 'intercept_'): pred += lr.intercept_ y_pred = softmax(pred) score = log_loss(y, y_pred, normalize=False) / n_samples score += 0.5 * alpha * np.sum(lr.coef_ ** 2) + beta * np.sum(np.abs(lr.coef_)) scores.append(score) (train_score, test_score) = tuple(scores) y_pred = lr.predict(X_test) accuracy = np.sum(y_pred == y_test) / y_test.shape[0] test_scores.append(test_score) train_scores.append(train_score) accuracies.append(accuracy) times.append(train_time) return (lr, times, train_scores, test_scores, accuracies)
def fit_single(solver, X, y, penalty='l2', single_target=True, C=1, max_iter=10, skip_slow=False, dtype=np.float64): if skip_slow and solver == 'lightning' and (penalty == 'l1'): print('skip_slowping l1 logistic regression with solver lightning.') return print('Solving %s logistic regression with penalty %s, solver %s.' % ('binary' if single_target else 'multinomial', penalty, solver)) if solver == 'lightning': from lightning.classification import SAGAClassifier if single_target or solver not in ['sag', 'saga']: multi_class = 'ovr' else: multi_class = 'multinomial' X = X.astype(dtype) y = y.astype(dtype) (X_train, X_test, y_train, y_test) = train_test_split(X, y, random_state=42, stratify=y) n_samples = X_train.shape[0] n_classes = np.unique(y_train).shape[0] test_scores = [1] train_scores = [1] accuracies = [1 / n_classes] times = [0] if penalty == 'l2': alpha = 1.0 / (C * n_samples) beta = 0 lightning_penalty = None else: alpha = 0.0 beta = 1.0 / (C * n_samples) lightning_penalty = 'l1' for this_max_iter in range(1, max_iter + 1, 2): print('[%s, %s, %s] Max iter: %s' % ('binary' if single_target else 'multinomial', penalty, solver, this_max_iter)) if solver == 'lightning': lr = SAGAClassifier(loss='log', alpha=alpha, beta=beta, penalty=lightning_penalty, tol=-1, max_iter=this_max_iter) else: lr = LogisticRegression(solver=solver, multi_class=multi_class, C=C, penalty=penalty, fit_intercept=False, tol=0, max_iter=this_max_iter, random_state=42) X_train.max() t0 = time.clock() lr.fit(X_train, y_train) train_time = time.clock() - t0 scores = [] for (X, y) in [(X_train, y_train), (X_test, y_test)]: try: y_pred = lr.predict_proba(X) except NotImplementedError: <DeepExtract> pred = safe_sparse_dot(X, lr.coef_.T) if hasattr(lr, 'intercept_'): pred += lr.intercept_ y_pred = softmax(pred) </DeepExtract> score = log_loss(y, y_pred, normalize=False) / n_samples score += 0.5 * alpha * np.sum(lr.coef_ ** 2) + beta * np.sum(np.abs(lr.coef_)) scores.append(score) (train_score, test_score) = tuple(scores) y_pred = lr.predict(X_test) accuracy = np.sum(y_pred == y_test) / y_test.shape[0] test_scores.append(test_score) train_scores.append(train_score) accuracies.append(accuracy) times.append(train_time) return (lr, times, train_scores, test_scores, accuracies)
def locally_linear_embedding(X, *, n_neighbors, n_components, reg=0.001, eigen_solver='auto', tol=1e-06, max_iter=100, method='standard', hessian_tol=0.0001, modified_tol=1e-12, random_state=None, n_jobs=None): """Perform a Locally Linear Embedding analysis on the data. Read more in the :ref:`User Guide <locally_linear_embedding>`. Parameters ---------- X : {array-like, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a numpy array or a NearestNeighbors object. n_neighbors : int Number of neighbors to consider for each point. n_components : int Number of coordinates for the manifold. reg : float, default=1e-3 Regularization constant, multiplies the trace of the local covariance matrix of the distances. eigen_solver : {'auto', 'arpack', 'dense'}, default='auto' auto : algorithm will attempt to choose the best method for input data arpack : use arnoldi iteration in shift-invert mode. For this method, M may be a dense matrix, sparse matrix, or general linear operator. Warning: ARPACK can be unstable for some problems. It is best to try several random seeds in order to check results. dense : use standard dense matrix operations for the eigenvalue decomposition. For this method, M must be an array or matrix type. This method should be avoided for large problems. tol : float, default=1e-6 Tolerance for 'arpack' method Not used if eigen_solver=='dense'. max_iter : int, default=100 Maximum number of iterations for the arpack solver. method : {'standard', 'hessian', 'modified', 'ltsa'}, default='standard' standard : use the standard locally linear embedding algorithm. see reference [1]_ hessian : use the Hessian eigenmap method. This method requires n_neighbors > n_components * (1 + (n_components + 1) / 2. see reference [2]_ modified : use the modified locally linear embedding algorithm. see reference [3]_ ltsa : use local tangent space alignment algorithm see reference [4]_ hessian_tol : float, default=1e-4 Tolerance for Hessian eigenmapping method. Only used if method == 'hessian'. modified_tol : float, default=1e-12 Tolerance for modified LLE method. Only used if method == 'modified'. random_state : int, RandomState instance, default=None Determines the random number generator when ``solver`` == 'arpack'. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. n_jobs : int or None, default=None The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- Y : array-like, shape [n_samples, n_components] Embedding vectors. squared_error : float Reconstruction error for the embedding vectors. Equivalent to ``norm(Y - W Y, 'fro')**2``, where W are the reconstruction weights. References ---------- .. [1] Roweis, S. & Saul, L. Nonlinear dimensionality reduction by locally linear embedding. Science 290:2323 (2000). .. [2] Donoho, D. & Grimes, C. Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data. Proc Natl Acad Sci U S A. 100:5591 (2003). .. [3] `Zhang, Z. & Wang, J. MLLE: Modified Locally Linear Embedding Using Multiple Weights. <https://citeseerx.ist.psu.edu/doc_view/pid/0b060fdbd92cbcc66b383bcaa9ba5e5e624d7ee3>`_ .. [4] Zhang, Z. & Zha, H. Principal manifolds and nonlinear dimensionality reduction via tangent space alignment. Journal of Shanghai Univ. 8:406 (2004) """ if eigen_solver not in ('auto', 'arpack', 'dense'): raise ValueError("unrecognized eigen_solver '%s'" % eigen_solver) if method not in ('standard', 'hessian', 'modified', 'ltsa'): raise ValueError("unrecognized method '%s'" % method) nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs) nbrs.fit(X) X = nbrs._fit_X (N, d_in) = X.shape if n_components > d_in: raise ValueError('output dimension must be less than or equal to input dimension') if n_neighbors >= N: raise ValueError('Expected n_neighbors <= n_samples, but n_samples = %d, n_neighbors = %d' % (N, n_neighbors)) if n_neighbors <= 0: raise ValueError('n_neighbors must be positive') M_sparse = eigen_solver != 'dense' if method == 'standard': knn = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs).fit(nbrs) nbrs = knn._fit_X n_samples = knn.n_samples_fit_ ind = knn.kneighbors(nbrs, return_distance=False)[:, 1:] data = barycenter_weights(nbrs, nbrs, ind, reg=reg) indptr = np.arange(0, n_samples * n_neighbors + 1, n_neighbors) W = csr_matrix((data.ravel(), ind.ravel(), indptr), shape=(n_samples, n_samples)) if M_sparse: M = eye(*W.shape, format=W.format) - W M = (M.T * M).tocsr() else: M = (W.T * W - W.T - W).toarray() M.flat[::M.shape[0] + 1] += 1 elif method == 'hessian': dp = n_components * (n_components + 1) // 2 if n_neighbors <= n_components + dp: raise ValueError("for method='hessian', n_neighbors must be greater than [n_components * (n_components + 3) / 2]") neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) neighbors = neighbors[:, 1:] Yi = np.empty((n_neighbors, 1 + n_components + dp), dtype=np.float64) Yi[:, 0] = 1 M = np.zeros((N, N), dtype=np.float64) use_svd = n_neighbors > d_in for i in range(N): Gi = X[neighbors[i]] Gi -= Gi.mean(0) if use_svd: U = svd(Gi, full_matrices=0)[0] else: Ci = np.dot(Gi, Gi.T) U = _eigh(Ci)[1][:, ::-1] Yi[:, 1:1 + n_components] = U[:, :n_components] j = 1 + n_components for k in range(n_components): Yi[:, j:j + n_components - k] = U[:, k:k + 1] * U[:, k:n_components] j += n_components - k (Q, R) = qr(Yi) w = Q[:, n_components + 1:] S = w.sum(0) S[np.where(abs(S) < hessian_tol)] = 1 w /= S (nbrs_x, nbrs_y) = np.meshgrid(neighbors[i], neighbors[i]) M[nbrs_x, nbrs_y] += np.dot(w, w.T) if M_sparse: M = csr_matrix(M) elif method == 'modified': if n_neighbors < n_components: raise ValueError('modified LLE requires n_neighbors >= n_components') neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) neighbors = neighbors[:, 1:] V = np.zeros((N, n_neighbors, n_neighbors)) nev = min(d_in, n_neighbors) evals = np.zeros([N, nev]) use_svd = n_neighbors > d_in if use_svd: for i in range(N): X_nbrs = X[neighbors[i]] - X[i] (V[i], evals[i], _) = svd(X_nbrs, full_matrices=True) evals **= 2 else: for i in range(N): X_nbrs = X[neighbors[i]] - X[i] C_nbrs = np.dot(X_nbrs, X_nbrs.T) (evi, vi) = _eigh(C_nbrs) evals[i] = evi[::-1] V[i] = vi[:, ::-1] reg = 0.001 * evals.sum(1) tmp = np.dot(V.transpose(0, 2, 1), np.ones(n_neighbors)) tmp[:, :nev] /= evals + reg[:, None] tmp[:, nev:] /= reg[:, None] w_reg = np.zeros((N, n_neighbors)) for i in range(N): w_reg[i] = np.dot(V[i], tmp[i]) w_reg /= w_reg.sum(1)[:, None] rho = evals[:, n_components:].sum(1) / evals[:, :n_components].sum(1) eta = np.median(rho) s_range = np.zeros(N, dtype=int) evals_cumsum = stable_cumsum(evals, 1) eta_range = evals_cumsum[:, -1:] / evals_cumsum[:, :-1] - 1 for i in range(N): s_range[i] = np.searchsorted(eta_range[i, ::-1], eta) s_range += n_neighbors - nev M = np.zeros((N, N), dtype=np.float64) for i in range(N): s_i = s_range[i] Vi = V[i, :, n_neighbors - s_i:] alpha_i = np.linalg.norm(Vi.sum(0)) / np.sqrt(s_i) h = np.full(s_i, alpha_i) - np.dot(Vi.T, np.ones(n_neighbors)) norm_h = np.linalg.norm(h) if norm_h < modified_tol: h *= 0 else: h /= norm_h Wi = Vi - 2 * np.outer(np.dot(Vi, h), h) + (1 - alpha_i) * w_reg[i, :, None] (nbrs_x, nbrs_y) = np.meshgrid(neighbors[i], neighbors[i]) M[nbrs_x, nbrs_y] += np.dot(Wi, Wi.T) Wi_sum1 = Wi.sum(1) M[i, neighbors[i]] -= Wi_sum1 M[neighbors[i], i] -= Wi_sum1 M[i, i] += s_i if M_sparse: M = csr_matrix(M) elif method == 'ltsa': neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) neighbors = neighbors[:, 1:] M = np.zeros((N, N)) use_svd = n_neighbors > d_in for i in range(N): Xi = X[neighbors[i]] Xi -= Xi.mean(0) if use_svd: v = svd(Xi, full_matrices=True)[0] else: Ci = np.dot(Xi, Xi.T) v = _eigh(Ci)[1][:, ::-1] Gi = np.zeros((n_neighbors, n_components + 1)) Gi[:, 1:] = v[:, :n_components] Gi[:, 0] = 1.0 / np.sqrt(n_neighbors) GiGiT = np.dot(Gi, Gi.T) (nbrs_x, nbrs_y) = np.meshgrid(neighbors[i], neighbors[i]) M[nbrs_x, nbrs_y] -= GiGiT M[neighbors[i], neighbors[i]] += 1 return null_space(M, n_components, k_skip=1, eigen_solver=eigen_solver, tol=tol, max_iter=max_iter, random_state=random_state)
def locally_linear_embedding(X, *, n_neighbors, n_components, reg=0.001, eigen_solver='auto', tol=1e-06, max_iter=100, method='standard', hessian_tol=0.0001, modified_tol=1e-12, random_state=None, n_jobs=None): """Perform a Locally Linear Embedding analysis on the data. Read more in the :ref:`User Guide <locally_linear_embedding>`. Parameters ---------- X : {array-like, NearestNeighbors} Sample data, shape = (n_samples, n_features), in the form of a numpy array or a NearestNeighbors object. n_neighbors : int Number of neighbors to consider for each point. n_components : int Number of coordinates for the manifold. reg : float, default=1e-3 Regularization constant, multiplies the trace of the local covariance matrix of the distances. eigen_solver : {'auto', 'arpack', 'dense'}, default='auto' auto : algorithm will attempt to choose the best method for input data arpack : use arnoldi iteration in shift-invert mode. For this method, M may be a dense matrix, sparse matrix, or general linear operator. Warning: ARPACK can be unstable for some problems. It is best to try several random seeds in order to check results. dense : use standard dense matrix operations for the eigenvalue decomposition. For this method, M must be an array or matrix type. This method should be avoided for large problems. tol : float, default=1e-6 Tolerance for 'arpack' method Not used if eigen_solver=='dense'. max_iter : int, default=100 Maximum number of iterations for the arpack solver. method : {'standard', 'hessian', 'modified', 'ltsa'}, default='standard' standard : use the standard locally linear embedding algorithm. see reference [1]_ hessian : use the Hessian eigenmap method. This method requires n_neighbors > n_components * (1 + (n_components + 1) / 2. see reference [2]_ modified : use the modified locally linear embedding algorithm. see reference [3]_ ltsa : use local tangent space alignment algorithm see reference [4]_ hessian_tol : float, default=1e-4 Tolerance for Hessian eigenmapping method. Only used if method == 'hessian'. modified_tol : float, default=1e-12 Tolerance for modified LLE method. Only used if method == 'modified'. random_state : int, RandomState instance, default=None Determines the random number generator when ``solver`` == 'arpack'. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. n_jobs : int or None, default=None The number of parallel jobs to run for neighbors search. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Returns ------- Y : array-like, shape [n_samples, n_components] Embedding vectors. squared_error : float Reconstruction error for the embedding vectors. Equivalent to ``norm(Y - W Y, 'fro')**2``, where W are the reconstruction weights. References ---------- .. [1] Roweis, S. & Saul, L. Nonlinear dimensionality reduction by locally linear embedding. Science 290:2323 (2000). .. [2] Donoho, D. & Grimes, C. Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data. Proc Natl Acad Sci U S A. 100:5591 (2003). .. [3] `Zhang, Z. & Wang, J. MLLE: Modified Locally Linear Embedding Using Multiple Weights. <https://citeseerx.ist.psu.edu/doc_view/pid/0b060fdbd92cbcc66b383bcaa9ba5e5e624d7ee3>`_ .. [4] Zhang, Z. & Zha, H. Principal manifolds and nonlinear dimensionality reduction via tangent space alignment. Journal of Shanghai Univ. 8:406 (2004) """ if eigen_solver not in ('auto', 'arpack', 'dense'): raise ValueError("unrecognized eigen_solver '%s'" % eigen_solver) if method not in ('standard', 'hessian', 'modified', 'ltsa'): raise ValueError("unrecognized method '%s'" % method) nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs) nbrs.fit(X) X = nbrs._fit_X (N, d_in) = X.shape if n_components > d_in: raise ValueError('output dimension must be less than or equal to input dimension') if n_neighbors >= N: raise ValueError('Expected n_neighbors <= n_samples, but n_samples = %d, n_neighbors = %d' % (N, n_neighbors)) if n_neighbors <= 0: raise ValueError('n_neighbors must be positive') M_sparse = eigen_solver != 'dense' if method == 'standard': <DeepExtract> knn = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs).fit(nbrs) nbrs = knn._fit_X n_samples = knn.n_samples_fit_ ind = knn.kneighbors(nbrs, return_distance=False)[:, 1:] data = barycenter_weights(nbrs, nbrs, ind, reg=reg) indptr = np.arange(0, n_samples * n_neighbors + 1, n_neighbors) W = csr_matrix((data.ravel(), ind.ravel(), indptr), shape=(n_samples, n_samples)) </DeepExtract> if M_sparse: M = eye(*W.shape, format=W.format) - W M = (M.T * M).tocsr() else: M = (W.T * W - W.T - W).toarray() M.flat[::M.shape[0] + 1] += 1 elif method == 'hessian': dp = n_components * (n_components + 1) // 2 if n_neighbors <= n_components + dp: raise ValueError("for method='hessian', n_neighbors must be greater than [n_components * (n_components + 3) / 2]") neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) neighbors = neighbors[:, 1:] Yi = np.empty((n_neighbors, 1 + n_components + dp), dtype=np.float64) Yi[:, 0] = 1 M = np.zeros((N, N), dtype=np.float64) use_svd = n_neighbors > d_in for i in range(N): Gi = X[neighbors[i]] Gi -= Gi.mean(0) if use_svd: U = svd(Gi, full_matrices=0)[0] else: Ci = np.dot(Gi, Gi.T) U = _eigh(Ci)[1][:, ::-1] Yi[:, 1:1 + n_components] = U[:, :n_components] j = 1 + n_components for k in range(n_components): Yi[:, j:j + n_components - k] = U[:, k:k + 1] * U[:, k:n_components] j += n_components - k (Q, R) = qr(Yi) w = Q[:, n_components + 1:] S = w.sum(0) S[np.where(abs(S) < hessian_tol)] = 1 w /= S (nbrs_x, nbrs_y) = np.meshgrid(neighbors[i], neighbors[i]) M[nbrs_x, nbrs_y] += np.dot(w, w.T) if M_sparse: M = csr_matrix(M) elif method == 'modified': if n_neighbors < n_components: raise ValueError('modified LLE requires n_neighbors >= n_components') neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) neighbors = neighbors[:, 1:] V = np.zeros((N, n_neighbors, n_neighbors)) nev = min(d_in, n_neighbors) evals = np.zeros([N, nev]) use_svd = n_neighbors > d_in if use_svd: for i in range(N): X_nbrs = X[neighbors[i]] - X[i] (V[i], evals[i], _) = svd(X_nbrs, full_matrices=True) evals **= 2 else: for i in range(N): X_nbrs = X[neighbors[i]] - X[i] C_nbrs = np.dot(X_nbrs, X_nbrs.T) (evi, vi) = _eigh(C_nbrs) evals[i] = evi[::-1] V[i] = vi[:, ::-1] reg = 0.001 * evals.sum(1) tmp = np.dot(V.transpose(0, 2, 1), np.ones(n_neighbors)) tmp[:, :nev] /= evals + reg[:, None] tmp[:, nev:] /= reg[:, None] w_reg = np.zeros((N, n_neighbors)) for i in range(N): w_reg[i] = np.dot(V[i], tmp[i]) w_reg /= w_reg.sum(1)[:, None] rho = evals[:, n_components:].sum(1) / evals[:, :n_components].sum(1) eta = np.median(rho) s_range = np.zeros(N, dtype=int) evals_cumsum = stable_cumsum(evals, 1) eta_range = evals_cumsum[:, -1:] / evals_cumsum[:, :-1] - 1 for i in range(N): s_range[i] = np.searchsorted(eta_range[i, ::-1], eta) s_range += n_neighbors - nev M = np.zeros((N, N), dtype=np.float64) for i in range(N): s_i = s_range[i] Vi = V[i, :, n_neighbors - s_i:] alpha_i = np.linalg.norm(Vi.sum(0)) / np.sqrt(s_i) h = np.full(s_i, alpha_i) - np.dot(Vi.T, np.ones(n_neighbors)) norm_h = np.linalg.norm(h) if norm_h < modified_tol: h *= 0 else: h /= norm_h Wi = Vi - 2 * np.outer(np.dot(Vi, h), h) + (1 - alpha_i) * w_reg[i, :, None] (nbrs_x, nbrs_y) = np.meshgrid(neighbors[i], neighbors[i]) M[nbrs_x, nbrs_y] += np.dot(Wi, Wi.T) Wi_sum1 = Wi.sum(1) M[i, neighbors[i]] -= Wi_sum1 M[neighbors[i], i] -= Wi_sum1 M[i, i] += s_i if M_sparse: M = csr_matrix(M) elif method == 'ltsa': neighbors = nbrs.kneighbors(X, n_neighbors=n_neighbors + 1, return_distance=False) neighbors = neighbors[:, 1:] M = np.zeros((N, N)) use_svd = n_neighbors > d_in for i in range(N): Xi = X[neighbors[i]] Xi -= Xi.mean(0) if use_svd: v = svd(Xi, full_matrices=True)[0] else: Ci = np.dot(Xi, Xi.T) v = _eigh(Ci)[1][:, ::-1] Gi = np.zeros((n_neighbors, n_components + 1)) Gi[:, 1:] = v[:, :n_components] Gi[:, 0] = 1.0 / np.sqrt(n_neighbors) GiGiT = np.dot(Gi, Gi.T) (nbrs_x, nbrs_y) = np.meshgrid(neighbors[i], neighbors[i]) M[nbrs_x, nbrs_y] -= GiGiT M[neighbors[i], neighbors[i]] += 1 return null_space(M, n_components, k_skip=1, eigen_solver=eigen_solver, tol=tol, max_iter=max_iter, random_state=random_state)
@abstractmethod def fit(self, X, Y, **fit_params): """Fit the model to data matrix X and targets Y. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. Y : array-like of shape (n_samples, n_classes) The target values. **fit_params : dict of string -> object Parameters passed to the `fit` method of each step. .. versionadded:: 0.23 Returns ------- self : object Returns a fitted instance. """ (X, Y) = self._validate_data(X, Y, multi_output=True, accept_sparse=True) random_state = check_random_state(self.random_state) self.order_ = self.order if isinstance(self.order_, tuple): self.order_ = np.array(self.order_) if self.order_ is None: self.order_ = np.array(range(Y.shape[1])) elif isinstance(self.order_, str): if self.order_ == 'random': self.order_ = random_state.permutation(Y.shape[1]) elif sorted(self.order_) != list(range(Y.shape[1])): raise ValueError('invalid order') self.estimators_ = [clone(self.base_estimator) for _ in range(Y.shape[1])] if self.cv is None: Y_pred_chain = Y[:, self.order_] if sp.issparse(X): X_aug = sp.hstack((X, Y_pred_chain), format='lil') X_aug = X_aug.tocsr() else: X_aug = np.hstack((X, Y_pred_chain)) elif sp.issparse(X): Y_pred_chain = sp.lil_matrix((X.shape[0], Y.shape[1])) X_aug = sp.hstack((X, Y_pred_chain), format='lil') else: Y_pred_chain = np.zeros((X.shape[0], Y.shape[1])) X_aug = np.hstack((X, Y_pred_chain)) del Y_pred_chain for (chain_idx, estimator) in enumerate(self.estimators_): if not self.verbose: message = None message = f"({chain_idx + 1} of {len(self.estimators_)}) {f'Processing order {self.order_[chain_idx]}'}" y = Y[:, self.order_[chain_idx]] with _print_elapsed_time('Chain', message): estimator.fit(X_aug[:, :X.shape[1] + chain_idx], y, **fit_params) if self.cv is not None and chain_idx < len(self.estimators_) - 1: col_idx = X.shape[1] + chain_idx cv_result = cross_val_predict(self.base_estimator, X_aug[:, :col_idx], y=y, cv=self.cv) if sp.issparse(X_aug): X_aug[:, col_idx] = np.expand_dims(cv_result, 1) else: X_aug[:, col_idx] = cv_result return self
@abstractmethod def fit(self, X, Y, **fit_params): """Fit the model to data matrix X and targets Y. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. Y : array-like of shape (n_samples, n_classes) The target values. **fit_params : dict of string -> object Parameters passed to the `fit` method of each step. .. versionadded:: 0.23 Returns ------- self : object Returns a fitted instance. """ (X, Y) = self._validate_data(X, Y, multi_output=True, accept_sparse=True) random_state = check_random_state(self.random_state) self.order_ = self.order if isinstance(self.order_, tuple): self.order_ = np.array(self.order_) if self.order_ is None: self.order_ = np.array(range(Y.shape[1])) elif isinstance(self.order_, str): if self.order_ == 'random': self.order_ = random_state.permutation(Y.shape[1]) elif sorted(self.order_) != list(range(Y.shape[1])): raise ValueError('invalid order') self.estimators_ = [clone(self.base_estimator) for _ in range(Y.shape[1])] if self.cv is None: Y_pred_chain = Y[:, self.order_] if sp.issparse(X): X_aug = sp.hstack((X, Y_pred_chain), format='lil') X_aug = X_aug.tocsr() else: X_aug = np.hstack((X, Y_pred_chain)) elif sp.issparse(X): Y_pred_chain = sp.lil_matrix((X.shape[0], Y.shape[1])) X_aug = sp.hstack((X, Y_pred_chain), format='lil') else: Y_pred_chain = np.zeros((X.shape[0], Y.shape[1])) X_aug = np.hstack((X, Y_pred_chain)) del Y_pred_chain for (chain_idx, estimator) in enumerate(self.estimators_): <DeepExtract> if not self.verbose: message = None message = f"({chain_idx + 1} of {len(self.estimators_)}) {f'Processing order {self.order_[chain_idx]}'}" </DeepExtract> y = Y[:, self.order_[chain_idx]] with _print_elapsed_time('Chain', message): estimator.fit(X_aug[:, :X.shape[1] + chain_idx], y, **fit_params) if self.cv is not None and chain_idx < len(self.estimators_) - 1: col_idx = X.shape[1] + chain_idx cv_result = cross_val_predict(self.base_estimator, X_aug[:, :col_idx], y=y, cv=self.cv) if sp.issparse(X_aug): X_aug[:, col_idx] = np.expand_dims(cv_result, 1) else: X_aug[:, col_idx] = cv_result return self
@ignore_warnings def check_pipeline_consistency(name, estimator_orig): if _safe_tags(estimator_orig, key='non_deterministic'): msg = name + ' is non deterministic' raise SkipTest(msg) (X, y) = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, n_features=2, cluster_std=0.1) if '1darray' in _safe_tags(estimator_orig, key='X_types'): X = X[:, 0] if _safe_tags(estimator_orig, key='requires_positive_X'): X = X - X.min() if 'categorical' in _safe_tags(estimator_orig, key='X_types'): X = (X - X.min()).astype(np.int32) if estimator_orig.__class__.__name__ == 'SkewedChi2Sampler': X = X - X.min() if _is_pairwise_metric(estimator_orig): X = pairwise_distances(X, metric='euclidean') elif _safe_tags(estimator_orig, key='pairwise'): X = rbf_kernel(X, X) X = X estimator = clone(estimator_orig) if _safe_tags(estimator, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(estimator, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(estimator, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y set_random_state(estimator) pipeline = make_pipeline(estimator) estimator.fit(X, y) pipeline.fit(X, y) funcs = ['score', 'fit_transform'] for func_name in funcs: func = getattr(estimator, func_name, None) if func is not None: func_pipeline = getattr(pipeline, func_name) result = func(X, y) result_pipe = func_pipeline(X, y) assert_allclose_dense_sparse(result, result_pipe)
@ignore_warnings def check_pipeline_consistency(name, estimator_orig): if _safe_tags(estimator_orig, key='non_deterministic'): msg = name + ' is non deterministic' raise SkipTest(msg) (X, y) = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, n_features=2, cluster_std=0.1) <DeepExtract> if '1darray' in _safe_tags(estimator_orig, key='X_types'): X = X[:, 0] if _safe_tags(estimator_orig, key='requires_positive_X'): X = X - X.min() if 'categorical' in _safe_tags(estimator_orig, key='X_types'): X = (X - X.min()).astype(np.int32) if estimator_orig.__class__.__name__ == 'SkewedChi2Sampler': X = X - X.min() if _is_pairwise_metric(estimator_orig): X = pairwise_distances(X, metric='euclidean') elif _safe_tags(estimator_orig, key='pairwise'): X = rbf_kernel(X, X) X = X </DeepExtract> estimator = clone(estimator_orig) <DeepExtract> if _safe_tags(estimator, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(estimator, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(estimator, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y </DeepExtract> set_random_state(estimator) pipeline = make_pipeline(estimator) estimator.fit(X, y) pipeline.fit(X, y) funcs = ['score', 'fit_transform'] for func_name in funcs: func = getattr(estimator, func_name, None) if func is not None: func_pipeline = getattr(pipeline, func_name) result = func(X, y) result_pipe = func_pipeline(X, y) assert_allclose_dense_sparse(result, result_pipe)
@pytest.mark.parametrize('name', sorted(SYMMETRIC_METRICS)) def test_symmetric_metric(name): random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20,)) y_pred = random_state.randint(0, 2, size=(20,)) if name in METRICS_REQUIRE_POSITIVE_Y: offset = abs(min(y_true.min(), y_pred.min())) + 1 y_true += offset y_pred += offset (y_true, y_pred) = (y_true, y_pred) y_true_bin = random_state.randint(0, 2, size=(20, 25)) y_pred_bin = random_state.randint(0, 2, size=(20, 25)) metric = ALL_METRICS[name] if name in METRIC_UNDEFINED_BINARY: if name in MULTILABELS_METRICS: assert_allclose(metric(y_true_bin, y_pred_bin), metric(y_pred_bin, y_true_bin), err_msg='%s is not symmetric' % name) else: assert False, 'This case is currently unhandled' else: assert_allclose(metric(y_true, y_pred), metric(y_pred, y_true), err_msg='%s is not symmetric' % name)
@pytest.mark.parametrize('name', sorted(SYMMETRIC_METRICS)) def test_symmetric_metric(name): random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20,)) y_pred = random_state.randint(0, 2, size=(20,)) if name in METRICS_REQUIRE_POSITIVE_Y: <DeepExtract> offset = abs(min(y_true.min(), y_pred.min())) + 1 y_true += offset y_pred += offset (y_true, y_pred) = (y_true, y_pred) </DeepExtract> y_true_bin = random_state.randint(0, 2, size=(20, 25)) y_pred_bin = random_state.randint(0, 2, size=(20, 25)) metric = ALL_METRICS[name] if name in METRIC_UNDEFINED_BINARY: if name in MULTILABELS_METRICS: assert_allclose(metric(y_true_bin, y_pred_bin), metric(y_pred_bin, y_true_bin), err_msg='%s is not symmetric' % name) else: assert False, 'This case is currently unhandled' else: assert_allclose(metric(y_true, y_pred), metric(y_pred, y_true), err_msg='%s is not symmetric' % name)
def build_projection_operator(l_x, n_dir): """Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2) """ (X, Y) = np.mgrid[:l_x, :l_x].astype(np.float64) center = l_x / 2.0 X += 0.5 - center Y += 0.5 - center (X, Y) = (X, Y) angles = np.linspace(0, np.pi, n_dir, endpoint=False) (data_inds, weights, camera_inds) = ([], [], []) data_unravel_indices = np.arange(l_x ** 2) data_unravel_indices = np.hstack((data_unravel_indices, data_unravel_indices)) for (i, angle) in enumerate(angles): Xrot = np.cos(angle) * X - np.sin(angle) * Y Xrot = np.ravel(Xrot) floor_x = np.floor((Xrot - X.min()) / 1).astype(np.int64) alpha = (Xrot - X.min() - floor_x * 1) / 1 (inds, w) = (np.hstack((floor_x, floor_x + 1)), np.hstack((1 - alpha, alpha))) mask = np.logical_and(inds >= 0, inds < l_x) weights += list(w[mask]) camera_inds += list(inds[mask] + i * l_x) data_inds += list(data_unravel_indices[mask]) proj_operator = sparse.coo_matrix((weights, (camera_inds, data_inds))) return proj_operator
def build_projection_operator(l_x, n_dir): """Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2) """ <DeepExtract> (X, Y) = np.mgrid[:l_x, :l_x].astype(np.float64) center = l_x / 2.0 X += 0.5 - center Y += 0.5 - center (X, Y) = (X, Y) </DeepExtract> angles = np.linspace(0, np.pi, n_dir, endpoint=False) (data_inds, weights, camera_inds) = ([], [], []) data_unravel_indices = np.arange(l_x ** 2) data_unravel_indices = np.hstack((data_unravel_indices, data_unravel_indices)) for (i, angle) in enumerate(angles): Xrot = np.cos(angle) * X - np.sin(angle) * Y <DeepExtract> Xrot = np.ravel(Xrot) floor_x = np.floor((Xrot - X.min()) / 1).astype(np.int64) alpha = (Xrot - X.min() - floor_x * 1) / 1 (inds, w) = (np.hstack((floor_x, floor_x + 1)), np.hstack((1 - alpha, alpha))) </DeepExtract> mask = np.logical_and(inds >= 0, inds < l_x) weights += list(w[mask]) camera_inds += list(inds[mask] + i * l_x) data_inds += list(data_unravel_indices[mask]) proj_operator = sparse.coo_matrix((weights, (camera_inds, data_inds))) return proj_operator
def _fit(self, X, alpha, C, loss, learning_rate, coef_init=None, offset_init=None, sample_weight=None): if self.warm_start and hasattr(self, 'coef_'): if coef_init is None: coef_init = self.coef_ if offset_init is None: offset_init = self.offset_ else: self.coef_ = None self.offset_ = None self.t_ = 1.0 first_call = not hasattr(self, 'classes_') (X, alpha) = self._validate_data(X, alpha, accept_sparse='csr', dtype=[np.float64, np.float32], order='C', accept_large_sparse=False, reset=first_call) (n_samples, n_features) = X.shape _check_partial_fit_first_call(self, coef_init) n_classes = self.classes_.shape[0] self._expanded_class_weight = compute_class_weight(self.class_weight, classes=self.classes_, y=alpha) offset_init = _check_sample_weight(offset_init, X, dtype=X.dtype) if getattr(self, 'coef_', None) is None or coef_init is not None: self._allocate_parameter_mem(n_classes=n_classes, n_features=n_features, input_dtype=X.dtype, coef_init=coef_init, intercept_init=intercept_init) elif n_features != self.coef_.shape[-1]: raise ValueError('Number of features %d does not match previous data %d.' % (n_features, self.coef_.shape[-1])) self.loss_function_ = self._get_loss_function(learning_rate) if not hasattr(self, 't_'): self.t_ = 1.0 if n_classes > 2: self._fit_multiclass(X, alpha, alpha=C, C=loss, learning_rate=self.max_iter, sample_weight=offset_init, max_iter=sample_weight) elif n_classes == 2: self._fit_binary(X, alpha, alpha=C, C=loss, learning_rate=self.max_iter, sample_weight=offset_init, max_iter=sample_weight) else: raise ValueError('The number of classes has to be greater than one; got %d class' % n_classes) return self if self.tol is not None and self.tol > -np.inf and (self.n_iter_ == self.max_iter): warnings.warn('Maximum number of iteration reached before convergence. Consider increasing max_iter to improve the fit.', ConvergenceWarning) return self
def _fit(self, X, alpha, C, loss, learning_rate, coef_init=None, offset_init=None, sample_weight=None): if self.warm_start and hasattr(self, 'coef_'): if coef_init is None: coef_init = self.coef_ if offset_init is None: offset_init = self.offset_ else: self.coef_ = None self.offset_ = None self.t_ = 1.0 <DeepExtract> first_call = not hasattr(self, 'classes_') (X, alpha) = self._validate_data(X, alpha, accept_sparse='csr', dtype=[np.float64, np.float32], order='C', accept_large_sparse=False, reset=first_call) (n_samples, n_features) = X.shape _check_partial_fit_first_call(self, coef_init) n_classes = self.classes_.shape[0] self._expanded_class_weight = compute_class_weight(self.class_weight, classes=self.classes_, y=alpha) offset_init = _check_sample_weight(offset_init, X, dtype=X.dtype) if getattr(self, 'coef_', None) is None or coef_init is not None: self._allocate_parameter_mem(n_classes=n_classes, n_features=n_features, input_dtype=X.dtype, coef_init=coef_init, intercept_init=intercept_init) elif n_features != self.coef_.shape[-1]: raise ValueError('Number of features %d does not match previous data %d.' % (n_features, self.coef_.shape[-1])) self.loss_function_ = self._get_loss_function(learning_rate) if not hasattr(self, 't_'): self.t_ = 1.0 if n_classes > 2: self._fit_multiclass(X, alpha, alpha=C, C=loss, learning_rate=self.max_iter, sample_weight=offset_init, max_iter=sample_weight) elif n_classes == 2: self._fit_binary(X, alpha, alpha=C, C=loss, learning_rate=self.max_iter, sample_weight=offset_init, max_iter=sample_weight) else: raise ValueError('The number of classes has to be greater than one; got %d class' % n_classes) return self </DeepExtract> if self.tol is not None and self.tol > -np.inf and (self.n_iter_ == self.max_iter): warnings.warn('Maximum number of iteration reached before convergence. Consider increasing max_iter to improve the fit.', ConvergenceWarning) return self
@validate_params({'y_true': ['array-like'], 'probas_pred': ['array-like'], 'pos_label': [Real, str, 'boolean', None], 'sample_weight': ['array-like', None], 'drop_intermediate': ['boolean']}) def precision_recall_curve(y_true, probas_pred, *, pos_label=None, sample_weight=None, drop_intermediate=False): """Compute precision-recall pairs for different probability thresholds. Note: this implementation is restricted to the binary classification task. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The last precision and recall values are 1. and 0. respectively and do not have a corresponding threshold. This ensures that the graph starts on the y axis. The first precision and recall values are precision=class balance and recall=1.0 which corresponds to a classifier that always predicts the positive class. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. probas_pred : array-like of shape (n_samples,) Target scores, can either be probability estimates of the positive class, or non-thresholded measure of decisions (as returned by `decision_function` on some classifiers). pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop some suboptimal thresholds which would not appear on a plotted precision-recall curve. This is useful in order to create lighter precision-recall curves. .. versionadded:: 1.3 Returns ------- precision : ndarray of shape (n_thresholds + 1,) Precision values such that element i is the precision of predictions with score >= thresholds[i] and the last element is 1. recall : ndarray of shape (n_thresholds + 1,) Decreasing recall values such that element i is the recall of predictions with score >= thresholds[i] and the last element is 0. thresholds : ndarray of shape (n_thresholds,) Increasing thresholds on the decision function used to compute precision and recall where `n_thresholds = len(np.unique(probas_pred))`. See Also -------- PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given a binary classifier. PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve using predictions from a binary classifier. average_precision_score : Compute average precision from prediction scores. det_curve: Compute error rates for different probability thresholds. roc_curve : Compute Receiver operating characteristic (ROC) curve. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> precision, recall, thresholds = precision_recall_curve( ... y_true, y_scores) >>> precision array([0.5 , 0.66666667, 0.5 , 1. , 1. ]) >>> recall array([1. , 1. , 0.5, 0.5, 0. ]) >>> thresholds array([0.1 , 0.35, 0.4 , 0.8 ]) """ y_type = type_of_target(y_true, input_name='y_true') if not (y_type == 'binary' or (y_type == 'multiclass' and pos_label is not None)): raise ValueError('{0} format is not supported'.format(y_type)) check_consistent_length(y_true, probas_pred, sample_weight) y_true = column_or_1d(y_true) probas_pred = column_or_1d(probas_pred) assert_all_finite(y_true) assert_all_finite(probas_pred) if sample_weight is not None: sample_weight = column_or_1d(sample_weight) sample_weight = _check_sample_weight(sample_weight, y_true) nonzero_weight_mask = sample_weight != 0 y_true = y_true[nonzero_weight_mask] probas_pred = probas_pred[nonzero_weight_mask] sample_weight = sample_weight[nonzero_weight_mask] pos_label = _check_pos_label_consistency(pos_label, y_true) y_true = y_true == pos_label desc_score_indices = np.argsort(probas_pred, kind='mergesort')[::-1] probas_pred = probas_pred[desc_score_indices] y_true = y_true[desc_score_indices] if sample_weight is not None: weight = sample_weight[desc_score_indices] else: weight = 1.0 distinct_value_indices = np.where(np.diff(probas_pred))[0] threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] tps = stable_cumsum(y_true * weight)[threshold_idxs] if sample_weight is not None: fps = stable_cumsum((1 - y_true) * weight)[threshold_idxs] else: fps = 1 + threshold_idxs - tps (fps, tps, thresholds) = (fps, tps, probas_pred[threshold_idxs]) if drop_intermediate and len(fps) > 2: optimal_idxs = np.where(np.concatenate([[True], np.logical_or(np.diff(tps[:-1]), np.diff(tps[1:])), [True]]))[0] fps = fps[optimal_idxs] tps = tps[optimal_idxs] thresholds = thresholds[optimal_idxs] ps = tps + fps precision = np.zeros_like(tps) np.divide(tps, ps, out=precision, where=ps != 0) if tps[-1] == 0: warnings.warn('No positive class found in y_true, recall is set to one for all thresholds.') recall = np.ones_like(tps) else: recall = tps / tps[-1] sl = slice(None, None, -1) return (np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl])
@validate_params({'y_true': ['array-like'], 'probas_pred': ['array-like'], 'pos_label': [Real, str, 'boolean', None], 'sample_weight': ['array-like', None], 'drop_intermediate': ['boolean']}) def precision_recall_curve(y_true, probas_pred, *, pos_label=None, sample_weight=None, drop_intermediate=False): """Compute precision-recall pairs for different probability thresholds. Note: this implementation is restricted to the binary classification task. The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. The precision is intuitively the ability of the classifier not to label as positive a sample that is negative. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The last precision and recall values are 1. and 0. respectively and do not have a corresponding threshold. This ensures that the graph starts on the y axis. The first precision and recall values are precision=class balance and recall=1.0 which corresponds to a classifier that always predicts the positive class. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) True binary labels. If labels are not either {-1, 1} or {0, 1}, then pos_label should be explicitly given. probas_pred : array-like of shape (n_samples,) Target scores, can either be probability estimates of the positive class, or non-thresholded measure of decisions (as returned by `decision_function` on some classifiers). pos_label : int, float, bool or str, default=None The label of the positive class. When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1}, ``pos_label`` is set to 1, otherwise an error will be raised. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop some suboptimal thresholds which would not appear on a plotted precision-recall curve. This is useful in order to create lighter precision-recall curves. .. versionadded:: 1.3 Returns ------- precision : ndarray of shape (n_thresholds + 1,) Precision values such that element i is the precision of predictions with score >= thresholds[i] and the last element is 1. recall : ndarray of shape (n_thresholds + 1,) Decreasing recall values such that element i is the recall of predictions with score >= thresholds[i] and the last element is 0. thresholds : ndarray of shape (n_thresholds,) Increasing thresholds on the decision function used to compute precision and recall where `n_thresholds = len(np.unique(probas_pred))`. See Also -------- PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given a binary classifier. PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve using predictions from a binary classifier. average_precision_score : Compute average precision from prediction scores. det_curve: Compute error rates for different probability thresholds. roc_curve : Compute Receiver operating characteristic (ROC) curve. Examples -------- >>> import numpy as np >>> from sklearn.metrics import precision_recall_curve >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> precision, recall, thresholds = precision_recall_curve( ... y_true, y_scores) >>> precision array([0.5 , 0.66666667, 0.5 , 1. , 1. ]) >>> recall array([1. , 1. , 0.5, 0.5, 0. ]) >>> thresholds array([0.1 , 0.35, 0.4 , 0.8 ]) """ <DeepExtract> y_type = type_of_target(y_true, input_name='y_true') if not (y_type == 'binary' or (y_type == 'multiclass' and pos_label is not None)): raise ValueError('{0} format is not supported'.format(y_type)) check_consistent_length(y_true, probas_pred, sample_weight) y_true = column_or_1d(y_true) probas_pred = column_or_1d(probas_pred) assert_all_finite(y_true) assert_all_finite(probas_pred) if sample_weight is not None: sample_weight = column_or_1d(sample_weight) sample_weight = _check_sample_weight(sample_weight, y_true) nonzero_weight_mask = sample_weight != 0 y_true = y_true[nonzero_weight_mask] probas_pred = probas_pred[nonzero_weight_mask] sample_weight = sample_weight[nonzero_weight_mask] pos_label = _check_pos_label_consistency(pos_label, y_true) y_true = y_true == pos_label desc_score_indices = np.argsort(probas_pred, kind='mergesort')[::-1] probas_pred = probas_pred[desc_score_indices] y_true = y_true[desc_score_indices] if sample_weight is not None: weight = sample_weight[desc_score_indices] else: weight = 1.0 distinct_value_indices = np.where(np.diff(probas_pred))[0] threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] tps = stable_cumsum(y_true * weight)[threshold_idxs] if sample_weight is not None: fps = stable_cumsum((1 - y_true) * weight)[threshold_idxs] else: fps = 1 + threshold_idxs - tps (fps, tps, thresholds) = (fps, tps, probas_pred[threshold_idxs]) </DeepExtract> if drop_intermediate and len(fps) > 2: optimal_idxs = np.where(np.concatenate([[True], np.logical_or(np.diff(tps[:-1]), np.diff(tps[1:])), [True]]))[0] fps = fps[optimal_idxs] tps = tps[optimal_idxs] thresholds = thresholds[optimal_idxs] ps = tps + fps precision = np.zeros_like(tps) np.divide(tps, ps, out=precision, where=ps != 0) if tps[-1] == 0: warnings.warn('No positive class found in y_true, recall is set to one for all thresholds.') recall = np.ones_like(tps) else: recall = tps / tps[-1] sl = slice(None, None, -1) return (np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl])
def _select_proba_binary(self, y_pred, classes): """Select the column of the positive label in `y_pred` when probabilities are provided. Parameters ---------- y_pred : ndarray of shape (n_samples, n_classes) The prediction given by `predict_proba`. classes : ndarray of shape (n_classes,) The class labels for the estimator. Returns ------- y_pred : ndarray of shape (n_samples,) Probability predictions of the positive class. """ if y_pred.shape[1] == 2: pos_label = self._kwargs.get('pos_label', classes[1]) if pos_label not in list(classes): raise ValueError(f'pos_label={pos_label} is not a valid label: {classes}') col_idx = np.flatnonzero(classes == pos_label)[0] return y_pred[:, col_idx] err_msg = f'Got predict_proba of shape {y_pred.shape}, but need classifier with two classes for {self._score_func.__name__} scoring' raise ValueError(err_msg)
def _select_proba_binary(self, y_pred, classes): """Select the column of the positive label in `y_pred` when probabilities are provided. Parameters ---------- y_pred : ndarray of shape (n_samples, n_classes) The prediction given by `predict_proba`. classes : ndarray of shape (n_classes,) The class labels for the estimator. Returns ------- y_pred : ndarray of shape (n_samples,) Probability predictions of the positive class. """ if y_pred.shape[1] == 2: pos_label = self._kwargs.get('pos_label', classes[1]) <DeepExtract> if pos_label not in list(classes): raise ValueError(f'pos_label={pos_label} is not a valid label: {classes}') </DeepExtract> col_idx = np.flatnonzero(classes == pos_label)[0] return y_pred[:, col_idx] err_msg = f'Got predict_proba of shape {y_pred.shape}, but need classifier with two classes for {self._score_func.__name__} scoring' raise ValueError(err_msg)
def get_submatrix(self, i, data): """Return the submatrix corresponding to bicluster `i`. Parameters ---------- i : int The index of the cluster. data : array-like of shape (n_samples, n_features) The data. Returns ------- submatrix : ndarray of shape (n_rows, n_cols) The submatrix corresponding to bicluster `i`. Notes ----- Works with sparse matrices. Only works if ``rows_`` and ``columns_`` attributes exist. """ from .utils.validation import check_array data = check_array(data, accept_sparse='csr') rows = self.rows_[i] columns = self.columns_[i] (row_ind, col_ind) = (np.nonzero(rows)[0], np.nonzero(columns)[0]) return data[row_ind[:, np.newaxis], col_ind]
def get_submatrix(self, i, data): """Return the submatrix corresponding to bicluster `i`. Parameters ---------- i : int The index of the cluster. data : array-like of shape (n_samples, n_features) The data. Returns ------- submatrix : ndarray of shape (n_rows, n_cols) The submatrix corresponding to bicluster `i`. Notes ----- Works with sparse matrices. Only works if ``rows_`` and ``columns_`` attributes exist. """ from .utils.validation import check_array data = check_array(data, accept_sparse='csr') <DeepExtract> rows = self.rows_[i] columns = self.columns_[i] (row_ind, col_ind) = (np.nonzero(rows)[0], np.nonzero(columns)[0]) </DeepExtract> return data[row_ind[:, np.newaxis], col_ind]
def apply(self, X, check_input=True): """Return the index of the leaf that each sample is predicted as. .. versionadded:: 0.17 Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- X_leaves : array-like of shape (n_samples,) For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within ``[0; self.tree_.node_count)``, possibly with gaps in the numbering. """ check_is_fitted(self) if check_input: X = self._validate_data(X, dtype=DTYPE, accept_sparse='csr', reset=False) if issparse(X) and (X.indices.dtype != np.intc or X.indptr.dtype != np.intc): raise ValueError('No support for np.int64 index based sparse matrices') else: self._check_n_features(X, reset=False) X = X return self.tree_.apply(X)
def apply(self, X, check_input=True): """Return the index of the leaf that each sample is predicted as. .. versionadded:: 0.17 Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided to a sparse ``csr_matrix``. check_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- X_leaves : array-like of shape (n_samples,) For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within ``[0; self.tree_.node_count)``, possibly with gaps in the numbering. """ check_is_fitted(self) <DeepExtract> if check_input: X = self._validate_data(X, dtype=DTYPE, accept_sparse='csr', reset=False) if issparse(X) and (X.indices.dtype != np.intc or X.indptr.dtype != np.intc): raise ValueError('No support for np.int64 index based sparse matrices') else: self._check_n_features(X, reset=False) X = X </DeepExtract> return self.tree_.apply(X)
def fit_transform(self, X, y=None, W=None, H=None): """Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Data matrix to be decomposed. y : Ignored Not used, present here for API consistency by convention. W : array-like of shape (n_samples, n_components), default=None If `init='custom'`, it is used as initial guess for the solution. If `None`, uses the initialisation method specified in `init`. H : array-like of shape (n_components, n_features), default=None If `init='custom'`, it is used as initial guess for the solution. If `None`, uses the initialisation method specified in `init`. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. """ self._validate_params() X = self._validate_data(X, accept_sparse=('csr', 'csc'), dtype=[np.float64, np.float32]) with config_context(assume_finite=True): check_non_negative(X, 'NMF (input X)') self._check_params(X) if X.min() == 0 and self._beta_loss <= 0: raise ValueError('When beta_loss <= 0 and X contains zeros, the solver may diverge. Please add small values to X, or use a positive beta_loss.') (W, H) = self._check_w_h(X, W, H, update_H) (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) = self._compute_regularization(X) if self.solver == 'cd': (W, H, n_iter) = _fit_coordinate_descent(X, W, H, self.tol, self.max_iter, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H=update_H, verbose=self.verbose, shuffle=self.shuffle, random_state=self.random_state) elif self.solver == 'mu': (W, H, n_iter, *_) = _fit_multiplicative_update(X, W, H, self._beta_loss, self.max_iter, self.tol, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H, self.verbose) else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iterations %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) (W, H, n_iter, n_steps) = (W, H, n_iter) self._beta_loss = _beta_loss_to_float(self._beta_loss) if not sp.issparse(X): X = np.atleast_2d(X) W = np.atleast_2d(W) H = np.atleast_2d(H) if self._beta_loss == 2: if sp.issparse(X): norm_X = np.dot(X.data, X.data) norm_WH = trace_dot(np.linalg.multi_dot([W.T, W, H]), H) cross_prod = trace_dot(X * H.T, W) res = (norm_X + norm_WH - 2.0 * cross_prod) / 2.0 else: res = squared_norm(X - np.dot(W, H)) / 2.0 if True: self.reconstruction_err_ = np.sqrt(res * 2) else: self.reconstruction_err_ = res if sp.issparse(X): WH_data = _special_sparse_dot(W, H, X).data X_data = X.data else: WH = np.dot(W, H) WH_data = WH.ravel() X_data = X.ravel() indices = X_data > EPSILON WH_data = WH_data[indices] X_data = X_data[indices] WH_data[WH_data < EPSILON] = EPSILON if self._beta_loss == 1: sum_WH = np.dot(np.sum(W, axis=0), np.sum(H, axis=1)) div = X_data / WH_data res = np.dot(X_data, np.log(div)) res += sum_WH - X_data.sum() elif self._beta_loss == 0: div = X_data / WH_data res = np.sum(div) - np.prod(X.shape) - np.sum(np.log(div)) else: if sp.issparse(X): sum_WH_beta = 0 for i in range(X.shape[1]): sum_WH_beta += np.sum(np.dot(W, H[:, i]) ** self._beta_loss) else: sum_WH_beta = np.sum(WH ** self._beta_loss) sum_X_WH = np.dot(X_data, WH_data ** (self._beta_loss - 1)) res = (X_data ** self._beta_loss).sum() - self._beta_loss * sum_X_WH res += sum_WH_beta * (self._beta_loss - 1) res /= self._beta_loss * (self._beta_loss - 1) if True: res = max(res, 0) self.reconstruction_err_ = np.sqrt(2 * res) else: self.reconstruction_err_ = res self.n_components_ = H.shape[0] self.components_ = H self.n_iter_ = n_iter self.n_steps_ = n_steps return W
def fit_transform(self, X, y=None, W=None, H=None): """Learn a NMF model for the data X and returns the transformed data. This is more efficient than calling fit followed by transform. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Data matrix to be decomposed. y : Ignored Not used, present here for API consistency by convention. W : array-like of shape (n_samples, n_components), default=None If `init='custom'`, it is used as initial guess for the solution. If `None`, uses the initialisation method specified in `init`. H : array-like of shape (n_components, n_features), default=None If `init='custom'`, it is used as initial guess for the solution. If `None`, uses the initialisation method specified in `init`. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. """ self._validate_params() X = self._validate_data(X, accept_sparse=('csr', 'csc'), dtype=[np.float64, np.float32]) with config_context(assume_finite=True): <DeepExtract> check_non_negative(X, 'NMF (input X)') self._check_params(X) if X.min() == 0 and self._beta_loss <= 0: raise ValueError('When beta_loss <= 0 and X contains zeros, the solver may diverge. Please add small values to X, or use a positive beta_loss.') (W, H) = self._check_w_h(X, W, H, update_H) (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) = self._compute_regularization(X) if self.solver == 'cd': (W, H, n_iter) = _fit_coordinate_descent(X, W, H, self.tol, self.max_iter, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H=update_H, verbose=self.verbose, shuffle=self.shuffle, random_state=self.random_state) elif self.solver == 'mu': (W, H, n_iter, *_) = _fit_multiplicative_update(X, W, H, self._beta_loss, self.max_iter, self.tol, l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H, update_H, self.verbose) else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iterations %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) (W, H, n_iter, n_steps) = (W, H, n_iter) </DeepExtract> <DeepExtract> self._beta_loss = _beta_loss_to_float(self._beta_loss) if not sp.issparse(X): X = np.atleast_2d(X) W = np.atleast_2d(W) H = np.atleast_2d(H) if self._beta_loss == 2: if sp.issparse(X): norm_X = np.dot(X.data, X.data) norm_WH = trace_dot(np.linalg.multi_dot([W.T, W, H]), H) cross_prod = trace_dot(X * H.T, W) res = (norm_X + norm_WH - 2.0 * cross_prod) / 2.0 else: res = squared_norm(X - np.dot(W, H)) / 2.0 if True: self.reconstruction_err_ = np.sqrt(res * 2) else: self.reconstruction_err_ = res if sp.issparse(X): WH_data = _special_sparse_dot(W, H, X).data X_data = X.data else: WH = np.dot(W, H) WH_data = WH.ravel() X_data = X.ravel() indices = X_data > EPSILON WH_data = WH_data[indices] X_data = X_data[indices] WH_data[WH_data < EPSILON] = EPSILON if self._beta_loss == 1: sum_WH = np.dot(np.sum(W, axis=0), np.sum(H, axis=1)) div = X_data / WH_data res = np.dot(X_data, np.log(div)) res += sum_WH - X_data.sum() elif self._beta_loss == 0: div = X_data / WH_data res = np.sum(div) - np.prod(X.shape) - np.sum(np.log(div)) else: if sp.issparse(X): sum_WH_beta = 0 for i in range(X.shape[1]): sum_WH_beta += np.sum(np.dot(W, H[:, i]) ** self._beta_loss) else: sum_WH_beta = np.sum(WH ** self._beta_loss) sum_X_WH = np.dot(X_data, WH_data ** (self._beta_loss - 1)) res = (X_data ** self._beta_loss).sum() - self._beta_loss * sum_X_WH res += sum_WH_beta * (self._beta_loss - 1) res /= self._beta_loss * (self._beta_loss - 1) if True: res = max(res, 0) self.reconstruction_err_ = np.sqrt(2 * res) else: self.reconstruction_err_ = res </DeepExtract> self.n_components_ = H.shape[0] self.components_ = H self.n_iter_ = n_iter self.n_steps_ = n_steps return W
def test_same_output_sparse_dense_lasso_and_enet_cv(): random_state = np.random.RandomState(seed) w = random_state.randn(10, n_targets) w[n_informative:] = 0.0 if positive: w = np.abs(w) X = random_state.randn(40, 10) rnd = random_state.uniform(size=(40, 10)) X[rnd > 0.5] = 0.0 y = np.dot(X, w) X = sp.csc_matrix(X) if n_targets == 1: y = np.ravel(y) (X, y) = (X, y) clfs = ElasticNetCV(max_iter=100) clfs.fit(X, y) clfd = ElasticNetCV(max_iter=100) clfd.fit(X.toarray(), y) assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) assert_array_almost_equal(clfs.alphas_, clfd.alphas_) clfs = LassoCV(max_iter=100, cv=4) clfs.fit(X, y) clfd = LassoCV(max_iter=100, cv=4) clfd.fit(X.toarray(), y) assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) assert_array_almost_equal(clfs.alphas_, clfd.alphas_)
def test_same_output_sparse_dense_lasso_and_enet_cv(): <DeepExtract> random_state = np.random.RandomState(seed) w = random_state.randn(10, n_targets) w[n_informative:] = 0.0 if positive: w = np.abs(w) X = random_state.randn(40, 10) rnd = random_state.uniform(size=(40, 10)) X[rnd > 0.5] = 0.0 y = np.dot(X, w) X = sp.csc_matrix(X) if n_targets == 1: y = np.ravel(y) (X, y) = (X, y) </DeepExtract> clfs = ElasticNetCV(max_iter=100) clfs.fit(X, y) clfd = ElasticNetCV(max_iter=100) clfd.fit(X.toarray(), y) assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) assert_array_almost_equal(clfs.alphas_, clfd.alphas_) clfs = LassoCV(max_iter=100, cv=4) clfs.fit(X, y) clfd = LassoCV(max_iter=100, cv=4) clfd.fit(X.toarray(), y) assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) assert_array_almost_equal(clfs.alphas_, clfd.alphas_)
def _eigen_decompose_gram(self, X, y, sqrt_sw): """Eigendecomposition of X.X^T, used when n_samples <= n_features.""" center = self.fit_intercept and sparse.issparse(X) if not center: X_mean = np.zeros(X.shape[1], dtype=X.dtype) (K, X_mean) = (safe_sparse_dot(X, X.T, dense_output=True), X_mean) n_samples = X.shape[0] sample_weight_matrix = sparse.dia_matrix((sqrt_sw, 0), shape=(n_samples, n_samples)) X_weighted = sample_weight_matrix.dot(X) (X_mean, _) = mean_variance_axis(X_weighted, axis=0) X_mean *= n_samples / sqrt_sw.dot(sqrt_sw) X_mX = sqrt_sw[:, None] * safe_sparse_dot(X_mean, X.T, dense_output=True) X_mX_m = np.outer(sqrt_sw, sqrt_sw) * np.dot(X_mean, X_mean) (K, X_mean) = (safe_sparse_dot(X, X.T, dense_output=True) + X_mX_m - X_mX - X_mX.T, X_mean) if self.fit_intercept: K += np.outer(sqrt_sw, sqrt_sw) (eigvals, Q) = linalg.eigh(K) QT_y = np.dot(Q.T, y) return (X_mean, eigvals, Q, QT_y)
def _eigen_decompose_gram(self, X, y, sqrt_sw): """Eigendecomposition of X.X^T, used when n_samples <= n_features.""" <DeepExtract> center = self.fit_intercept and sparse.issparse(X) if not center: X_mean = np.zeros(X.shape[1], dtype=X.dtype) (K, X_mean) = (safe_sparse_dot(X, X.T, dense_output=True), X_mean) n_samples = X.shape[0] sample_weight_matrix = sparse.dia_matrix((sqrt_sw, 0), shape=(n_samples, n_samples)) X_weighted = sample_weight_matrix.dot(X) (X_mean, _) = mean_variance_axis(X_weighted, axis=0) X_mean *= n_samples / sqrt_sw.dot(sqrt_sw) X_mX = sqrt_sw[:, None] * safe_sparse_dot(X_mean, X.T, dense_output=True) X_mX_m = np.outer(sqrt_sw, sqrt_sw) * np.dot(X_mean, X_mean) (K, X_mean) = (safe_sparse_dot(X, X.T, dense_output=True) + X_mX_m - X_mX - X_mX.T, X_mean) </DeepExtract> if self.fit_intercept: K += np.outer(sqrt_sw, sqrt_sw) (eigvals, Q) = linalg.eigh(K) QT_y = np.dot(Q.T, y) return (X_mean, eigvals, Q, QT_y)
def _fit(self, X, partial): has_root = getattr(self, 'root_', None) first_call = not (partial and has_root) X = self._validate_data(X, accept_sparse='csr', copy=self.copy, reset=first_call, dtype=[np.float64, np.float32]) threshold = self.threshold branching_factor = self.branching_factor (n_samples, n_features) = X.shape if first_call: self.root_ = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=True, n_features=n_features, dtype=X.dtype) self.dummy_leaf_ = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=True, n_features=n_features, dtype=X.dtype) self.dummy_leaf_.next_leaf_ = self.root_ self.root_.prev_leaf_ = self.dummy_leaf_ if not sparse.issparse(X): iter_func = iter else: iter_func = _iterate_sparse_X for sample in iter_func(X): subcluster = _CFSubcluster(linear_sum=sample) split = self.root_.insert_cf_subcluster(subcluster) if split: new_subcluster1 = _CFSubcluster() new_subcluster2 = _CFSubcluster() new_node1 = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=self.root_.is_leaf, n_features=self.root_.n_features, dtype=self.root_.init_centroids_.dtype) new_node2 = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=self.root_.is_leaf, n_features=self.root_.n_features, dtype=self.root_.init_centroids_.dtype) new_subcluster1.child_ = new_node1 new_subcluster2.child_ = new_node2 if self.root_.is_leaf: if self.root_.prev_leaf_ is not None: self.root_.prev_leaf_.next_leaf_ = new_node1 new_node1.prev_leaf_ = self.root_.prev_leaf_ new_node1.next_leaf_ = new_node2 new_node2.prev_leaf_ = new_node1 new_node2.next_leaf_ = self.root_.next_leaf_ if self.root_.next_leaf_ is not None: self.root_.next_leaf_.prev_leaf_ = new_node2 dist = euclidean_distances(self.root_.centroids_, Y_norm_squared=self.root_.squared_norm_, squared=True) n_clusters = dist.shape[0] farthest_idx = np.unravel_index(dist.argmax(), (n_clusters, n_clusters)) (node1_dist, node2_dist) = dist[farthest_idx,] node1_closer = node1_dist < node2_dist node1_closer[farthest_idx[0]] = True for (idx, subcluster) in enumerate(self.root_.subclusters_): if node1_closer[idx]: new_node1.append_subcluster(subcluster) new_subcluster1.update(subcluster) else: new_node2.append_subcluster(subcluster) new_subcluster2.update(subcluster) (new_subcluster1, new_subcluster2) = (new_subcluster1, new_subcluster2) del self.root_ self.root_ = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=False, n_features=n_features, dtype=X.dtype) self.root_.append_subcluster(new_subcluster1) self.root_.append_subcluster(new_subcluster2) centroids = np.concatenate([leaf.centroids_ for leaf in self._get_leaves()]) self.subcluster_centers_ = centroids self._n_features_out = self.subcluster_centers_.shape[0] clusterer = self.n_clusters centroids = self.subcluster_centers_ compute_labels = X is not None and self.compute_labels not_enough_centroids = False if isinstance(clusterer, Integral): clusterer = AgglomerativeClustering(n_clusters=self.n_clusters) if len(centroids) < self.n_clusters: not_enough_centroids = True self._subcluster_norms = row_norms(self.subcluster_centers_, squared=True) if clusterer is None or not_enough_centroids: self.subcluster_labels_ = np.arange(len(centroids)) if not_enough_centroids: warnings.warn('Number of subclusters found (%d) by BIRCH is less than (%d). Decrease the threshold.' % (len(centroids), self.n_clusters), ConvergenceWarning) else: self.subcluster_labels_ = clusterer.fit_predict(self.subcluster_centers_) if compute_labels: self.labels_ = self._predict(X) return self
def _fit(self, X, partial): has_root = getattr(self, 'root_', None) first_call = not (partial and has_root) X = self._validate_data(X, accept_sparse='csr', copy=self.copy, reset=first_call, dtype=[np.float64, np.float32]) threshold = self.threshold branching_factor = self.branching_factor (n_samples, n_features) = X.shape if first_call: self.root_ = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=True, n_features=n_features, dtype=X.dtype) self.dummy_leaf_ = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=True, n_features=n_features, dtype=X.dtype) self.dummy_leaf_.next_leaf_ = self.root_ self.root_.prev_leaf_ = self.dummy_leaf_ if not sparse.issparse(X): iter_func = iter else: iter_func = _iterate_sparse_X for sample in iter_func(X): subcluster = _CFSubcluster(linear_sum=sample) split = self.root_.insert_cf_subcluster(subcluster) if split: <DeepExtract> new_subcluster1 = _CFSubcluster() new_subcluster2 = _CFSubcluster() new_node1 = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=self.root_.is_leaf, n_features=self.root_.n_features, dtype=self.root_.init_centroids_.dtype) new_node2 = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=self.root_.is_leaf, n_features=self.root_.n_features, dtype=self.root_.init_centroids_.dtype) new_subcluster1.child_ = new_node1 new_subcluster2.child_ = new_node2 if self.root_.is_leaf: if self.root_.prev_leaf_ is not None: self.root_.prev_leaf_.next_leaf_ = new_node1 new_node1.prev_leaf_ = self.root_.prev_leaf_ new_node1.next_leaf_ = new_node2 new_node2.prev_leaf_ = new_node1 new_node2.next_leaf_ = self.root_.next_leaf_ if self.root_.next_leaf_ is not None: self.root_.next_leaf_.prev_leaf_ = new_node2 dist = euclidean_distances(self.root_.centroids_, Y_norm_squared=self.root_.squared_norm_, squared=True) n_clusters = dist.shape[0] farthest_idx = np.unravel_index(dist.argmax(), (n_clusters, n_clusters)) (node1_dist, node2_dist) = dist[farthest_idx,] node1_closer = node1_dist < node2_dist node1_closer[farthest_idx[0]] = True for (idx, subcluster) in enumerate(self.root_.subclusters_): if node1_closer[idx]: new_node1.append_subcluster(subcluster) new_subcluster1.update(subcluster) else: new_node2.append_subcluster(subcluster) new_subcluster2.update(subcluster) (new_subcluster1, new_subcluster2) = (new_subcluster1, new_subcluster2) </DeepExtract> del self.root_ self.root_ = _CFNode(threshold=threshold, branching_factor=branching_factor, is_leaf=False, n_features=n_features, dtype=X.dtype) self.root_.append_subcluster(new_subcluster1) self.root_.append_subcluster(new_subcluster2) centroids = np.concatenate([leaf.centroids_ for leaf in self._get_leaves()]) self.subcluster_centers_ = centroids self._n_features_out = self.subcluster_centers_.shape[0] <DeepExtract> clusterer = self.n_clusters centroids = self.subcluster_centers_ compute_labels = X is not None and self.compute_labels not_enough_centroids = False if isinstance(clusterer, Integral): clusterer = AgglomerativeClustering(n_clusters=self.n_clusters) if len(centroids) < self.n_clusters: not_enough_centroids = True self._subcluster_norms = row_norms(self.subcluster_centers_, squared=True) if clusterer is None or not_enough_centroids: self.subcluster_labels_ = np.arange(len(centroids)) if not_enough_centroids: warnings.warn('Number of subclusters found (%d) by BIRCH is less than (%d). Decrease the threshold.' % (len(centroids), self.n_clusters), ConvergenceWarning) else: self.subcluster_labels_ = clusterer.fit_predict(self.subcluster_centers_) if compute_labels: self.labels_ = self._predict(X) </DeepExtract> return self
def inverse_transform(self, X): """ Convert the data back to the original representation. When unknown categories are encountered (all zeros in the one-hot encoding), ``None`` is used to represent this category. If the feature with the unknown category has a dropped category, the dropped category will be its inverse. For a given input feature, if there is an infrequent category, 'infrequent_sklearn' will be used to represent the infrequent category. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_encoded_features) The transformed data. Returns ------- X_tr : ndarray of shape (n_samples, n_features) Inverse transformed array. """ check_is_fitted(self) X = check_array(X, accept_sparse='csr') (n_samples, _) = X.shape n_features = len(self.categories_) n_features_out = np.sum(self._n_features_outs) msg = 'Shape of the passed X data is not correct. Expected {0} columns, got {1}.' if X.shape[1] != n_features_out: raise ValueError(msg.format(n_features_out, X.shape[1])) transformed_features = [self._compute_transformed_categories(i, remove_dropped=False) for (i, _) in enumerate(self.categories_)] dt = np.result_type(*[cat.dtype for cat in transformed_features]) X_tr = np.empty((n_samples, n_features), dtype=dt) j = 0 found_unknown = {} if self._infrequent_enabled: infrequent_indices = self._infrequent_indices else: infrequent_indices = [None] * n_features for i in range(n_features): if self._drop_idx_after_grouping is not None and self._drop_idx_after_grouping[i] is not None: cats_wo_dropped = np.delete(transformed_features[i], self._drop_idx_after_grouping[i]) cats_wo_dropped = transformed_features[i] n_categories = cats_wo_dropped.shape[0] if n_categories == 0: X_tr[:, i] = self.categories_[i][self._drop_idx_after_grouping[i]] j += n_categories continue sub = X[:, j:j + n_categories] labels = np.asarray(sub.argmax(axis=1)).flatten() X_tr[:, i] = cats_wo_dropped[labels] if self.handle_unknown == 'ignore' or (self.handle_unknown == 'infrequent_if_exist' and infrequent_indices[i] is None): unknown = np.asarray(sub.sum(axis=1) == 0).flatten() if unknown.any(): if self._drop_idx_after_grouping is None or self._drop_idx_after_grouping[i] is None: found_unknown[i] = unknown else: X_tr[unknown, i] = self.categories_[i][self._drop_idx_after_grouping[i]] else: dropped = np.asarray(sub.sum(axis=1) == 0).flatten() if dropped.any(): if self._drop_idx_after_grouping is None: all_zero_samples = np.flatnonzero(dropped) raise ValueError(f"Samples {all_zero_samples} can not be inverted when drop=None and handle_unknown='error' because they contain all zeros") drop_idx = self._drop_idx_after_grouping[i] X_tr[dropped, i] = transformed_features[i][drop_idx] j += n_categories if found_unknown: if X_tr.dtype != object: X_tr = X_tr.astype(object) for (idx, mask) in found_unknown.items(): X_tr[mask, idx] = None return X_tr
def inverse_transform(self, X): """ Convert the data back to the original representation. When unknown categories are encountered (all zeros in the one-hot encoding), ``None`` is used to represent this category. If the feature with the unknown category has a dropped category, the dropped category will be its inverse. For a given input feature, if there is an infrequent category, 'infrequent_sklearn' will be used to represent the infrequent category. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_encoded_features) The transformed data. Returns ------- X_tr : ndarray of shape (n_samples, n_features) Inverse transformed array. """ check_is_fitted(self) X = check_array(X, accept_sparse='csr') (n_samples, _) = X.shape n_features = len(self.categories_) n_features_out = np.sum(self._n_features_outs) msg = 'Shape of the passed X data is not correct. Expected {0} columns, got {1}.' if X.shape[1] != n_features_out: raise ValueError(msg.format(n_features_out, X.shape[1])) transformed_features = [self._compute_transformed_categories(i, remove_dropped=False) for (i, _) in enumerate(self.categories_)] dt = np.result_type(*[cat.dtype for cat in transformed_features]) X_tr = np.empty((n_samples, n_features), dtype=dt) j = 0 found_unknown = {} if self._infrequent_enabled: infrequent_indices = self._infrequent_indices else: infrequent_indices = [None] * n_features for i in range(n_features): <DeepExtract> if self._drop_idx_after_grouping is not None and self._drop_idx_after_grouping[i] is not None: cats_wo_dropped = np.delete(transformed_features[i], self._drop_idx_after_grouping[i]) cats_wo_dropped = transformed_features[i] </DeepExtract> n_categories = cats_wo_dropped.shape[0] if n_categories == 0: X_tr[:, i] = self.categories_[i][self._drop_idx_after_grouping[i]] j += n_categories continue sub = X[:, j:j + n_categories] labels = np.asarray(sub.argmax(axis=1)).flatten() X_tr[:, i] = cats_wo_dropped[labels] if self.handle_unknown == 'ignore' or (self.handle_unknown == 'infrequent_if_exist' and infrequent_indices[i] is None): unknown = np.asarray(sub.sum(axis=1) == 0).flatten() if unknown.any(): if self._drop_idx_after_grouping is None or self._drop_idx_after_grouping[i] is None: found_unknown[i] = unknown else: X_tr[unknown, i] = self.categories_[i][self._drop_idx_after_grouping[i]] else: dropped = np.asarray(sub.sum(axis=1) == 0).flatten() if dropped.any(): if self._drop_idx_after_grouping is None: all_zero_samples = np.flatnonzero(dropped) raise ValueError(f"Samples {all_zero_samples} can not be inverted when drop=None and handle_unknown='error' because they contain all zeros") drop_idx = self._drop_idx_after_grouping[i] X_tr[dropped, i] = transformed_features[i][drop_idx] j += n_categories if found_unknown: if X_tr.dtype != object: X_tr = X_tr.astype(object) for (idx, mask) in found_unknown.items(): X_tr[mask, idx] = None return X_tr
@contextmanager def config_context(*, assume_finite=None, working_memory=None, print_changed_only=None, display=None, pairwise_dist_chunk_size=None, enable_cython_pairwise_dist=None, array_api_dispatch=None, transform_output=None): """Context manager for global scikit-learn configuration. Parameters ---------- assume_finite : bool, default=None If True, validation for finiteness will be skipped, saving time, but leading to potential crashes. If False, validation for finiteness will be performed, avoiding error. If None, the existing value won't change. The default value is False. working_memory : int, default=None If set, scikit-learn will attempt to limit the size of temporary arrays to this number of MiB (per job when parallelised), often saving both computation time and memory on expensive operations that can be performed in chunks. If None, the existing value won't change. The default value is 1024. print_changed_only : bool, default=None If True, only the parameters that were set to non-default values will be printed when printing an estimator. For example, ``print(SVC())`` while True will only print 'SVC()', but would print 'SVC(C=1.0, cache_size=200, ...)' with all the non-changed parameters when False. If None, the existing value won't change. The default value is True. .. versionchanged:: 0.23 Default changed from False to True. display : {'text', 'diagram'}, default=None If 'diagram', estimators will be displayed as a diagram in a Jupyter lab or notebook context. If 'text', estimators will be displayed as text. If None, the existing value won't change. The default value is 'diagram'. .. versionadded:: 0.23 pairwise_dist_chunk_size : int, default=None The number of row vectors per chunk for the accelerated pairwise- distances reduction backend. Default is 256 (suitable for most of modern laptops' caches and architectures). Intended for easier benchmarking and testing of scikit-learn internals. End users are not expected to benefit from customizing this configuration setting. .. versionadded:: 1.1 enable_cython_pairwise_dist : bool, default=None Use the accelerated pairwise-distances reduction backend when possible. Global default: True. Intended for easier benchmarking and testing of scikit-learn internals. End users are not expected to benefit from customizing this configuration setting. .. versionadded:: 1.1 array_api_dispatch : bool, default=None Use Array API dispatching when inputs follow the Array API standard. Default is False. See the :ref:`User Guide <array_api>` for more details. .. versionadded:: 1.2 transform_output : str, default=None Configure output of `transform` and `fit_transform`. See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py` for an example on how to use the API. - `"default"`: Default output format of a transformer - `"pandas"`: DataFrame output - `None`: Transform configuration is unchanged .. versionadded:: 1.2 Yields ------ None. See Also -------- set_config : Set global scikit-learn configuration. get_config : Retrieve current values of the global configuration. Notes ----- All settings, not just those presently modified, will be returned to their previous values when the context manager is exited. Examples -------- >>> import sklearn >>> from sklearn.utils.validation import assert_all_finite >>> with sklearn.config_context(assume_finite=True): ... assert_all_finite([float('nan')]) >>> with sklearn.config_context(assume_finite=True): ... with sklearn.config_context(assume_finite=False): ... assert_all_finite([float('nan')]) Traceback (most recent call last): ... ValueError: Input contains NaN... """ old_config = _get_threadlocal_config().copy() local_config = _get_threadlocal_config() if assume_finite is not None: local_config['assume_finite'] = assume_finite if working_memory is not None: local_config['working_memory'] = working_memory if print_changed_only is not None: local_config['print_changed_only'] = print_changed_only if display is not None: local_config['display'] = display if pairwise_dist_chunk_size is not None: local_config['pairwise_dist_chunk_size'] = pairwise_dist_chunk_size if enable_cython_pairwise_dist is not None: local_config['enable_cython_pairwise_dist'] = enable_cython_pairwise_dist if array_api_dispatch is not None: local_config['array_api_dispatch'] = array_api_dispatch if transform_output is not None: local_config['transform_output'] = transform_output try: yield finally: local_config = _get_threadlocal_config() if assume_finite is not None: local_config['assume_finite'] = assume_finite if working_memory is not None: local_config['working_memory'] = working_memory if print_changed_only is not None: local_config['print_changed_only'] = print_changed_only if display is not None: local_config['display'] = display if pairwise_dist_chunk_size is not None: local_config['pairwise_dist_chunk_size'] = pairwise_dist_chunk_size if enable_cython_pairwise_dist is not None: local_config['enable_cython_pairwise_dist'] = enable_cython_pairwise_dist if array_api_dispatch is not None: local_config['array_api_dispatch'] = array_api_dispatch if transform_output is not None: local_config['transform_output'] = transform_output </DeepExtract>
@contextmanager def config_context(*, assume_finite=None, working_memory=None, print_changed_only=None, display=None, pairwise_dist_chunk_size=None, enable_cython_pairwise_dist=None, array_api_dispatch=None, transform_output=None): """Context manager for global scikit-learn configuration. Parameters ---------- assume_finite : bool, default=None If True, validation for finiteness will be skipped, saving time, but leading to potential crashes. If False, validation for finiteness will be performed, avoiding error. If None, the existing value won't change. The default value is False. working_memory : int, default=None If set, scikit-learn will attempt to limit the size of temporary arrays to this number of MiB (per job when parallelised), often saving both computation time and memory on expensive operations that can be performed in chunks. If None, the existing value won't change. The default value is 1024. print_changed_only : bool, default=None If True, only the parameters that were set to non-default values will be printed when printing an estimator. For example, ``print(SVC())`` while True will only print 'SVC()', but would print 'SVC(C=1.0, cache_size=200, ...)' with all the non-changed parameters when False. If None, the existing value won't change. The default value is True. .. versionchanged:: 0.23 Default changed from False to True. display : {'text', 'diagram'}, default=None If 'diagram', estimators will be displayed as a diagram in a Jupyter lab or notebook context. If 'text', estimators will be displayed as text. If None, the existing value won't change. The default value is 'diagram'. .. versionadded:: 0.23 pairwise_dist_chunk_size : int, default=None The number of row vectors per chunk for the accelerated pairwise- distances reduction backend. Default is 256 (suitable for most of modern laptops' caches and architectures). Intended for easier benchmarking and testing of scikit-learn internals. End users are not expected to benefit from customizing this configuration setting. .. versionadded:: 1.1 enable_cython_pairwise_dist : bool, default=None Use the accelerated pairwise-distances reduction backend when possible. Global default: True. Intended for easier benchmarking and testing of scikit-learn internals. End users are not expected to benefit from customizing this configuration setting. .. versionadded:: 1.1 array_api_dispatch : bool, default=None Use Array API dispatching when inputs follow the Array API standard. Default is False. See the :ref:`User Guide <array_api>` for more details. .. versionadded:: 1.2 transform_output : str, default=None Configure output of `transform` and `fit_transform`. See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py` for an example on how to use the API. - `"default"`: Default output format of a transformer - `"pandas"`: DataFrame output - `None`: Transform configuration is unchanged .. versionadded:: 1.2 Yields ------ None. See Also -------- set_config : Set global scikit-learn configuration. get_config : Retrieve current values of the global configuration. Notes ----- All settings, not just those presently modified, will be returned to their previous values when the context manager is exited. Examples -------- >>> import sklearn >>> from sklearn.utils.validation import assert_all_finite >>> with sklearn.config_context(assume_finite=True): ... assert_all_finite([float('nan')]) >>> with sklearn.config_context(assume_finite=True): ... with sklearn.config_context(assume_finite=False): ... assert_all_finite([float('nan')]) Traceback (most recent call last): ... ValueError: Input contains NaN... """ <DeepExtract> old_config = _get_threadlocal_config().copy() </DeepExtract> <DeepExtract> local_config = _get_threadlocal_config() if assume_finite is not None: local_config['assume_finite'] = assume_finite if working_memory is not None: local_config['working_memory'] = working_memory if print_changed_only is not None: local_config['print_changed_only'] = print_changed_only if display is not None: local_config['display'] = display if pairwise_dist_chunk_size is not None: local_config['pairwise_dist_chunk_size'] = pairwise_dist_chunk_size if enable_cython_pairwise_dist is not None: local_config['enable_cython_pairwise_dist'] = enable_cython_pairwise_dist if array_api_dispatch is not None: local_config['array_api_dispatch'] = array_api_dispatch if transform_output is not None: local_config['transform_output'] = transform_output </DeepExtract> try: yield finally: <DeepExtract> local_config = _get_threadlocal_config() if assume_finite is not None: local_config['assume_finite'] = assume_finite if working_memory is not None: local_config['working_memory'] = working_memory if print_changed_only is not None: local_config['print_changed_only'] = print_changed_only if display is not None: local_config['display'] = display if pairwise_dist_chunk_size is not None: local_config['pairwise_dist_chunk_size'] = pairwise_dist_chunk_size if enable_cython_pairwise_dist is not None: local_config['enable_cython_pairwise_dist'] = enable_cython_pairwise_dist if array_api_dispatch is not None: local_config['array_api_dispatch'] = array_api_dispatch if transform_output is not None: local_config['transform_output'] = transform_output </DeepExtract>
def _ledoit_wolf(X, *, assume_centered, block_size): """Estimate the shrunk Ledoit-Wolf covariance matrix.""" if len(X.shape) == 2 and X.shape[1] == 1: if not assume_centered: X = X - X.mean() return (np.atleast_2d((X ** 2).mean()), 0.0) n_features = X.shape[1] X = check_array(X) if len(X.shape) == 2 and X.shape[1] == 1: shrinkage = 0.0 if X.ndim == 1: X = np.reshape(X, (1, -1)) if X.shape[0] == 1: warnings.warn('Only one sample available. You may want to reshape your data array') (n_samples, n_features) = X.shape if not assume_centered: X = X - X.mean(0) n_splits = int(n_features / block_size) X2 = X ** 2 emp_cov_trace = np.sum(X2, axis=0) / n_samples mu = np.sum(emp_cov_trace) / n_features beta_ = 0.0 delta_ = 0.0 for i in range(n_splits): for j in range(n_splits): rows = slice(block_size * i, block_size * (i + 1)) cols = slice(block_size * j, block_size * (j + 1)) beta_ += np.sum(np.dot(X2.T[rows], X2[:, cols])) delta_ += np.sum(np.dot(X.T[rows], X[:, cols]) ** 2) rows = slice(block_size * i, block_size * (i + 1)) beta_ += np.sum(np.dot(X2.T[rows], X2[:, block_size * n_splits:])) delta_ += np.sum(np.dot(X.T[rows], X[:, block_size * n_splits:]) ** 2) for j in range(n_splits): cols = slice(block_size * j, block_size * (j + 1)) beta_ += np.sum(np.dot(X2.T[block_size * n_splits:], X2[:, cols])) delta_ += np.sum(np.dot(X.T[block_size * n_splits:], X[:, cols]) ** 2) delta_ += np.sum(np.dot(X.T[block_size * n_splits:], X[:, block_size * n_splits:]) ** 2) delta_ /= n_samples ** 2 beta_ += np.sum(np.dot(X2.T[block_size * n_splits:], X2[:, block_size * n_splits:])) beta = 1.0 / (n_features * n_samples) * (beta_ / n_samples - delta_) delta = delta_ - 2.0 * mu * emp_cov_trace.sum() + n_features * mu ** 2 delta /= n_features beta = min(beta, delta) shrinkage = 0 if beta == 0 else beta / delta shrinkage = shrinkage emp_cov = empirical_covariance(X, assume_centered=assume_centered) mu = np.sum(np.trace(emp_cov)) / n_features shrunk_cov = (1.0 - shrinkage) * emp_cov shrunk_cov.flat[::n_features + 1] += shrinkage * mu return (shrunk_cov, shrinkage)
def _ledoit_wolf(X, *, assume_centered, block_size): """Estimate the shrunk Ledoit-Wolf covariance matrix.""" if len(X.shape) == 2 and X.shape[1] == 1: if not assume_centered: X = X - X.mean() return (np.atleast_2d((X ** 2).mean()), 0.0) n_features = X.shape[1] <DeepExtract> X = check_array(X) if len(X.shape) == 2 and X.shape[1] == 1: shrinkage = 0.0 if X.ndim == 1: X = np.reshape(X, (1, -1)) if X.shape[0] == 1: warnings.warn('Only one sample available. You may want to reshape your data array') (n_samples, n_features) = X.shape if not assume_centered: X = X - X.mean(0) n_splits = int(n_features / block_size) X2 = X ** 2 emp_cov_trace = np.sum(X2, axis=0) / n_samples mu = np.sum(emp_cov_trace) / n_features beta_ = 0.0 delta_ = 0.0 for i in range(n_splits): for j in range(n_splits): rows = slice(block_size * i, block_size * (i + 1)) cols = slice(block_size * j, block_size * (j + 1)) beta_ += np.sum(np.dot(X2.T[rows], X2[:, cols])) delta_ += np.sum(np.dot(X.T[rows], X[:, cols]) ** 2) rows = slice(block_size * i, block_size * (i + 1)) beta_ += np.sum(np.dot(X2.T[rows], X2[:, block_size * n_splits:])) delta_ += np.sum(np.dot(X.T[rows], X[:, block_size * n_splits:]) ** 2) for j in range(n_splits): cols = slice(block_size * j, block_size * (j + 1)) beta_ += np.sum(np.dot(X2.T[block_size * n_splits:], X2[:, cols])) delta_ += np.sum(np.dot(X.T[block_size * n_splits:], X[:, cols]) ** 2) delta_ += np.sum(np.dot(X.T[block_size * n_splits:], X[:, block_size * n_splits:]) ** 2) delta_ /= n_samples ** 2 beta_ += np.sum(np.dot(X2.T[block_size * n_splits:], X2[:, block_size * n_splits:])) beta = 1.0 / (n_features * n_samples) * (beta_ / n_samples - delta_) delta = delta_ - 2.0 * mu * emp_cov_trace.sum() + n_features * mu ** 2 delta /= n_features beta = min(beta, delta) shrinkage = 0 if beta == 0 else beta / delta shrinkage = shrinkage </DeepExtract> emp_cov = empirical_covariance(X, assume_centered=assume_centered) mu = np.sum(np.trace(emp_cov)) / n_features shrunk_cov = (1.0 - shrinkage) * emp_cov shrunk_cov.flat[::n_features + 1] += shrinkage * mu return (shrunk_cov, shrinkage)
def _open_openml_url(openml_path: str, data_home: Optional[str], n_retries: int=3, delay: float=1.0): """ Returns a resource from OpenML.org. Caches it to data_home if required. Parameters ---------- openml_path : str OpenML URL that will be accessed. This will be prefixes with _OPENML_PREFIX. data_home : str Directory to which the files will be cached. If None, no caching will be applied. n_retries : int, default=3 Number of retries when HTTP errors are encountered. Error with status code 412 won't be retried as they represent OpenML generic errors. delay : float, default=1.0 Number of seconds between retries. Returns ------- result : stream A stream to the OpenML resource. """ def is_gzip_encoded(_fsrc): return _fsrc.info().get('Content-Encoding', '') == 'gzip' req = Request(_OPENML_PREFIX + openml_path) req.add_header('Accept-encoding', 'gzip') if data_home is None: fsrc = _retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req) if is_gzip_encoded(fsrc): return gzip.GzipFile(fileobj=fsrc, mode='rb') return fsrc local_path = os.path.join(data_home, 'openml.org', openml_path + '.gz') (dir_name, file_name) = os.path.split(local_path) if not os.path.exists(local_path): os.makedirs(dir_name, exist_ok=True) try: with TemporaryDirectory(dir=dir_name) as tmpdir: with closing(_retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req)) as fsrc: opener: Callable if is_gzip_encoded(fsrc): opener = open else: opener = gzip.GzipFile with opener(os.path.join(tmpdir, file_name), 'wb') as fdst: shutil.copyfileobj(fsrc, fdst) shutil.move(fdst.name, local_path) except Exception: if os.path.exists(local_path): os.unlink(local_path) raise return gzip.GzipFile(local_path, 'rb')
def _open_openml_url(openml_path: str, data_home: Optional[str], n_retries: int=3, delay: float=1.0): """ Returns a resource from OpenML.org. Caches it to data_home if required. Parameters ---------- openml_path : str OpenML URL that will be accessed. This will be prefixes with _OPENML_PREFIX. data_home : str Directory to which the files will be cached. If None, no caching will be applied. n_retries : int, default=3 Number of retries when HTTP errors are encountered. Error with status code 412 won't be retried as they represent OpenML generic errors. delay : float, default=1.0 Number of seconds between retries. Returns ------- result : stream A stream to the OpenML resource. """ def is_gzip_encoded(_fsrc): return _fsrc.info().get('Content-Encoding', '') == 'gzip' req = Request(_OPENML_PREFIX + openml_path) req.add_header('Accept-encoding', 'gzip') if data_home is None: fsrc = _retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req) if is_gzip_encoded(fsrc): return gzip.GzipFile(fileobj=fsrc, mode='rb') return fsrc <DeepExtract> local_path = os.path.join(data_home, 'openml.org', openml_path + '.gz') </DeepExtract> (dir_name, file_name) = os.path.split(local_path) if not os.path.exists(local_path): os.makedirs(dir_name, exist_ok=True) try: with TemporaryDirectory(dir=dir_name) as tmpdir: with closing(_retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req)) as fsrc: opener: Callable if is_gzip_encoded(fsrc): opener = open else: opener = gzip.GzipFile with opener(os.path.join(tmpdir, file_name), 'wb') as fdst: shutil.copyfileobj(fsrc, fdst) shutil.move(fdst.name, local_path) except Exception: if os.path.exists(local_path): os.unlink(local_path) raise return gzip.GzipFile(local_path, 'rb')
@validate_params({'labels_true': ['array-like', None], 'labels_pred': ['array-like', None], 'contingency': ['array-like', 'sparse matrix', None]}) def mutual_info_score(labels_true, labels_pred, *, contingency=None): """Mutual Information between two clusterings. The Mutual Information is a measure of the similarity between two labels of the same data. Where :math:`|U_i|` is the number of the samples in cluster :math:`U_i` and :math:`|V_j|` is the number of the samples in cluster :math:`V_j`, the Mutual Information between clusterings :math:`U` and :math:`V` is given as: .. math:: MI(U,V)=\\sum_{i=1}^{|U|} \\sum_{j=1}^{|V|} \\frac{|U_i\\cap V_j|}{N} \\log\\frac{N|U_i \\cap V_j|}{|U_i||V_j|} This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching :math:`U` (i.e ``label_true``) with :math:`V` (i.e. ``label_pred``) will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Read more in the :ref:`User Guide <mutual_info_score>`. Parameters ---------- labels_true : array-like of shape (n_samples,), dtype=integral A clustering of the data into disjoint subsets, called :math:`U` in the above formula. labels_pred : array-like of shape (n_samples,), dtype=integral A clustering of the data into disjoint subsets, called :math:`V` in the above formula. contingency : {array-like, sparse matrix} of shape (n_classes_true, n_classes_pred), default=None A contingency matrix given by the :func:`contingency_matrix` function. If value is ``None``, it will be computed, otherwise the given value is used, with ``labels_true`` and ``labels_pred`` ignored. Returns ------- mi : float Mutual information, a non-negative value, measured in nats using the natural logarithm. See Also -------- adjusted_mutual_info_score : Adjusted against chance Mutual Information. normalized_mutual_info_score : Normalized Mutual Information. Notes ----- The logarithm used is the natural logarithm (base-e). """ if contingency is None: labels_true = check_array(labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None) labels_pred = check_array(labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None) type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred) if 'continuous' in (type_pred, type_label): msg = f'Clustering metrics expects discrete values but received {type_label} values for label, and {type_pred} values for target' warnings.warn(msg, UserWarning) if labels_true.ndim != 1: raise ValueError('labels_true must be 1D: shape is %r' % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError('labels_pred must be 1D: shape is %r' % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred) (labels_true, labels_pred) = (labels_true, labels_pred) if eps is not None and True: raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] contingency = sp.coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype) if True: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: contingency = contingency + eps contingency = contingency else: contingency = check_array(contingency, accept_sparse=['csr', 'csc', 'coo'], dtype=[int, np.int32, np.int64]) if isinstance(contingency, np.ndarray): (nzx, nzy) = np.nonzero(contingency) nz_val = contingency[nzx, nzy] else: (nzx, nzy, nz_val) = sp.find(contingency) contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0)) if pi.size == 1 or pj.size == 1: return 0.0 log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(np.int64, copy=False) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) return np.clip(mi.sum(), 0.0, None)
@validate_params({'labels_true': ['array-like', None], 'labels_pred': ['array-like', None], 'contingency': ['array-like', 'sparse matrix', None]}) def mutual_info_score(labels_true, labels_pred, *, contingency=None): """Mutual Information between two clusterings. The Mutual Information is a measure of the similarity between two labels of the same data. Where :math:`|U_i|` is the number of the samples in cluster :math:`U_i` and :math:`|V_j|` is the number of the samples in cluster :math:`V_j`, the Mutual Information between clusterings :math:`U` and :math:`V` is given as: .. math:: MI(U,V)=\\sum_{i=1}^{|U|} \\sum_{j=1}^{|V|} \\frac{|U_i\\cap V_j|}{N} \\log\\frac{N|U_i \\cap V_j|}{|U_i||V_j|} This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching :math:`U` (i.e ``label_true``) with :math:`V` (i.e. ``label_pred``) will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Read more in the :ref:`User Guide <mutual_info_score>`. Parameters ---------- labels_true : array-like of shape (n_samples,), dtype=integral A clustering of the data into disjoint subsets, called :math:`U` in the above formula. labels_pred : array-like of shape (n_samples,), dtype=integral A clustering of the data into disjoint subsets, called :math:`V` in the above formula. contingency : {array-like, sparse matrix} of shape (n_classes_true, n_classes_pred), default=None A contingency matrix given by the :func:`contingency_matrix` function. If value is ``None``, it will be computed, otherwise the given value is used, with ``labels_true`` and ``labels_pred`` ignored. Returns ------- mi : float Mutual information, a non-negative value, measured in nats using the natural logarithm. See Also -------- adjusted_mutual_info_score : Adjusted against chance Mutual Information. normalized_mutual_info_score : Normalized Mutual Information. Notes ----- The logarithm used is the natural logarithm (base-e). """ if contingency is None: <DeepExtract> labels_true = check_array(labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None) labels_pred = check_array(labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None) type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred) if 'continuous' in (type_pred, type_label): msg = f'Clustering metrics expects discrete values but received {type_label} values for label, and {type_pred} values for target' warnings.warn(msg, UserWarning) if labels_true.ndim != 1: raise ValueError('labels_true must be 1D: shape is %r' % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError('labels_pred must be 1D: shape is %r' % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred) (labels_true, labels_pred) = (labels_true, labels_pred) </DeepExtract> <DeepExtract> if eps is not None and True: raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] contingency = sp.coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype) if True: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: contingency = contingency + eps contingency = contingency </DeepExtract> else: contingency = check_array(contingency, accept_sparse=['csr', 'csc', 'coo'], dtype=[int, np.int32, np.int64]) if isinstance(contingency, np.ndarray): (nzx, nzy) = np.nonzero(contingency) nz_val = contingency[nzx, nzy] else: (nzx, nzy, nz_val) = sp.find(contingency) contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0)) if pi.size == 1 or pj.size == 1: return 0.0 log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(np.int64, copy=False) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) return np.clip(mi.sum(), 0.0, None)
@validate_params({'y_true': ['array-like'], 'y_pred': ['array-like'], 'sample_weight': ['array-like', None], 'alpha': [Interval(Real, 0, 1, closed='both')], 'multioutput': [StrOptions({'raw_values', 'uniform_average'}), 'array-like']}) def d2_pinball_score(y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput='uniform_average'): """ :math:`D^2` regression score function, fraction of pinball loss explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical alpha-quantile of `y_true` as constant prediction, disregarding the input features, gets a :math:`D^2` score of 0.0. Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.1 Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. alpha : float, default=0.5 Slope of the pinball deviance. It determines the quantile level alpha for which the pinball deviance and also D2 are optimal. The default `alpha=0.5` is equivalent to `d2_absolute_error_score`. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. Returns ------- score : float or ndarray of floats The :math:`D^2` score with a pinball deviance or ndarray of scores if `multioutput='raw_values'`. Notes ----- Like :math:`R^2`, :math:`D^2` score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for a single point and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999). "Goodness of Fit and Related Inference Processes for Quantile Regression" <http://dx.doi.org/10.1080/01621459.1999.10473882>`_ .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ Examples -------- >>> from sklearn.metrics import d2_pinball_score >>> y_true = [1, 2, 3] >>> y_pred = [1, 3, 3] >>> d2_pinball_score(y_true, y_pred) 0.5 >>> d2_pinball_score(y_true, y_pred, alpha=0.9) 0.772... >>> d2_pinball_score(y_true, y_pred, alpha=0.1) -1.045... >>> d2_pinball_score(y_true, y_true, alpha=0.1) 1.0 """ check_consistent_length(y_true, y_pred) y_true = check_array(y_true, ensure_2d=False, dtype=dtype) y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) if y_true.ndim == 1: y_true = y_true.reshape((-1, 1)) if y_pred.ndim == 1: y_pred = y_pred.reshape((-1, 1)) if y_true.shape[1] != y_pred.shape[1]: raise ValueError('y_true and y_pred have different number of output ({0}!={1})'.format(y_true.shape[1], y_pred.shape[1])) n_outputs = y_true.shape[1] allowed_multioutput_str = ('raw_values', 'uniform_average', 'variance_weighted') if isinstance(multioutput, str): if multioutput not in allowed_multioutput_str: raise ValueError("Allowed 'multioutput' string values are {}. You provided multioutput={!r}".format(allowed_multioutput_str, multioutput)) elif multioutput is not None: multioutput = check_array(multioutput, ensure_2d=False) if n_outputs == 1: raise ValueError('Custom weights are useful only in multi-output cases.') elif n_outputs != len(multioutput): raise ValueError('There must be equally many custom weights (%d) as outputs (%d).' % (len(multioutput), n_outputs)) y_type = 'continuous' if n_outputs == 1 else 'continuous-multioutput' (y_type, y_true, y_pred, multioutput) = (y_type, y_true, y_pred, multioutput) check_consistent_length(y_true, y_pred, sample_weight) if _num_samples(y_pred) < 2: msg = 'D^2 score is not well-defined with less than two samples.' warnings.warn(msg, UndefinedMetricWarning) return float('nan') (y_type, y_true, y_pred, 'raw_values') = _check_reg_targets(y_true, y_pred, 'raw_values') check_consistent_length(y_true, y_pred, sample_weight) diff = y_true - y_pred sign = (diff >= 0).astype(diff.dtype) loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff output_errors = np.average(loss, weights=sample_weight, axis=0) if isinstance('raw_values', str) and 'raw_values' == 'raw_values': numerator = output_errors if isinstance('raw_values', str) and 'raw_values' == 'uniform_average': 'raw_values' = None numerator = np.average(output_errors, weights='raw_values') if sample_weight is None: y_quantile = np.tile(np.percentile(y_true, q=alpha * 100, axis=0), (len(y_true), 1)) else: sample_weight = _check_sample_weight(sample_weight, y_true) y_quantile = np.tile(_weighted_percentile(y_true, sample_weight=sample_weight, percentile=alpha * 100), (len(y_true), 1)) (y_type, y_true, y_quantile, 'raw_values') = _check_reg_targets(y_true, y_quantile, 'raw_values') check_consistent_length(y_true, y_quantile, sample_weight) diff = y_true - y_quantile sign = (diff >= 0).astype(diff.dtype) loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff output_errors = np.average(loss, weights=sample_weight, axis=0) if isinstance('raw_values', str) and 'raw_values' == 'raw_values': denominator = output_errors if isinstance('raw_values', str) and 'raw_values' == 'uniform_average': 'raw_values' = None denominator = np.average(output_errors, weights='raw_values') nonzero_numerator = numerator != 0 nonzero_denominator = denominator != 0 valid_score = nonzero_numerator & nonzero_denominator output_scores = np.ones(y_true.shape[1]) output_scores[valid_score] = 1 - numerator[valid_score] / denominator[valid_score] output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 if isinstance(multioutput, str): if multioutput == 'raw_values': return output_scores else: avg_weights = None else: avg_weights = multioutput return np.average(output_scores, weights=avg_weights)
@validate_params({'y_true': ['array-like'], 'y_pred': ['array-like'], 'sample_weight': ['array-like', None], 'alpha': [Interval(Real, 0, 1, closed='both')], 'multioutput': [StrOptions({'raw_values', 'uniform_average'}), 'array-like']}) def d2_pinball_score(y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput='uniform_average'): """ :math:`D^2` regression score function, fraction of pinball loss explained. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A model that always uses the empirical alpha-quantile of `y_true` as constant prediction, disregarding the input features, gets a :math:`D^2` score of 0.0. Read more in the :ref:`User Guide <d2_score>`. .. versionadded:: 1.1 Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. alpha : float, default=0.5 Slope of the pinball deviance. It determines the quantile level alpha for which the pinball deviance and also D2 are optimal. The default `alpha=0.5` is equivalent to `d2_absolute_error_score`. multioutput : {'raw_values', 'uniform_average'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output values. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of errors in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. Returns ------- score : float or ndarray of floats The :math:`D^2` score with a pinball deviance or ndarray of scores if `multioutput='raw_values'`. Notes ----- Like :math:`R^2`, :math:`D^2` score may be negative (it need not actually be the square of a quantity D). This metric is not well-defined for a single point and will return a NaN value if n_samples is less than two. References ---------- .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999). "Goodness of Fit and Related Inference Processes for Quantile Regression" <http://dx.doi.org/10.1080/01621459.1999.10473882>`_ .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. Wainwright. "Statistical Learning with Sparsity: The Lasso and Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ Examples -------- >>> from sklearn.metrics import d2_pinball_score >>> y_true = [1, 2, 3] >>> y_pred = [1, 3, 3] >>> d2_pinball_score(y_true, y_pred) 0.5 >>> d2_pinball_score(y_true, y_pred, alpha=0.9) 0.772... >>> d2_pinball_score(y_true, y_pred, alpha=0.1) -1.045... >>> d2_pinball_score(y_true, y_true, alpha=0.1) 1.0 """ <DeepExtract> check_consistent_length(y_true, y_pred) y_true = check_array(y_true, ensure_2d=False, dtype=dtype) y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) if y_true.ndim == 1: y_true = y_true.reshape((-1, 1)) if y_pred.ndim == 1: y_pred = y_pred.reshape((-1, 1)) if y_true.shape[1] != y_pred.shape[1]: raise ValueError('y_true and y_pred have different number of output ({0}!={1})'.format(y_true.shape[1], y_pred.shape[1])) n_outputs = y_true.shape[1] allowed_multioutput_str = ('raw_values', 'uniform_average', 'variance_weighted') if isinstance(multioutput, str): if multioutput not in allowed_multioutput_str: raise ValueError("Allowed 'multioutput' string values are {}. You provided multioutput={!r}".format(allowed_multioutput_str, multioutput)) elif multioutput is not None: multioutput = check_array(multioutput, ensure_2d=False) if n_outputs == 1: raise ValueError('Custom weights are useful only in multi-output cases.') elif n_outputs != len(multioutput): raise ValueError('There must be equally many custom weights (%d) as outputs (%d).' % (len(multioutput), n_outputs)) y_type = 'continuous' if n_outputs == 1 else 'continuous-multioutput' (y_type, y_true, y_pred, multioutput) = (y_type, y_true, y_pred, multioutput) </DeepExtract> check_consistent_length(y_true, y_pred, sample_weight) if _num_samples(y_pred) < 2: msg = 'D^2 score is not well-defined with less than two samples.' warnings.warn(msg, UndefinedMetricWarning) return float('nan') <DeepExtract> (y_type, y_true, y_pred, 'raw_values') = _check_reg_targets(y_true, y_pred, 'raw_values') check_consistent_length(y_true, y_pred, sample_weight) diff = y_true - y_pred sign = (diff >= 0).astype(diff.dtype) loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff output_errors = np.average(loss, weights=sample_weight, axis=0) if isinstance('raw_values', str) and 'raw_values' == 'raw_values': numerator = output_errors if isinstance('raw_values', str) and 'raw_values' == 'uniform_average': 'raw_values' = None numerator = np.average(output_errors, weights='raw_values') </DeepExtract> if sample_weight is None: y_quantile = np.tile(np.percentile(y_true, q=alpha * 100, axis=0), (len(y_true), 1)) else: sample_weight = _check_sample_weight(sample_weight, y_true) y_quantile = np.tile(_weighted_percentile(y_true, sample_weight=sample_weight, percentile=alpha * 100), (len(y_true), 1)) <DeepExtract> (y_type, y_true, y_quantile, 'raw_values') = _check_reg_targets(y_true, y_quantile, 'raw_values') check_consistent_length(y_true, y_quantile, sample_weight) diff = y_true - y_quantile sign = (diff >= 0).astype(diff.dtype) loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff output_errors = np.average(loss, weights=sample_weight, axis=0) if isinstance('raw_values', str) and 'raw_values' == 'raw_values': denominator = output_errors if isinstance('raw_values', str) and 'raw_values' == 'uniform_average': 'raw_values' = None denominator = np.average(output_errors, weights='raw_values') </DeepExtract> nonzero_numerator = numerator != 0 nonzero_denominator = denominator != 0 valid_score = nonzero_numerator & nonzero_denominator output_scores = np.ones(y_true.shape[1]) output_scores[valid_score] = 1 - numerator[valid_score] / denominator[valid_score] output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 if isinstance(multioutput, str): if multioutput == 'raw_values': return output_scores else: avg_weights = None else: avg_weights = multioutput return np.average(output_scores, weights=avg_weights)
def test_random_search_cv_results(): (X, y) = make_classification(n_samples=50, n_features=4, random_state=42) n_splits = 3 n_search_iter = 30 params = [{'kernel': ['rbf'], 'C': expon(scale=10), 'gamma': expon(scale=0.1)}, {'kernel': ['poly'], 'degree': [2, 3]}] param_keys = ('param_C', 'param_degree', 'param_gamma', 'param_kernel') score_keys = ('mean_test_score', 'mean_train_score', 'rank_test_score', 'split0_test_score', 'split1_test_score', 'split2_test_score', 'split0_train_score', 'split1_train_score', 'split2_train_score', 'std_test_score', 'std_train_score', 'mean_fit_time', 'std_fit_time', 'mean_score_time', 'std_score_time') n_cand = n_search_iter search = RandomizedSearchCV(SVC(), n_iter=n_search_iter, cv=n_splits, param_distributions=params, return_train_score=True) search.fit(X, y) cv_results = search.cv_results_ cv_results = search.cv_results_ assert all((isinstance(cv_results[param], np.ma.MaskedArray) for param in param_keys)) assert all((cv_results[key].dtype == object for key in param_keys)) assert not any((isinstance(cv_results[key], np.ma.MaskedArray) for key in score_keys)) assert all((cv_results[key].dtype == np.float64 for key in score_keys if not key.startswith('rank'))) scorer_keys = search.scorer_.keys() if search.multimetric_ else ['score'] for key in scorer_keys: assert cv_results['rank_test_%s' % key].dtype == np.int32 assert_array_equal(sorted(cv_results.keys()), sorted(param_keys + score_keys + ('params',))) assert all((cv_results[key].shape == (n_cand,) for key in param_keys + score_keys)) n_candidates = len(search.cv_results_['params']) assert all((cv_results['param_C'].mask[i] and cv_results['param_gamma'].mask[i] and (not cv_results['param_degree'].mask[i]) for i in range(n_candidates) if cv_results['param_kernel'][i] == 'linear')) assert all((not cv_results['param_C'].mask[i] and (not cv_results['param_gamma'].mask[i]) and cv_results['param_degree'].mask[i] for i in range(n_candidates) if cv_results['param_kernel'][i] == 'rbf'))
def test_random_search_cv_results(): (X, y) = make_classification(n_samples=50, n_features=4, random_state=42) n_splits = 3 n_search_iter = 30 params = [{'kernel': ['rbf'], 'C': expon(scale=10), 'gamma': expon(scale=0.1)}, {'kernel': ['poly'], 'degree': [2, 3]}] param_keys = ('param_C', 'param_degree', 'param_gamma', 'param_kernel') score_keys = ('mean_test_score', 'mean_train_score', 'rank_test_score', 'split0_test_score', 'split1_test_score', 'split2_test_score', 'split0_train_score', 'split1_train_score', 'split2_train_score', 'std_test_score', 'std_train_score', 'mean_fit_time', 'std_fit_time', 'mean_score_time', 'std_score_time') n_cand = n_search_iter search = RandomizedSearchCV(SVC(), n_iter=n_search_iter, cv=n_splits, param_distributions=params, return_train_score=True) search.fit(X, y) cv_results = search.cv_results_ <DeepExtract> cv_results = search.cv_results_ assert all((isinstance(cv_results[param], np.ma.MaskedArray) for param in param_keys)) assert all((cv_results[key].dtype == object for key in param_keys)) assert not any((isinstance(cv_results[key], np.ma.MaskedArray) for key in score_keys)) assert all((cv_results[key].dtype == np.float64 for key in score_keys if not key.startswith('rank'))) scorer_keys = search.scorer_.keys() if search.multimetric_ else ['score'] for key in scorer_keys: assert cv_results['rank_test_%s' % key].dtype == np.int32 </DeepExtract> <DeepExtract> assert_array_equal(sorted(cv_results.keys()), sorted(param_keys + score_keys + ('params',))) assert all((cv_results[key].shape == (n_cand,) for key in param_keys + score_keys)) </DeepExtract> n_candidates = len(search.cv_results_['params']) assert all((cv_results['param_C'].mask[i] and cv_results['param_gamma'].mask[i] and (not cv_results['param_degree'].mask[i]) for i in range(n_candidates) if cv_results['param_kernel'][i] == 'linear')) assert all((not cv_results['param_C'].mask[i] and (not cv_results['param_gamma'].mask[i]) and cv_results['param_degree'].mask[i] for i in range(n_candidates) if cv_results['param_kernel'][i] == 'rbf'))
def iter_minibatches(doc_iter, minibatch_size): """Generator of minibatches.""" data = [('{title}\n\n{body}'.format(**doc), pos_class in doc['topics']) for doc in itertools.islice(doc_iter, minibatch_size) if doc['topics']] if not len(data): (X_text, y) = (np.asarray([], dtype=int), np.asarray([], dtype=int)) (X_text, y) = zip(*data) (X_text, y) = (X_text, np.asarray(y, dtype=int)) while len(X_text): yield (X_text, y) data = [('{title}\n\n{body}'.format(**doc), pos_class in doc['topics']) for doc in itertools.islice(doc_iter, minibatch_size) if doc['topics']] if not len(data): (X_text, y) = (np.asarray([], dtype=int), np.asarray([], dtype=int)) (X_text, y) = zip(*data) (X_text, y) = (X_text, np.asarray(y, dtype=int)) </DeepExtract>
def iter_minibatches(doc_iter, minibatch_size): """Generator of minibatches.""" <DeepExtract> data = [('{title}\n\n{body}'.format(**doc), pos_class in doc['topics']) for doc in itertools.islice(doc_iter, minibatch_size) if doc['topics']] if not len(data): (X_text, y) = (np.asarray([], dtype=int), np.asarray([], dtype=int)) (X_text, y) = zip(*data) (X_text, y) = (X_text, np.asarray(y, dtype=int)) </DeepExtract> while len(X_text): yield (X_text, y) <DeepExtract> data = [('{title}\n\n{body}'.format(**doc), pos_class in doc['topics']) for doc in itertools.islice(doc_iter, minibatch_size) if doc['topics']] if not len(data): (X_text, y) = (np.asarray([], dtype=int), np.asarray([], dtype=int)) (X_text, y) = zip(*data) (X_text, y) = (X_text, np.asarray(y, dtype=int)) </DeepExtract>
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False, return_n_test_samples=False, return_times=False, return_estimator=False, split_progress=None, candidate_progress=None, error_score=np.nan): """Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape (n_samples, n_features) The data to fit. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None The target variable to try to predict in the case of supervised learning. scorer : A single callable or dict mapping scorer name to the callable If it is a single callable, the return value for ``train_scores`` and ``test_scores`` is a single float. For a dict, it should be one mapping the scorer name to the scorer callable object / function. The callable object / fn should have signature ``scorer(estimator, X, y)``. train : array-like of shape (n_train_samples,) Indices of training samples. test : array-like of shape (n_test_samples,) Indices of test samples. verbose : int The verbosity level. error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. parameters : dict or None Parameters to be set on the estimator. fit_params : dict or None Parameters that will be passed to ``estimator.fit``. return_train_score : bool, default=False Compute and return score on training set. return_parameters : bool, default=False Return parameters that has been used for the estimator. split_progress : {list, tuple} of int, default=None A list or tuple of format (<current_split_id>, <total_num_of_splits>). candidate_progress : {list, tuple} of int, default=None A list or tuple of format (<current_candidate_id>, <total_number_of_candidates>). return_n_test_samples : bool, default=False Whether to return the ``n_test_samples``. return_times : bool, default=False Whether to return the fit/score times. return_estimator : bool, default=False Whether to return the fitted estimator. Returns ------- result : dict with the following attributes train_scores : dict of scorer name -> float Score on training set (for all the scorers), returned only if `return_train_score` is `True`. test_scores : dict of scorer name -> float Score on testing set (for all the scorers). n_test_samples : int Number of test samples. fit_time : float Time spent for fitting in seconds. score_time : float Time spent for scoring in seconds. parameters : dict or None The parameters that have been evaluated. estimator : estimator object The fitted estimator. fit_error : str or None Traceback str if the fit failed, None if the fit succeeded. """ if not isinstance(error_score, numbers.Number) and error_score != 'raise': raise ValueError("error_score must be the string 'raise' or a numeric value. (Hint: if using 'raise', please make sure that it has been spelled correctly.)") progress_msg = '' if verbose > 2: if split_progress is not None: progress_msg = f' {split_progress[0] + 1}/{split_progress[1]}' if candidate_progress and verbose > 9: progress_msg += f'; {candidate_progress[0] + 1}/{candidate_progress[1]}' if verbose > 1: if parameters is None: params_msg = '' else: sorted_keys = sorted(parameters) params_msg = ', '.join((f'{k}={parameters[k]}' for k in sorted_keys)) if verbose > 9: start_msg = f'[CV{progress_msg}] START {params_msg}' print(f"{start_msg}{(80 - len(start_msg)) * '.'}") fit_params = fit_params if fit_params is not None else {} fit_params = _check_fit_params(X, fit_params, train) if parameters is not None: cloned_parameters = {} for (k, v) in parameters.items(): cloned_parameters[k] = clone(v, safe=False) estimator = estimator.set_params(**cloned_parameters) start_time = time.time() (X_train, y_train) = _safe_split(estimator, X, y, train) (X_test, y_test) = _safe_split(estimator, X, y, test, train) result = {} try: if y_train is None: estimator.fit(X_train, **fit_params) else: estimator.fit(X_train, y_train, **fit_params) except Exception: fit_time = time.time() - start_time score_time = 0.0 if error_score == 'raise': raise elif isinstance(error_score, numbers.Number): if isinstance(scorer, dict): test_scores = {name: error_score for name in scorer} if return_train_score: train_scores = test_scores.copy() else: test_scores = error_score if return_train_score: train_scores = error_score result['fit_error'] = format_exc() else: result['fit_error'] = None fit_time = time.time() - start_time if isinstance(scorer, dict): scorer = _MultimetricScorer(scorers=scorer, raise_exc=error_score == 'raise') try: if y_test is None: scores = scorer(estimator, X_test) else: scores = scorer(estimator, X_test, y_test) except Exception: if isinstance(scorer, _MultimetricScorer): raise elif error_score == 'raise': raise else: scores = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{format_exc()}', UserWarning) if isinstance(scorer, _MultimetricScorer): exception_messages = [(name, str_e) for (name, str_e) in scores.items() if isinstance(str_e, str)] if exception_messages: for (name, str_e) in exception_messages: scores[name] = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{str_e}', UserWarning) error_msg = 'scoring must return a number, got %s (%s) instead. (scorer=%s)' if isinstance(scores, dict): for (name, score) in scores.items(): if hasattr(score, 'item'): with suppress(ValueError): score = score.item() if not isinstance(score, numbers.Number): raise ValueError(error_msg % (score, type(score), name)) scores[name] = score else: if hasattr(scores, 'item'): with suppress(ValueError): scores = scores.item() if not isinstance(scores, numbers.Number): raise ValueError(error_msg % (scores, type(scores), scorer)) test_scores = scores score_time = time.time() - start_time - fit_time if return_train_score: if isinstance(scorer, dict): scorer = _MultimetricScorer(scorers=scorer, raise_exc=error_score == 'raise') try: if y_train is None: scores = scorer(estimator, X_train) else: scores = scorer(estimator, X_train, y_train) except Exception: if isinstance(scorer, _MultimetricScorer): raise elif error_score == 'raise': raise else: scores = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{format_exc()}', UserWarning) if isinstance(scorer, _MultimetricScorer): exception_messages = [(name, str_e) for (name, str_e) in scores.items() if isinstance(str_e, str)] if exception_messages: for (name, str_e) in exception_messages: scores[name] = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{str_e}', UserWarning) error_msg = 'scoring must return a number, got %s (%s) instead. (scorer=%s)' if isinstance(scores, dict): for (name, score) in scores.items(): if hasattr(score, 'item'): with suppress(ValueError): score = score.item() if not isinstance(score, numbers.Number): raise ValueError(error_msg % (score, type(score), name)) scores[name] = score else: if hasattr(scores, 'item'): with suppress(ValueError): scores = scores.item() if not isinstance(scores, numbers.Number): raise ValueError(error_msg % (scores, type(scores), scorer)) train_scores = scores if verbose > 1: total_time = score_time + fit_time end_msg = f'[CV{progress_msg}] END ' result_msg = params_msg + (';' if params_msg else '') if verbose > 2: if isinstance(test_scores, dict): for scorer_name in sorted(test_scores): result_msg += f' {scorer_name}: (' if return_train_score: scorer_scores = train_scores[scorer_name] result_msg += f'train={scorer_scores:.3f}, ' result_msg += f'test={test_scores[scorer_name]:.3f})' else: result_msg += ', score=' if return_train_score: result_msg += f'(train={train_scores:.3f}, test={test_scores:.3f})' else: result_msg += f'{test_scores:.3f}' result_msg += f' total time={logger.short_format_time(total_time)}' end_msg += '.' * (80 - len(end_msg) - len(result_msg)) end_msg += result_msg print(end_msg) result['test_scores'] = test_scores if return_train_score: result['train_scores'] = train_scores if return_n_test_samples: result['n_test_samples'] = _num_samples(X_test) if return_times: result['fit_time'] = fit_time result['score_time'] = score_time if return_parameters: result['parameters'] = parameters if return_estimator: result['estimator'] = estimator return result
def _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score=False, return_parameters=False, return_n_test_samples=False, return_times=False, return_estimator=False, split_progress=None, candidate_progress=None, error_score=np.nan): """Fit estimator and compute scores for a given dataset split. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape (n_samples, n_features) The data to fit. y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None The target variable to try to predict in the case of supervised learning. scorer : A single callable or dict mapping scorer name to the callable If it is a single callable, the return value for ``train_scores`` and ``test_scores`` is a single float. For a dict, it should be one mapping the scorer name to the scorer callable object / function. The callable object / fn should have signature ``scorer(estimator, X, y)``. train : array-like of shape (n_train_samples,) Indices of training samples. test : array-like of shape (n_test_samples,) Indices of test samples. verbose : int The verbosity level. error_score : 'raise' or numeric, default=np.nan Value to assign to the score if an error occurs in estimator fitting. If set to 'raise', the error is raised. If a numeric value is given, FitFailedWarning is raised. parameters : dict or None Parameters to be set on the estimator. fit_params : dict or None Parameters that will be passed to ``estimator.fit``. return_train_score : bool, default=False Compute and return score on training set. return_parameters : bool, default=False Return parameters that has been used for the estimator. split_progress : {list, tuple} of int, default=None A list or tuple of format (<current_split_id>, <total_num_of_splits>). candidate_progress : {list, tuple} of int, default=None A list or tuple of format (<current_candidate_id>, <total_number_of_candidates>). return_n_test_samples : bool, default=False Whether to return the ``n_test_samples``. return_times : bool, default=False Whether to return the fit/score times. return_estimator : bool, default=False Whether to return the fitted estimator. Returns ------- result : dict with the following attributes train_scores : dict of scorer name -> float Score on training set (for all the scorers), returned only if `return_train_score` is `True`. test_scores : dict of scorer name -> float Score on testing set (for all the scorers). n_test_samples : int Number of test samples. fit_time : float Time spent for fitting in seconds. score_time : float Time spent for scoring in seconds. parameters : dict or None The parameters that have been evaluated. estimator : estimator object The fitted estimator. fit_error : str or None Traceback str if the fit failed, None if the fit succeeded. """ if not isinstance(error_score, numbers.Number) and error_score != 'raise': raise ValueError("error_score must be the string 'raise' or a numeric value. (Hint: if using 'raise', please make sure that it has been spelled correctly.)") progress_msg = '' if verbose > 2: if split_progress is not None: progress_msg = f' {split_progress[0] + 1}/{split_progress[1]}' if candidate_progress and verbose > 9: progress_msg += f'; {candidate_progress[0] + 1}/{candidate_progress[1]}' if verbose > 1: if parameters is None: params_msg = '' else: sorted_keys = sorted(parameters) params_msg = ', '.join((f'{k}={parameters[k]}' for k in sorted_keys)) if verbose > 9: start_msg = f'[CV{progress_msg}] START {params_msg}' print(f"{start_msg}{(80 - len(start_msg)) * '.'}") fit_params = fit_params if fit_params is not None else {} fit_params = _check_fit_params(X, fit_params, train) if parameters is not None: cloned_parameters = {} for (k, v) in parameters.items(): cloned_parameters[k] = clone(v, safe=False) estimator = estimator.set_params(**cloned_parameters) start_time = time.time() (X_train, y_train) = _safe_split(estimator, X, y, train) (X_test, y_test) = _safe_split(estimator, X, y, test, train) result = {} try: if y_train is None: estimator.fit(X_train, **fit_params) else: estimator.fit(X_train, y_train, **fit_params) except Exception: fit_time = time.time() - start_time score_time = 0.0 if error_score == 'raise': raise elif isinstance(error_score, numbers.Number): if isinstance(scorer, dict): test_scores = {name: error_score for name in scorer} if return_train_score: train_scores = test_scores.copy() else: test_scores = error_score if return_train_score: train_scores = error_score result['fit_error'] = format_exc() else: result['fit_error'] = None fit_time = time.time() - start_time <DeepExtract> if isinstance(scorer, dict): scorer = _MultimetricScorer(scorers=scorer, raise_exc=error_score == 'raise') try: if y_test is None: scores = scorer(estimator, X_test) else: scores = scorer(estimator, X_test, y_test) except Exception: if isinstance(scorer, _MultimetricScorer): raise elif error_score == 'raise': raise else: scores = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{format_exc()}', UserWarning) if isinstance(scorer, _MultimetricScorer): exception_messages = [(name, str_e) for (name, str_e) in scores.items() if isinstance(str_e, str)] if exception_messages: for (name, str_e) in exception_messages: scores[name] = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{str_e}', UserWarning) error_msg = 'scoring must return a number, got %s (%s) instead. (scorer=%s)' if isinstance(scores, dict): for (name, score) in scores.items(): if hasattr(score, 'item'): with suppress(ValueError): score = score.item() if not isinstance(score, numbers.Number): raise ValueError(error_msg % (score, type(score), name)) scores[name] = score else: if hasattr(scores, 'item'): with suppress(ValueError): scores = scores.item() if not isinstance(scores, numbers.Number): raise ValueError(error_msg % (scores, type(scores), scorer)) test_scores = scores </DeepExtract> score_time = time.time() - start_time - fit_time if return_train_score: <DeepExtract> if isinstance(scorer, dict): scorer = _MultimetricScorer(scorers=scorer, raise_exc=error_score == 'raise') try: if y_train is None: scores = scorer(estimator, X_train) else: scores = scorer(estimator, X_train, y_train) except Exception: if isinstance(scorer, _MultimetricScorer): raise elif error_score == 'raise': raise else: scores = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{format_exc()}', UserWarning) if isinstance(scorer, _MultimetricScorer): exception_messages = [(name, str_e) for (name, str_e) in scores.items() if isinstance(str_e, str)] if exception_messages: for (name, str_e) in exception_messages: scores[name] = error_score warnings.warn(f'Scoring failed. The score on this train-test partition for these parameters will be set to {error_score}. Details: \n{str_e}', UserWarning) error_msg = 'scoring must return a number, got %s (%s) instead. (scorer=%s)' if isinstance(scores, dict): for (name, score) in scores.items(): if hasattr(score, 'item'): with suppress(ValueError): score = score.item() if not isinstance(score, numbers.Number): raise ValueError(error_msg % (score, type(score), name)) scores[name] = score else: if hasattr(scores, 'item'): with suppress(ValueError): scores = scores.item() if not isinstance(scores, numbers.Number): raise ValueError(error_msg % (scores, type(scores), scorer)) train_scores = scores </DeepExtract> if verbose > 1: total_time = score_time + fit_time end_msg = f'[CV{progress_msg}] END ' result_msg = params_msg + (';' if params_msg else '') if verbose > 2: if isinstance(test_scores, dict): for scorer_name in sorted(test_scores): result_msg += f' {scorer_name}: (' if return_train_score: scorer_scores = train_scores[scorer_name] result_msg += f'train={scorer_scores:.3f}, ' result_msg += f'test={test_scores[scorer_name]:.3f})' else: result_msg += ', score=' if return_train_score: result_msg += f'(train={train_scores:.3f}, test={test_scores:.3f})' else: result_msg += f'{test_scores:.3f}' result_msg += f' total time={logger.short_format_time(total_time)}' end_msg += '.' * (80 - len(end_msg) - len(result_msg)) end_msg += result_msg print(end_msg) result['test_scores'] = test_scores if return_train_score: result['train_scores'] = train_scores if return_n_test_samples: result['n_test_samples'] = _num_samples(X_test) if return_times: result['fit_time'] = fit_time result['score_time'] = score_time if return_parameters: result['parameters'] = parameters if return_estimator: result['estimator'] = estimator return result
def test_selectkbest_tiebreaking(): Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]] y = [1] dummy_score = lambda X, y: (X[0], X[0]) for X in Xs: sel = SelectKBest(dummy_score, k=1) X1 = ignore_warnings(sel.fit_transform)([X], y) assert X1.shape[1] == 1 scores = sel.scores_ support = sel.get_support() assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():]) sel = SelectKBest(dummy_score, k=2) X2 = ignore_warnings(sel.fit_transform)([X], y) assert X2.shape[1] == 2 scores = sel.scores_ support = sel.get_support() assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():]) </DeepExtract>
def test_selectkbest_tiebreaking(): Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]] y = [1] dummy_score = lambda X, y: (X[0], X[0]) for X in Xs: sel = SelectKBest(dummy_score, k=1) X1 = ignore_warnings(sel.fit_transform)([X], y) assert X1.shape[1] == 1 <DeepExtract> scores = sel.scores_ support = sel.get_support() assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():]) </DeepExtract> sel = SelectKBest(dummy_score, k=2) X2 = ignore_warnings(sel.fit_transform)([X], y) assert X2.shape[1] == 2 <DeepExtract> scores = sel.scores_ support = sel.get_support() assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():]) </DeepExtract>
def _solve_eigen(self, X, y, shrinkage, covariance_estimator): """Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduction (with any covariance estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. shrinkage : 'auto', float or None Shrinkage parameter, possible values: - None: no shrinkage. - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage constant. Shrinkage parameter is ignored if `covariance_estimator` i not None covariance_estimator : estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. .. versionadded:: 0.24 Notes ----- This solver is based on [1]_, section 3.8.3, pp. 121-124. References ---------- .. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification (Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN 0-471-05669-3. """ (xp, is_array_api) = get_namespace(X) (classes, y) = xp.unique_inverse(y) means = xp.zeros(shape=(classes.shape[0], X.shape[1])) if is_array_api: for i in range(classes.shape[0]): means[i, :] = xp.mean(X[y == i], axis=0) else: cnt = np.bincount(y) np.add.at(means, y, X) means /= cnt[:, None] self.means_ = means classes = np.unique(y) cov = np.zeros(shape=(X.shape[1], X.shape[1])) for (idx, group) in enumerate(classes): Xg = X[y == group, :] cov += self.priors_[idx] * np.atleast_2d(_cov(Xg, shrinkage, covariance_estimator)) self.covariance_ = cov Sw = self.covariance_ if covariance_estimator is None: shrinkage = 'empirical' if shrinkage is None else shrinkage if isinstance(shrinkage, str): if shrinkage == 'auto': sc = StandardScaler() X = sc.fit_transform(X) s = ledoit_wolf(X)[0] s = sc.scale_[:, np.newaxis] * s * sc.scale_[np.newaxis, :] elif shrinkage == 'empirical': s = empirical_covariance(X) elif isinstance(shrinkage, Real): s = shrunk_covariance(empirical_covariance(X), shrinkage) else: if shrinkage is not None and shrinkage != 0: raise ValueError('covariance_estimator and shrinkage parameters are not None. Only one of the two can be set.') covariance_estimator.fit(X) if not hasattr(covariance_estimator, 'covariance_'): raise ValueError('%s does not have a covariance_ attribute' % covariance_estimator.__class__.__name__) s = covariance_estimator.covariance_ St = s Sb = St - Sw (evals, evecs) = linalg.eigh(Sb, Sw) self.explained_variance_ratio_ = np.sort(evals / np.sum(evals))[::-1][:self._max_components] evecs = evecs[:, np.argsort(evals)[::-1]] self.scalings_ = evecs self.coef_ = np.dot(self.means_, evecs).dot(evecs.T) self.intercept_ = -0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(self.priors_)
def _solve_eigen(self, X, y, shrinkage, covariance_estimator): """Eigenvalue solver. The eigenvalue solver computes the optimal solution of the Rayleigh coefficient (basically the ratio of between class scatter to within class scatter). This solver supports both classification and dimensionality reduction (with any covariance estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. shrinkage : 'auto', float or None Shrinkage parameter, possible values: - None: no shrinkage. - 'auto': automatic shrinkage using the Ledoit-Wolf lemma. - float between 0 and 1: fixed shrinkage constant. Shrinkage parameter is ignored if `covariance_estimator` i not None covariance_estimator : estimator, default=None If not None, `covariance_estimator` is used to estimate the covariance matrices instead of relying the empirical covariance estimator (with potential shrinkage). The object should have a fit method and a ``covariance_`` attribute like the estimators in sklearn.covariance. if None the shrinkage parameter drives the estimate. .. versionadded:: 0.24 Notes ----- This solver is based on [1]_, section 3.8.3, pp. 121-124. References ---------- .. [1] R. O. Duda, P. E. Hart, D. G. Stork. Pattern Classification (Second Edition). John Wiley & Sons, Inc., New York, 2001. ISBN 0-471-05669-3. """ <DeepExtract> (xp, is_array_api) = get_namespace(X) (classes, y) = xp.unique_inverse(y) means = xp.zeros(shape=(classes.shape[0], X.shape[1])) if is_array_api: for i in range(classes.shape[0]): means[i, :] = xp.mean(X[y == i], axis=0) else: cnt = np.bincount(y) np.add.at(means, y, X) means /= cnt[:, None] self.means_ = means </DeepExtract> <DeepExtract> classes = np.unique(y) cov = np.zeros(shape=(X.shape[1], X.shape[1])) for (idx, group) in enumerate(classes): Xg = X[y == group, :] cov += self.priors_[idx] * np.atleast_2d(_cov(Xg, shrinkage, covariance_estimator)) self.covariance_ = cov </DeepExtract> Sw = self.covariance_ <DeepExtract> if covariance_estimator is None: shrinkage = 'empirical' if shrinkage is None else shrinkage if isinstance(shrinkage, str): if shrinkage == 'auto': sc = StandardScaler() X = sc.fit_transform(X) s = ledoit_wolf(X)[0] s = sc.scale_[:, np.newaxis] * s * sc.scale_[np.newaxis, :] elif shrinkage == 'empirical': s = empirical_covariance(X) elif isinstance(shrinkage, Real): s = shrunk_covariance(empirical_covariance(X), shrinkage) else: if shrinkage is not None and shrinkage != 0: raise ValueError('covariance_estimator and shrinkage parameters are not None. Only one of the two can be set.') covariance_estimator.fit(X) if not hasattr(covariance_estimator, 'covariance_'): raise ValueError('%s does not have a covariance_ attribute' % covariance_estimator.__class__.__name__) s = covariance_estimator.covariance_ St = s </DeepExtract> Sb = St - Sw (evals, evecs) = linalg.eigh(Sb, Sw) self.explained_variance_ratio_ = np.sort(evals / np.sum(evals))[::-1][:self._max_components] evecs = evecs[:, np.argsort(evals)[::-1]] self.scalings_ = evecs self.coef_ = np.dot(self.means_, evecs).dot(evecs.T) self.intercept_ = -0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(self.priors_)
def test_scaler_return_identity(): X_dense = np.array([[0, 1, 3], [5, 6, 0], [8, 0, 10]], dtype=np.float64) X_csr = sparse.csr_matrix(X_dense) X_csc = X_csr.tocsc() transformer_dense = StandardScaler(with_mean=False, with_std=False) X_trans_dense = transformer_dense.fit_transform(X_dense) transformer_csr = clone(transformer_dense) X_trans_csr = transformer_csr.fit_transform(X_csr) transformer_csc = clone(transformer_dense) X_trans_csc = transformer_csc.fit_transform(X_csc) assert_allclose_dense_sparse(X_trans_csr, X_csr) assert_allclose_dense_sparse(X_trans_csc, X_csc) assert_allclose(X_trans_dense, X_dense) for (trans_1, trans_2) in itertools.combinations([transformer_dense, transformer_csr, transformer_csc], 2): assert trans_1.mean_ is trans_2.mean_ is None assert trans_1.var_ is trans_2.var_ is None assert trans_1.scale_ is trans_2.scale_ is None assert trans_1.n_samples_seen_ == trans_2.n_samples_seen_ transformer_dense.partial_fit(X_dense) transformer_csr.partial_fit(X_csr) transformer_csc.partial_fit(X_csc) for (trans_1, trans_2) in itertools.combinations([transformer_dense, transformer_csr, transformer_csc], 2): assert trans_1.mean_ is trans_2.mean_ is None assert trans_1.var_ is trans_2.var_ is None assert trans_1.scale_ is trans_2.scale_ is None assert trans_1.n_samples_seen_ == trans_2.n_samples_seen_ transformer_dense.fit(X_dense) transformer_csr.fit(X_csr) transformer_csc.fit(X_csc) for (trans_1, trans_2) in itertools.combinations([transformer_dense, transformer_csr, transformer_csc], 2): assert trans_1.mean_ is trans_2.mean_ is None assert trans_1.var_ is trans_2.var_ is None assert trans_1.scale_ is trans_2.scale_ is None assert trans_1.n_samples_seen_ == trans_2.n_samples_seen_ </DeepExtract>
def test_scaler_return_identity(): X_dense = np.array([[0, 1, 3], [5, 6, 0], [8, 0, 10]], dtype=np.float64) X_csr = sparse.csr_matrix(X_dense) X_csc = X_csr.tocsc() transformer_dense = StandardScaler(with_mean=False, with_std=False) X_trans_dense = transformer_dense.fit_transform(X_dense) transformer_csr = clone(transformer_dense) X_trans_csr = transformer_csr.fit_transform(X_csr) transformer_csc = clone(transformer_dense) X_trans_csc = transformer_csc.fit_transform(X_csc) assert_allclose_dense_sparse(X_trans_csr, X_csr) assert_allclose_dense_sparse(X_trans_csc, X_csc) assert_allclose(X_trans_dense, X_dense) for (trans_1, trans_2) in itertools.combinations([transformer_dense, transformer_csr, transformer_csc], 2): <DeepExtract> assert trans_1.mean_ is trans_2.mean_ is None assert trans_1.var_ is trans_2.var_ is None assert trans_1.scale_ is trans_2.scale_ is None assert trans_1.n_samples_seen_ == trans_2.n_samples_seen_ </DeepExtract> transformer_dense.partial_fit(X_dense) transformer_csr.partial_fit(X_csr) transformer_csc.partial_fit(X_csc) for (trans_1, trans_2) in itertools.combinations([transformer_dense, transformer_csr, transformer_csc], 2): <DeepExtract> assert trans_1.mean_ is trans_2.mean_ is None assert trans_1.var_ is trans_2.var_ is None assert trans_1.scale_ is trans_2.scale_ is None assert trans_1.n_samples_seen_ == trans_2.n_samples_seen_ </DeepExtract> transformer_dense.fit(X_dense) transformer_csr.fit(X_csr) transformer_csc.fit(X_csc) for (trans_1, trans_2) in itertools.combinations([transformer_dense, transformer_csr, transformer_csc], 2): <DeepExtract> assert trans_1.mean_ is trans_2.mean_ is None assert trans_1.var_ is trans_2.var_ is None assert trans_1.scale_ is trans_2.scale_ is None assert trans_1.n_samples_seen_ == trans_2.n_samples_seen_ </DeepExtract>
def check_paired_arrays(X, Y): """Set X and Y appropriately and checks inputs for paired distances. All paired distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the dimensions of the two arrays are equal. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ (X, Y, dtype_float) = _return_float_dtype(X, Y) estimator = 'check_pairwise_arrays' if dtype is None: dtype = dtype_float if Y is X or Y is None: X = Y = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) else: X = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) Y = check_array(Y, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) if precomputed: if X.shape[1] != Y.shape[0]: raise ValueError('Precomputed metric requires shape (n_queries, n_indexed). Got (%d, %d) for %d indexed.' % (X.shape[0], X.shape[1], Y.shape[0])) elif X.shape[1] != Y.shape[1]: raise ValueError('Incompatible dimension for X and Y matrices: X.shape[1] == %d while Y.shape[1] == %d' % (X.shape[1], Y.shape[1])) (X, Y) = (X, Y) if X.shape != Y.shape: raise ValueError('X and Y should be of same shape. They were respectively %r and %r long.' % (X.shape, Y.shape)) return (X, Y)
def check_paired_arrays(X, Y): """Set X and Y appropriately and checks inputs for paired distances. All paired distance metrics should use this function first to assert that the given parameters are correct and safe to use. Specifically, this function first ensures that both X and Y are arrays, then checks that they are at least two dimensional while ensuring that their elements are floats. Finally, the function checks that the size of the dimensions of the two arrays are equal. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Returns ------- safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) An array equal to X, guaranteed to be a numpy array. safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) An array equal to Y if Y was not None, guaranteed to be a numpy array. If Y was None, safe_Y will be a pointer to X. """ <DeepExtract> (X, Y, dtype_float) = _return_float_dtype(X, Y) estimator = 'check_pairwise_arrays' if dtype is None: dtype = dtype_float if Y is X or Y is None: X = Y = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) else: X = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) Y = check_array(Y, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) if precomputed: if X.shape[1] != Y.shape[0]: raise ValueError('Precomputed metric requires shape (n_queries, n_indexed). Got (%d, %d) for %d indexed.' % (X.shape[0], X.shape[1], Y.shape[0])) elif X.shape[1] != Y.shape[1]: raise ValueError('Incompatible dimension for X and Y matrices: X.shape[1] == %d while Y.shape[1] == %d' % (X.shape[1], Y.shape[1])) (X, Y) = (X, Y) </DeepExtract> if X.shape != Y.shape: raise ValueError('X and Y should be of same shape. They were respectively %r and %r long.' % (X.shape, Y.shape)) return (X, Y)
def best_low_complexity(cv_results): """ Balance model complexity with cross-validated score. Parameters ---------- cv_results : dict of numpy(masked) ndarrays See attribute cv_results_ of `GridSearchCV`. Return ------ int Index of a model that has the fewest PCA components while has its test score within 1 standard deviation of the best `mean_test_score`. """ best_score_idx = np.argmax(cv_results['mean_test_score']) threshold = cv_results['mean_test_score'][best_score_idx] - cv_results['std_test_score'][best_score_idx] candidate_idx = np.flatnonzero(cv_results['mean_test_score'] >= threshold) best_idx = candidate_idx[cv_results['param_reduce_dim__n_components'][candidate_idx].argmin()] return best_idx
def best_low_complexity(cv_results): """ Balance model complexity with cross-validated score. Parameters ---------- cv_results : dict of numpy(masked) ndarrays See attribute cv_results_ of `GridSearchCV`. Return ------ int Index of a model that has the fewest PCA components while has its test score within 1 standard deviation of the best `mean_test_score`. """ <DeepExtract> best_score_idx = np.argmax(cv_results['mean_test_score']) threshold = cv_results['mean_test_score'][best_score_idx] - cv_results['std_test_score'][best_score_idx] </DeepExtract> candidate_idx = np.flatnonzero(cv_results['mean_test_score'] >= threshold) best_idx = candidate_idx[cv_results['param_reduce_dim__n_components'][candidate_idx].argmin()] return best_idx
def _fit_transform(X, y=None, W=None, H=None, update_H=True): """Learn a NMF model for the data X and returns the transformed data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Data matrix to be decomposed y : Ignored W : array-like of shape (n_samples, n_components), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is initialised as an array of zeros, unless `solver='mu'`, then it is filled with values calculated by `np.sqrt(X.mean() / self._n_components)`. If `None`, uses the initialisation method specified in `init`. H : array-like of shape (n_components, n_features), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is used as a constant, to solve for W only. If `None`, uses the initialisation method specified in `init`. update_H : bool, default=True If True, both W and H will be estimated from initial guesses, this corresponds to a call to the 'fit_transform' method. If False, only W will be estimated, this corresponds to a call to the 'transform' method. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. H : ndarray of shape (n_components, n_features) Factorization matrix, sometimes called 'dictionary'. n_iter_ : int Actual number of iterations. """ check_non_negative(X, 'NMF (input X)') self._n_components = self.n_components if self._n_components is None: self._n_components = X.shape[1] self._beta_loss = _beta_loss_to_float(self.beta_loss) if X.min() == 0 and self._beta_loss <= 0: raise ValueError('When beta_loss <= 0 and X contains zeros, the solver may diverge. Please add small values to X, or use a positive beta_loss.') (n_samples, n_features) = X.shape if self.init == 'custom' and update_H: _check_init(H, (self._n_components, n_features), 'NMF (input H)') _check_init(W, (n_samples, self._n_components), 'NMF (input W)') if H.dtype != X.dtype or W.dtype != X.dtype: raise TypeError('H and W should have the same dtype as X. Got H.dtype = {} and W.dtype = {}.'.format(H.dtype, W.dtype)) elif not update_H: _check_init(H, (self._n_components, n_features), 'NMF (input H)') if H.dtype != X.dtype: raise TypeError('H should have the same dtype as X. Got H.dtype = {}.'.format(H.dtype)) if self.solver == 'mu': avg = np.sqrt(X.mean() / self._n_components) W = np.full((n_samples, self._n_components), avg, dtype=X.dtype) else: W = np.zeros((n_samples, self._n_components), dtype=X.dtype) else: (W, H) = _initialize_nmf(X, self._n_components, init=self.init, random_state=self.random_state) (W, H) = (W, H) (n_samples, n_features) = X.shape alpha_W = self.alpha_W alpha_H = self.alpha_W if self.alpha_H == 'same' else self.alpha_H l1_reg_W = n_features * alpha_W * self.l1_ratio l1_reg_H = n_samples * alpha_H * self.l1_ratio l2_reg_W = n_features * alpha_W * (1.0 - self.l1_ratio) l2_reg_H = n_samples * alpha_H * (1.0 - self.l1_ratio) (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) = (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) if self.solver == 'cd': Ht = check_array(H.T, order='C') X = check_array(X, accept_sparse='csr') rng = check_random_state(self.random_state) for n_iter in range(1, self.max_iter + 1): violation = 0.0 violation += _update_coordinate_descent(X, W, Ht, l1_reg_W, l2_reg_W, self.shuffle, rng) if update_H: violation += _update_coordinate_descent(X.T, Ht, W, l1_reg_H, l2_reg_H, self.shuffle, rng) if n_iter == 1: violation_init = violation if violation_init == 0: break if self.verbose: print('violation:', violation / violation_init) if violation / violation_init <= self.tol: if self.verbose: print('Converged at iteration', n_iter + 1) break (W, H, n_iter) = (W, Ht.T, n_iter) elif self.solver == 'mu': start_time = time.time() self._beta_loss = _beta_loss_to_float(self._beta_loss) if self._beta_loss < 1: gamma = 1.0 / (2.0 - self._beta_loss) elif self._beta_loss > 2: gamma = 1.0 / (self._beta_loss - 1.0) else: gamma = 1.0 error_at_init = _beta_divergence(X, W, H, self._beta_loss, square_root=True) previous_error = error_at_init (H_sum, HHt, XHt) = (None, None, None) for n_iter in range(1, self.max_iter + 1): (W, H_sum, HHt, XHt) = _multiplicative_update_w(X, W, H, beta_loss=self._beta_loss, l1_reg_W=l1_reg_W, l2_reg_W=l2_reg_W, gamma=gamma, H_sum=H_sum, HHt=HHt, XHt=XHt, update_H=update_H) if self._beta_loss < 1: W[W < np.finfo(np.float64).eps] = 0.0 if update_H: H = _multiplicative_update_h(X, W, H, beta_loss=self._beta_loss, l1_reg_H=l1_reg_H, l2_reg_H=l2_reg_H, gamma=gamma) (H_sum, HHt, XHt) = (None, None, None) if self._beta_loss <= 1: H[H < np.finfo(np.float64).eps] = 0.0 if self.tol > 0 and n_iter % 10 == 0: error = _beta_divergence(X, W, H, self._beta_loss, square_root=True) if self.verbose: iter_time = time.time() print('Epoch %02d reached after %.3f seconds, error: %f' % (n_iter, iter_time - start_time, error)) if (previous_error - error) / error_at_init < self.tol: break previous_error = error if self.verbose and (self.tol == 0 or n_iter % 10 != 0): end_time = time.time() print('Epoch %02d reached after %.3f seconds.' % (n_iter, end_time - start_time)) (W, H, n_iter, *_) = (W, H, n_iter) else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iterations %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) return (W, H, n_iter)
def _fit_transform(X, y=None, W=None, H=None, update_H=True): """Learn a NMF model for the data X and returns the transformed data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Data matrix to be decomposed y : Ignored W : array-like of shape (n_samples, n_components), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is initialised as an array of zeros, unless `solver='mu'`, then it is filled with values calculated by `np.sqrt(X.mean() / self._n_components)`. If `None`, uses the initialisation method specified in `init`. H : array-like of shape (n_components, n_features), default=None If `init='custom'`, it is used as initial guess for the solution. If `update_H=False`, it is used as a constant, to solve for W only. If `None`, uses the initialisation method specified in `init`. update_H : bool, default=True If True, both W and H will be estimated from initial guesses, this corresponds to a call to the 'fit_transform' method. If False, only W will be estimated, this corresponds to a call to the 'transform' method. Returns ------- W : ndarray of shape (n_samples, n_components) Transformed data. H : ndarray of shape (n_components, n_features) Factorization matrix, sometimes called 'dictionary'. n_iter_ : int Actual number of iterations. """ check_non_negative(X, 'NMF (input X)') <DeepExtract> self._n_components = self.n_components if self._n_components is None: self._n_components = X.shape[1] self._beta_loss = _beta_loss_to_float(self.beta_loss) </DeepExtract> if X.min() == 0 and self._beta_loss <= 0: raise ValueError('When beta_loss <= 0 and X contains zeros, the solver may diverge. Please add small values to X, or use a positive beta_loss.') <DeepExtract> (n_samples, n_features) = X.shape if self.init == 'custom' and update_H: _check_init(H, (self._n_components, n_features), 'NMF (input H)') _check_init(W, (n_samples, self._n_components), 'NMF (input W)') if H.dtype != X.dtype or W.dtype != X.dtype: raise TypeError('H and W should have the same dtype as X. Got H.dtype = {} and W.dtype = {}.'.format(H.dtype, W.dtype)) elif not update_H: _check_init(H, (self._n_components, n_features), 'NMF (input H)') if H.dtype != X.dtype: raise TypeError('H should have the same dtype as X. Got H.dtype = {}.'.format(H.dtype)) if self.solver == 'mu': avg = np.sqrt(X.mean() / self._n_components) W = np.full((n_samples, self._n_components), avg, dtype=X.dtype) else: W = np.zeros((n_samples, self._n_components), dtype=X.dtype) else: (W, H) = _initialize_nmf(X, self._n_components, init=self.init, random_state=self.random_state) (W, H) = (W, H) </DeepExtract> <DeepExtract> (n_samples, n_features) = X.shape alpha_W = self.alpha_W alpha_H = self.alpha_W if self.alpha_H == 'same' else self.alpha_H l1_reg_W = n_features * alpha_W * self.l1_ratio l1_reg_H = n_samples * alpha_H * self.l1_ratio l2_reg_W = n_features * alpha_W * (1.0 - self.l1_ratio) l2_reg_H = n_samples * alpha_H * (1.0 - self.l1_ratio) (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) = (l1_reg_W, l1_reg_H, l2_reg_W, l2_reg_H) </DeepExtract> if self.solver == 'cd': <DeepExtract> Ht = check_array(H.T, order='C') X = check_array(X, accept_sparse='csr') rng = check_random_state(self.random_state) for n_iter in range(1, self.max_iter + 1): violation = 0.0 violation += _update_coordinate_descent(X, W, Ht, l1_reg_W, l2_reg_W, self.shuffle, rng) if update_H: violation += _update_coordinate_descent(X.T, Ht, W, l1_reg_H, l2_reg_H, self.shuffle, rng) if n_iter == 1: violation_init = violation if violation_init == 0: break if self.verbose: print('violation:', violation / violation_init) if violation / violation_init <= self.tol: if self.verbose: print('Converged at iteration', n_iter + 1) break (W, H, n_iter) = (W, Ht.T, n_iter) </DeepExtract> elif self.solver == 'mu': <DeepExtract> start_time = time.time() self._beta_loss = _beta_loss_to_float(self._beta_loss) if self._beta_loss < 1: gamma = 1.0 / (2.0 - self._beta_loss) elif self._beta_loss > 2: gamma = 1.0 / (self._beta_loss - 1.0) else: gamma = 1.0 error_at_init = _beta_divergence(X, W, H, self._beta_loss, square_root=True) previous_error = error_at_init (H_sum, HHt, XHt) = (None, None, None) for n_iter in range(1, self.max_iter + 1): (W, H_sum, HHt, XHt) = _multiplicative_update_w(X, W, H, beta_loss=self._beta_loss, l1_reg_W=l1_reg_W, l2_reg_W=l2_reg_W, gamma=gamma, H_sum=H_sum, HHt=HHt, XHt=XHt, update_H=update_H) if self._beta_loss < 1: W[W < np.finfo(np.float64).eps] = 0.0 if update_H: H = _multiplicative_update_h(X, W, H, beta_loss=self._beta_loss, l1_reg_H=l1_reg_H, l2_reg_H=l2_reg_H, gamma=gamma) (H_sum, HHt, XHt) = (None, None, None) if self._beta_loss <= 1: H[H < np.finfo(np.float64).eps] = 0.0 if self.tol > 0 and n_iter % 10 == 0: error = _beta_divergence(X, W, H, self._beta_loss, square_root=True) if self.verbose: iter_time = time.time() print('Epoch %02d reached after %.3f seconds, error: %f' % (n_iter, iter_time - start_time, error)) if (previous_error - error) / error_at_init < self.tol: break previous_error = error if self.verbose and (self.tol == 0 or n_iter % 10 != 0): end_time = time.time() print('Epoch %02d reached after %.3f seconds.' % (n_iter, end_time - start_time)) (W, H, n_iter, *_) = (W, H, n_iter) </DeepExtract> else: raise ValueError("Invalid solver parameter '%s'." % self.solver) if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iterations %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) return (W, H, n_iter)
def export(self, decision_tree, ax=None): import matplotlib.pyplot as plt from matplotlib.text import Annotation if ax is None: ax = plt.gca() ax.clear() ax.set_axis_off() name = self.node_to_str(decision_tree.tree_, 0, criterion=decision_tree.criterion) if decision_tree.tree_.children_left[0] != _tree.TREE_LEAF and (self.max_depth is None or depth <= self.max_depth): children = [self._make_tree(decision_tree.tree_.children_left[0], decision_tree.tree_, decision_tree.criterion, depth=depth + 1), self._make_tree(decision_tree.tree_.children_right[0], decision_tree.tree_, decision_tree.criterion, depth=depth + 1)] else: my_tree = Tree(name, 0) my_tree = Tree(name, 0, *children) draw_tree = buchheim(my_tree) (max_x, max_y) = draw_tree.max_extents() + 1 ax_width = ax.get_window_extent().width ax_height = ax.get_window_extent().height scale_x = ax_width / max_x scale_y = ax_height / max_y if decision_tree.tree_ == _tree.TREE_LEAF: raise ValueError('Invalid node_id %s' % _tree.TREE_LEAF) left_child = draw_tree.children_left[decision_tree.tree_] right_child = draw_tree.children_right[decision_tree.tree_] if self.max_depth is None or max_y <= self.max_depth: if left_child == _tree.TREE_LEAF: self.ranks['leaves'].append(str(decision_tree.tree_)) elif str(max_y) not in self.ranks: self.ranks[str(max_y)] = [str(decision_tree.tree_)] else: self.ranks[str(max_y)].append(str(decision_tree.tree_)) self.out_file.write('%d [label=%s' % (decision_tree.tree_, self.node_to_str(draw_tree, decision_tree.tree_, ax))) if self.filled: self.out_file.write(', fillcolor="%s"' % self.get_fill_color(draw_tree, decision_tree.tree_)) self.out_file.write('] ;\n') if max_x is not None: self.out_file.write('%d -> %d' % (max_x, decision_tree.tree_)) if max_x == 0: angles = np.array([45, -45]) * ((self.rotate - 0.5) * -2) self.out_file.write(' [labeldistance=2.5, labelangle=') if decision_tree.tree_ == 1: self.out_file.write('%d, headlabel="True"]' % angles[0]) else: self.out_file.write('%d, headlabel="False"]' % angles[1]) self.out_file.write(' ;\n') if left_child != _tree.TREE_LEAF: self.recurse(draw_tree, left_child, criterion=ax, parent=decision_tree.tree_, depth=max_y + 1) self.recurse(draw_tree, right_child, criterion=ax, parent=decision_tree.tree_, depth=max_y + 1) else: self.ranks['leaves'].append(str(decision_tree.tree_)) self.out_file.write('%d [label="(...)"' % decision_tree.tree_) if self.filled: self.out_file.write(', fillcolor="#C0C0C0"') self.out_file.write('] ;\n' % decision_tree.tree_) if max_x is not None: self.out_file.write('%d -> %d ;\n' % (max_x, decision_tree.tree_)) anns = [ann for ann in ax.get_children() if isinstance(ann, Annotation)] renderer = ax.figure.canvas.get_renderer() for ann in anns: ann.update_bbox_position_size(renderer) if self.fontsize is None: extents = [ann.get_bbox_patch().get_window_extent() for ann in anns] max_width = max([extent.width for extent in extents]) max_height = max([extent.height for extent in extents]) size = anns[0].get_fontsize() * min(scale_x / max_width, scale_y / max_height) for ann in anns: ann.set_fontsize(size) return anns
def export(self, decision_tree, ax=None): import matplotlib.pyplot as plt from matplotlib.text import Annotation if ax is None: ax = plt.gca() ax.clear() ax.set_axis_off() <DeepExtract> name = self.node_to_str(decision_tree.tree_, 0, criterion=decision_tree.criterion) if decision_tree.tree_.children_left[0] != _tree.TREE_LEAF and (self.max_depth is None or depth <= self.max_depth): children = [self._make_tree(decision_tree.tree_.children_left[0], decision_tree.tree_, decision_tree.criterion, depth=depth + 1), self._make_tree(decision_tree.tree_.children_right[0], decision_tree.tree_, decision_tree.criterion, depth=depth + 1)] else: my_tree = Tree(name, 0) my_tree = Tree(name, 0, *children) </DeepExtract> draw_tree = buchheim(my_tree) (max_x, max_y) = draw_tree.max_extents() + 1 ax_width = ax.get_window_extent().width ax_height = ax.get_window_extent().height scale_x = ax_width / max_x scale_y = ax_height / max_y <DeepExtract> if decision_tree.tree_ == _tree.TREE_LEAF: raise ValueError('Invalid node_id %s' % _tree.TREE_LEAF) left_child = draw_tree.children_left[decision_tree.tree_] right_child = draw_tree.children_right[decision_tree.tree_] if self.max_depth is None or max_y <= self.max_depth: if left_child == _tree.TREE_LEAF: self.ranks['leaves'].append(str(decision_tree.tree_)) elif str(max_y) not in self.ranks: self.ranks[str(max_y)] = [str(decision_tree.tree_)] else: self.ranks[str(max_y)].append(str(decision_tree.tree_)) self.out_file.write('%d [label=%s' % (decision_tree.tree_, self.node_to_str(draw_tree, decision_tree.tree_, ax))) if self.filled: self.out_file.write(', fillcolor="%s"' % self.get_fill_color(draw_tree, decision_tree.tree_)) self.out_file.write('] ;\n') if max_x is not None: self.out_file.write('%d -> %d' % (max_x, decision_tree.tree_)) if max_x == 0: angles = np.array([45, -45]) * ((self.rotate - 0.5) * -2) self.out_file.write(' [labeldistance=2.5, labelangle=') if decision_tree.tree_ == 1: self.out_file.write('%d, headlabel="True"]' % angles[0]) else: self.out_file.write('%d, headlabel="False"]' % angles[1]) self.out_file.write(' ;\n') if left_child != _tree.TREE_LEAF: self.recurse(draw_tree, left_child, criterion=ax, parent=decision_tree.tree_, depth=max_y + 1) self.recurse(draw_tree, right_child, criterion=ax, parent=decision_tree.tree_, depth=max_y + 1) else: self.ranks['leaves'].append(str(decision_tree.tree_)) self.out_file.write('%d [label="(...)"' % decision_tree.tree_) if self.filled: self.out_file.write(', fillcolor="#C0C0C0"') self.out_file.write('] ;\n' % decision_tree.tree_) if max_x is not None: self.out_file.write('%d -> %d ;\n' % (max_x, decision_tree.tree_)) </DeepExtract> anns = [ann for ann in ax.get_children() if isinstance(ann, Annotation)] renderer = ax.figure.canvas.get_renderer() for ann in anns: ann.update_bbox_position_size(renderer) if self.fontsize is None: extents = [ann.get_bbox_patch().get_window_extent() for ann in anns] max_width = max([extent.width for extent in extents]) max_height = max([extent.height for extent in extents]) size = anns[0].get_fontsize() * min(scale_x / max_width, scale_y / max_height) for ann in anns: ann.set_fontsize(size) return anns
def test_branching_factor(global_random_seed, global_dtype): (X, y) = make_blobs(random_state=global_random_seed) X = X.astype(global_dtype, copy=False) branching_factor = 9 brc = Birch(n_clusters=None, branching_factor=branching_factor, threshold=0.01) brc.fit(X) subclusters = brc.root_.subclusters_ assert branching_factor >= len(subclusters) for cluster in subclusters: if cluster.child_: check_branching_factor(cluster.child_, branching_factor) brc = Birch(n_clusters=3, branching_factor=branching_factor, threshold=0.01) brc.fit(X) subclusters = brc.root_.subclusters_ assert branching_factor >= len(subclusters) for cluster in subclusters: if cluster.child_: check_branching_factor(cluster.child_, branching_factor) </DeepExtract>
def test_branching_factor(global_random_seed, global_dtype): (X, y) = make_blobs(random_state=global_random_seed) X = X.astype(global_dtype, copy=False) branching_factor = 9 brc = Birch(n_clusters=None, branching_factor=branching_factor, threshold=0.01) brc.fit(X) <DeepExtract> subclusters = brc.root_.subclusters_ assert branching_factor >= len(subclusters) for cluster in subclusters: if cluster.child_: check_branching_factor(cluster.child_, branching_factor) </DeepExtract> brc = Birch(n_clusters=3, branching_factor=branching_factor, threshold=0.01) brc.fit(X) <DeepExtract> subclusters = brc.root_.subclusters_ assert branching_factor >= len(subclusters) for cluster in subclusters: if cluster.child_: check_branching_factor(cluster.child_, branching_factor) </DeepExtract>
def _solve_lsqr(X, y, *, alpha, fit_intercept=True, max_iter=None, tol=0.0001, X_offset=None, X_scale=None, sample_weight_sqrt=None): """Solve Ridge regression via LSQR. We expect that y is always mean centered. If X is dense, we expect it to be mean centered such that we can solve ||y - Xw||_2^2 + alpha * ||w||_2^2 If X is sparse, we expect X_offset to be given such that we can solve ||y - (X - X_offset)w||_2^2 + alpha * ||w||_2^2 With sample weights S=diag(sample_weight), this becomes ||sqrt(S) (y - (X - X_offset) w)||_2^2 + alpha * ||w||_2^2 and we expect y and X to already be rescaled, i.e. sqrt(S) @ y, sqrt(S) @ X. In this case, X_offset is the sample_weight weighted mean of X before scaling by sqrt(S). The objective then reads ||y - (X - sqrt(S) X_offset) w)||_2^2 + alpha * ||w||_2^2 """ if sample_weight_sqrt is None: sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype) if sparse.issparse(X) and fit_intercept: X_offset_scale = X_offset / X_scale def matvec(b): X1 = X.dot(b) - sample_weight_sqrt * b.dot(X_offset_scale) def rmatvec(b): X1 = X.T.dot(b) - X_offset_scale * b.dot(sample_weight_sqrt) X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec) X1 = X1 else: X1 = X (n_samples, n_features) = X.shape coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) n_iter = np.empty(y.shape[1], dtype=np.int32) sqrt_alpha = np.sqrt(alpha) for i in range(y.shape[1]): y_column = y[:, i] info = sp_linalg.lsqr(X1, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter) coefs[i] = info[0] n_iter[i] = info[2] return (coefs, n_iter)
def _solve_lsqr(X, y, *, alpha, fit_intercept=True, max_iter=None, tol=0.0001, X_offset=None, X_scale=None, sample_weight_sqrt=None): """Solve Ridge regression via LSQR. We expect that y is always mean centered. If X is dense, we expect it to be mean centered such that we can solve ||y - Xw||_2^2 + alpha * ||w||_2^2 If X is sparse, we expect X_offset to be given such that we can solve ||y - (X - X_offset)w||_2^2 + alpha * ||w||_2^2 With sample weights S=diag(sample_weight), this becomes ||sqrt(S) (y - (X - X_offset) w)||_2^2 + alpha * ||w||_2^2 and we expect y and X to already be rescaled, i.e. sqrt(S) @ y, sqrt(S) @ X. In this case, X_offset is the sample_weight weighted mean of X before scaling by sqrt(S). The objective then reads ||y - (X - sqrt(S) X_offset) w)||_2^2 + alpha * ||w||_2^2 """ if sample_weight_sqrt is None: sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype) if sparse.issparse(X) and fit_intercept: X_offset_scale = X_offset / X_scale <DeepExtract> def matvec(b): X1 = X.dot(b) - sample_weight_sqrt * b.dot(X_offset_scale) def rmatvec(b): X1 = X.T.dot(b) - X_offset_scale * b.dot(sample_weight_sqrt) X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec) X1 = X1 </DeepExtract> else: X1 = X (n_samples, n_features) = X.shape coefs = np.empty((y.shape[1], n_features), dtype=X.dtype) n_iter = np.empty(y.shape[1], dtype=np.int32) sqrt_alpha = np.sqrt(alpha) for i in range(y.shape[1]): y_column = y[:, i] info = sp_linalg.lsqr(X1, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter) coefs[i] = info[0] n_iter[i] = info[2] return (coefs, n_iter)
@hides def predict_proba(self, X, *args, **kwargs): check_is_fitted(self) return np.ones(X.shape[0])
@hides def predict_proba(self, X, *args, **kwargs): <DeepExtract> check_is_fitted(self) </DeepExtract> return np.ones(X.shape[0])
@validate_params({'y_true': ['array-like', 'sparse matrix'], 'y_pred': ['array-like', 'sparse matrix'], 'labels': ['array-like', None], 'pos_label': [Real, str, 'boolean', None], 'average': [StrOptions({'micro', 'macro', 'samples', 'weighted', 'binary'}), None], 'sample_weight': ['array-like', None], 'zero_division': [Options(Real, {0.0, 1.0, np.nan}), StrOptions({'warn'})]}) def recall_score(y_true, y_pred, *, labels=None, pos_label=1, average='binary', sample_weight=None, zero_division='warn'): """Compute the recall. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) target values. y_pred : 1d array-like, or label indicator array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when ``average != 'binary'``, and their order if ``average is None``. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in ``y_true`` and ``y_pred`` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if ``average='binary'`` and the data is binary. If the data are multiclass or multilabel, this will be ignored; setting ``labels=[pos_label]`` and ``average != 'binary'`` will report scores for that label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. Weighted recall is equal to accuracy. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- recall : float (if average is not None) or array of float of shape (n_unique_labels,) Recall of the positive class in binary classification or weighted average of the recall of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute precision, recall, F-measure and support for each class. precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced datasets. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given an estimator and some data. PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given binary class predictions. Notes ----- When ``true positive + false negative == 0``, recall returns 0 and raises ``UndefinedMetricWarning``. This behavior can be modified with ``zero_division``. Examples -------- >>> import numpy as np >>> from sklearn.metrics import recall_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> recall_score(y_true, y_pred, average='macro') 0.33... >>> recall_score(y_true, y_pred, average='micro') 0.33... >>> recall_score(y_true, y_pred, average='weighted') 0.33... >>> recall_score(y_true, y_pred, average=None) array([1., 0., 0.]) >>> y_true = [0, 0, 0, 0, 0, 0] >>> recall_score(y_true, y_pred, average=None) array([0.5, 0. , 0. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=1) array([0.5, 1. , 1. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=np.nan) array([0.5, nan, nan]) >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> recall_score(y_true, y_pred, average=None) array([1. , 1. , 0.5]) """ zero_division_value = _check_zero_division(zero_division) labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) samplewise = average == 'samples' MCM = multilabel_confusion_matrix(y_true, y_pred, sample_weight=sample_weight, labels=labels, samplewise=samplewise) tp_sum = MCM[:, 1, 1] pred_sum = tp_sum + MCM[:, 0, 1] true_sum = tp_sum + MCM[:, 1, 0] if average == 'micro': tp_sum = np.array([tp_sum.sum()]) pred_sum = np.array([pred_sum.sum()]) true_sum = np.array([true_sum.sum()]) beta2 = beta ** 2 precision = _prf_divide(tp_sum, pred_sum, 'precision', 'predicted', average, ('recall',), zero_division) recall = _prf_divide(tp_sum, true_sum, 'recall', 'true', average, ('recall',), zero_division) if zero_division == 'warn' and ('f-score',) == ('recall',): if (pred_sum[true_sum == 0] == 0).any(): _warn_prf(average, 'true nor predicted', 'F-score is', len(true_sum)) if np.isposinf(beta): f_score = recall elif beta == 0: f_score = precision else: denom = beta2 * precision + recall mask = np.isclose(denom, 0) | np.isclose(pred_sum + true_sum, 0) denom[mask] = 1 f_score = (1 + beta2) * precision * recall / denom f_score[mask] = zero_division_value if average == 'weighted': weights = true_sum elif average == 'samples': weights = sample_weight else: weights = None if average is not None: assert average != 'binary' or len(precision) == 1 precision = _nanaverage(precision, weights=weights) recall = _nanaverage(recall, weights=weights) f_score = _nanaverage(f_score, weights=weights) true_sum = None (_, r, _, _) = (precision, recall, f_score, true_sum) return r
@validate_params({'y_true': ['array-like', 'sparse matrix'], 'y_pred': ['array-like', 'sparse matrix'], 'labels': ['array-like', None], 'pos_label': [Real, str, 'boolean', None], 'average': [StrOptions({'micro', 'macro', 'samples', 'weighted', 'binary'}), None], 'sample_weight': ['array-like', None], 'zero_division': [Options(Real, {0.0, 1.0, np.nan}), StrOptions({'warn'})]}) def recall_score(y_true, y_pred, *, labels=None, pos_label=1, average='binary', sample_weight=None, zero_division='warn'): """Compute the recall. The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of true positives and ``fn`` the number of false negatives. The recall is intuitively the ability of the classifier to find all the positive samples. The best value is 1 and the worst value is 0. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : 1d array-like, or label indicator array / sparse matrix Ground truth (correct) target values. y_pred : 1d array-like, or label indicator array / sparse matrix Estimated targets as returned by a classifier. labels : array-like, default=None The set of labels to include when ``average != 'binary'``, and their order if ``average is None``. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in ``y_true`` and ``y_pred`` are used in sorted order. .. versionchanged:: 0.17 Parameter `labels` improved for multiclass problem. pos_label : int, float, bool or str, default=1 The class to report if ``average='binary'`` and the data is binary. If the data are multiclass or multilabel, this will be ignored; setting ``labels=[pos_label]`` and ``average != 'binary'`` will report scores for that label only. average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, default='binary' This parameter is required for multiclass/multilabel targets. If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'binary'``: Only report results for the class specified by ``pos_label``. This is applicable only if targets (``y_{true,pred}``) are binary. ``'micro'``: Calculate metrics globally by counting the total true positives, false negatives and false positives. ``'macro'``: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. ``'weighted'``: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters 'macro' to account for label imbalance; it can result in an F-score that is not between precision and recall. Weighted recall is equal to accuracy. ``'samples'``: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification where this differs from :func:`accuracy_score`). sample_weight : array-like of shape (n_samples,), default=None Sample weights. zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" Sets the value to return when there is a zero division. Notes: - If set to "warn", this acts like 0, but a warning is also raised. - If set to `np.nan`, such values will be excluded from the average. .. versionadded:: 1.3 `np.nan` option was added. Returns ------- recall : float (if average is not None) or array of float of shape (n_unique_labels,) Recall of the positive class in binary classification or weighted average of the recall of each class for the multiclass task. See Also -------- precision_recall_fscore_support : Compute precision, recall, F-measure and support for each class. precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the number of true positives and ``fp`` the number of false positives. balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced datasets. multilabel_confusion_matrix : Compute a confusion matrix for each class or sample. PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given an estimator and some data. PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given binary class predictions. Notes ----- When ``true positive + false negative == 0``, recall returns 0 and raises ``UndefinedMetricWarning``. This behavior can be modified with ``zero_division``. Examples -------- >>> import numpy as np >>> from sklearn.metrics import recall_score >>> y_true = [0, 1, 2, 0, 1, 2] >>> y_pred = [0, 2, 1, 0, 0, 1] >>> recall_score(y_true, y_pred, average='macro') 0.33... >>> recall_score(y_true, y_pred, average='micro') 0.33... >>> recall_score(y_true, y_pred, average='weighted') 0.33... >>> recall_score(y_true, y_pred, average=None) array([1., 0., 0.]) >>> y_true = [0, 0, 0, 0, 0, 0] >>> recall_score(y_true, y_pred, average=None) array([0.5, 0. , 0. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=1) array([0.5, 1. , 1. ]) >>> recall_score(y_true, y_pred, average=None, zero_division=np.nan) array([0.5, nan, nan]) >>> # multilabel classification >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] >>> recall_score(y_true, y_pred, average=None) array([1. , 1. , 0.5]) """ <DeepExtract> zero_division_value = _check_zero_division(zero_division) labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) samplewise = average == 'samples' MCM = multilabel_confusion_matrix(y_true, y_pred, sample_weight=sample_weight, labels=labels, samplewise=samplewise) tp_sum = MCM[:, 1, 1] pred_sum = tp_sum + MCM[:, 0, 1] true_sum = tp_sum + MCM[:, 1, 0] if average == 'micro': tp_sum = np.array([tp_sum.sum()]) pred_sum = np.array([pred_sum.sum()]) true_sum = np.array([true_sum.sum()]) beta2 = beta ** 2 precision = _prf_divide(tp_sum, pred_sum, 'precision', 'predicted', average, ('recall',), zero_division) recall = _prf_divide(tp_sum, true_sum, 'recall', 'true', average, ('recall',), zero_division) if zero_division == 'warn' and ('f-score',) == ('recall',): if (pred_sum[true_sum == 0] == 0).any(): _warn_prf(average, 'true nor predicted', 'F-score is', len(true_sum)) if np.isposinf(beta): f_score = recall elif beta == 0: f_score = precision else: denom = beta2 * precision + recall mask = np.isclose(denom, 0) | np.isclose(pred_sum + true_sum, 0) denom[mask] = 1 f_score = (1 + beta2) * precision * recall / denom f_score[mask] = zero_division_value if average == 'weighted': weights = true_sum elif average == 'samples': weights = sample_weight else: weights = None if average is not None: assert average != 'binary' or len(precision) == 1 precision = _nanaverage(precision, weights=weights) recall = _nanaverage(recall, weights=weights) f_score = _nanaverage(f_score, weights=weights) true_sum = None (_, r, _, _) = (precision, recall, f_score, true_sum) </DeepExtract> return r
@pytest.mark.filterwarnings('ignore:EfficiencyWarning') def check_precomputed(make_train_test, estimators): """Tests unsupervised NearestNeighbors with a distance matrix.""" rng = np.random.RandomState(42) X = rng.random_sample((10, 4)) Y = rng.random_sample((3, 4)) (DXX, DYX) = (metrics.pairwise_distances(X), metrics.pairwise_distances(Y, X)) for method in ['kneighbors']: nbrs_X = neighbors.NearestNeighbors(n_neighbors=3) nbrs_X.fit(X) (dist_X, ind_X) = getattr(nbrs_X, method)(Y) nbrs_D = neighbors.NearestNeighbors(n_neighbors=3, algorithm='brute', metric='precomputed') nbrs_D.fit(DXX) (dist_D, ind_D) = getattr(nbrs_D, method)(DYX) assert_allclose(dist_X, dist_D) assert_array_equal(ind_X, ind_D) nbrs_D = neighbors.NearestNeighbors(n_neighbors=3, algorithm='auto', metric='precomputed') nbrs_D.fit(DXX) (dist_D, ind_D) = getattr(nbrs_D, method)(DYX) assert_allclose(dist_X, dist_D) assert_array_equal(ind_X, ind_D) (dist_X, ind_X) = getattr(nbrs_X, method)(None) (dist_D, ind_D) = getattr(nbrs_D, method)(None) assert_allclose(dist_X, dist_D) assert_array_equal(ind_X, ind_D) with pytest.raises(ValueError): getattr(nbrs_D, method)(X) target = np.arange(X.shape[0]) for Est in estimators: est = Est(metric='euclidean') est.radius = est.n_neighbors = 1 pred_X = est.fit(X, target).predict(Y) est.metric = 'precomputed' pred_D = est.fit(DXX, target).predict(DYX) assert_allclose(pred_X, pred_D)
@pytest.mark.filterwarnings('ignore:EfficiencyWarning') def check_precomputed(make_train_test, estimators): """Tests unsupervised NearestNeighbors with a distance matrix.""" rng = np.random.RandomState(42) X = rng.random_sample((10, 4)) Y = rng.random_sample((3, 4)) <DeepExtract> (DXX, DYX) = (metrics.pairwise_distances(X), metrics.pairwise_distances(Y, X)) </DeepExtract> for method in ['kneighbors']: nbrs_X = neighbors.NearestNeighbors(n_neighbors=3) nbrs_X.fit(X) (dist_X, ind_X) = getattr(nbrs_X, method)(Y) nbrs_D = neighbors.NearestNeighbors(n_neighbors=3, algorithm='brute', metric='precomputed') nbrs_D.fit(DXX) (dist_D, ind_D) = getattr(nbrs_D, method)(DYX) assert_allclose(dist_X, dist_D) assert_array_equal(ind_X, ind_D) nbrs_D = neighbors.NearestNeighbors(n_neighbors=3, algorithm='auto', metric='precomputed') nbrs_D.fit(DXX) (dist_D, ind_D) = getattr(nbrs_D, method)(DYX) assert_allclose(dist_X, dist_D) assert_array_equal(ind_X, ind_D) (dist_X, ind_X) = getattr(nbrs_X, method)(None) (dist_D, ind_D) = getattr(nbrs_D, method)(None) assert_allclose(dist_X, dist_D) assert_array_equal(ind_X, ind_D) with pytest.raises(ValueError): getattr(nbrs_D, method)(X) target = np.arange(X.shape[0]) for Est in estimators: est = Est(metric='euclidean') est.radius = est.n_neighbors = 1 pred_X = est.fit(X, target).predict(Y) est.metric = 'precomputed' pred_D = est.fit(DXX, target).predict(DYX) assert_allclose(pred_X, pred_D)
@pytest.mark.parametrize('gzip_response', [True, False]) @pytest.mark.parametrize('dataset_params', [{'data_id': 40675}, {'data_id': None, 'name': 'glass2', 'version': 1}]) def test_fetch_openml_inactive(monkeypatch, gzip_response, dataset_params): """Check that we raise a warning when the dataset is inactive.""" data_id = 40675 url_prefix_data_description = 'https://openml.org/api/v1/json/data/' url_prefix_data_features = 'https://openml.org/api/v1/json/data/features/' url_prefix_download_data = 'https://openml.org/data/v1/' url_prefix_data_list = 'https://openml.org/api/v1/json/data/list/' path_suffix = '.gz' read_fn = gzip.open data_module = OPENML_TEST_DATA_MODULE + '.' + f'id_{data_id}' def _file_name(url, suffix): output = re.sub('\\W', '-', url[len('https://openml.org/'):]) + suffix + path_suffix return output.replace('-json-data-list', '-jdl').replace('-json-data-features', '-jdf').replace('-json-data-qualities', '-jdq').replace('-json-data', '-jd').replace('-data_name', '-dn').replace('-download', '-dl').replace('-limit', '-l').replace('-data_version', '-dv').replace('-status', '-s').replace('-deactivated', '-dact').replace('-active', '-act') def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix): assert url.startswith(expected_prefix) data_file_name = _file_name(url, suffix) with _open_binary(data_module, data_file_name) as f: if has_gzip_header and gzip_response: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen_data_description(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_description, suffix='.json') def _mock_urlopen_data_features(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_features, suffix='.json') def _mock_urlopen_download_data(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_download_data, suffix='.arff') def _mock_urlopen_data_list(url, has_gzip_header): assert url.startswith(url_prefix_data_list) data_file_name = _file_name(url, '.json') with _open_binary(data_module, data_file_name) as f: decompressed_f = read_fn(f, 'rb') decoded_s = decompressed_f.read().decode('utf-8') json_data = json.loads(decoded_s) if 'error' in json_data: raise HTTPError(url=None, code=412, msg='Simulated mock error', hdrs=None, fp=None) with _open_binary(data_module, data_file_name) as f: if has_gzip_header: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen(request, *args, **kwargs): url = request.get_full_url() has_gzip_header = request.get_header('Accept-encoding') == 'gzip' if url.startswith(url_prefix_data_list): return _mock_urlopen_data_list(url, has_gzip_header) elif url.startswith(url_prefix_data_features): return _mock_urlopen_data_features(url, has_gzip_header) elif url.startswith(url_prefix_download_data): return _mock_urlopen_download_data(url, has_gzip_header) elif url.startswith(url_prefix_data_description): return _mock_urlopen_data_description(url, has_gzip_header) else: raise ValueError('Unknown mocking URL pattern: %s' % url) if test_offline: monkeypatch.setattr(sklearn.datasets._openml, 'urlopen', _mock_urlopen) msg = 'Version 1 of dataset glass2 is inactive,' with pytest.warns(UserWarning, match=msg): glass2 = fetch_openml(cache=False, as_frame=False, parser='liac-arff', **dataset_params) assert glass2.data.shape == (163, 9) assert glass2.details['id'] == '40675'
@pytest.mark.parametrize('gzip_response', [True, False]) @pytest.mark.parametrize('dataset_params', [{'data_id': 40675}, {'data_id': None, 'name': 'glass2', 'version': 1}]) def test_fetch_openml_inactive(monkeypatch, gzip_response, dataset_params): """Check that we raise a warning when the dataset is inactive.""" data_id = 40675 <DeepExtract> url_prefix_data_description = 'https://openml.org/api/v1/json/data/' url_prefix_data_features = 'https://openml.org/api/v1/json/data/features/' url_prefix_download_data = 'https://openml.org/data/v1/' url_prefix_data_list = 'https://openml.org/api/v1/json/data/list/' path_suffix = '.gz' read_fn = gzip.open data_module = OPENML_TEST_DATA_MODULE + '.' + f'id_{data_id}' def _file_name(url, suffix): output = re.sub('\\W', '-', url[len('https://openml.org/'):]) + suffix + path_suffix return output.replace('-json-data-list', '-jdl').replace('-json-data-features', '-jdf').replace('-json-data-qualities', '-jdq').replace('-json-data', '-jd').replace('-data_name', '-dn').replace('-download', '-dl').replace('-limit', '-l').replace('-data_version', '-dv').replace('-status', '-s').replace('-deactivated', '-dact').replace('-active', '-act') def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix): assert url.startswith(expected_prefix) data_file_name = _file_name(url, suffix) with _open_binary(data_module, data_file_name) as f: if has_gzip_header and gzip_response: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen_data_description(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_description, suffix='.json') def _mock_urlopen_data_features(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_data_features, suffix='.json') def _mock_urlopen_download_data(url, has_gzip_header): return _mock_urlopen_shared(url=url, has_gzip_header=has_gzip_header, expected_prefix=url_prefix_download_data, suffix='.arff') def _mock_urlopen_data_list(url, has_gzip_header): assert url.startswith(url_prefix_data_list) data_file_name = _file_name(url, '.json') with _open_binary(data_module, data_file_name) as f: decompressed_f = read_fn(f, 'rb') decoded_s = decompressed_f.read().decode('utf-8') json_data = json.loads(decoded_s) if 'error' in json_data: raise HTTPError(url=None, code=412, msg='Simulated mock error', hdrs=None, fp=None) with _open_binary(data_module, data_file_name) as f: if has_gzip_header: fp = BytesIO(f.read()) return _MockHTTPResponse(fp, True) else: decompressed_f = read_fn(f, 'rb') fp = BytesIO(decompressed_f.read()) return _MockHTTPResponse(fp, False) def _mock_urlopen(request, *args, **kwargs): url = request.get_full_url() has_gzip_header = request.get_header('Accept-encoding') == 'gzip' if url.startswith(url_prefix_data_list): return _mock_urlopen_data_list(url, has_gzip_header) elif url.startswith(url_prefix_data_features): return _mock_urlopen_data_features(url, has_gzip_header) elif url.startswith(url_prefix_download_data): return _mock_urlopen_download_data(url, has_gzip_header) elif url.startswith(url_prefix_data_description): return _mock_urlopen_data_description(url, has_gzip_header) else: raise ValueError('Unknown mocking URL pattern: %s' % url) if test_offline: monkeypatch.setattr(sklearn.datasets._openml, 'urlopen', _mock_urlopen) </DeepExtract> msg = 'Version 1 of dataset glass2 is inactive,' with pytest.warns(UserWarning, match=msg): glass2 = fetch_openml(cache=False, as_frame=False, parser='liac-arff', **dataset_params) assert glass2.data.shape == (163, 9) assert glass2.details['id'] == '40675'
def test_lda_fit_online(): rng = np.random.RandomState(0) n_components = 3 block = np.full((3, 3), n_components, dtype=int) blocks = [block] * n_components X = block_diag(*blocks) X = csr_matrix(X) (n_components, X) = (n_components, X) lda = LatentDirichletAllocation(n_components=n_components, learning_offset=10.0, evaluate_every=1, learning_method='online', random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: top_idx = set(component.argsort()[-3:][::-1]) assert tuple(sorted(top_idx)) in correct_idx_grps
def test_lda_fit_online(): rng = np.random.RandomState(0) <DeepExtract> n_components = 3 block = np.full((3, 3), n_components, dtype=int) blocks = [block] * n_components X = block_diag(*blocks) X = csr_matrix(X) (n_components, X) = (n_components, X) </DeepExtract> lda = LatentDirichletAllocation(n_components=n_components, learning_offset=10.0, evaluate_every=1, learning_method='online', random_state=rng) lda.fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for component in lda.components_: top_idx = set(component.argsort()[-3:][::-1]) assert tuple(sorted(top_idx)) in correct_idx_grps
@validate_params({'labels_true': ['array-like'], 'labels_pred': ['array-like'], 'average_method': [StrOptions({'arithmetic', 'max', 'min', 'geometric'})]}) def adjusted_mutual_info_score(labels_true, labels_pred, *, average_method='arithmetic'): """Adjusted Mutual Information between two clusterings. Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for chance. It accounts for the fact that the MI is generally higher for two clusterings with a larger number of clusters, regardless of whether there is actually more information shared. For two clusterings :math:`U` and :math:`V`, the AMI is given as:: AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [avg(H(U), H(V)) - E(MI(U, V))] This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching :math:`U` (``label_true``) with :math:`V` (``labels_pred``) will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Be mindful that this function is an order of magnitude slower than other metrics, such as the Adjusted Rand Index. Read more in the :ref:`User Guide <mutual_info_score>`. Parameters ---------- labels_true : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets, called :math:`U` in the above formula. labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets, called :math:`V` in the above formula. average_method : {'min', 'geometric', 'arithmetic', 'max'}, default='arithmetic' How to compute the normalizer in the denominator. .. versionadded:: 0.20 .. versionchanged:: 0.22 The default value of ``average_method`` changed from 'max' to 'arithmetic'. Returns ------- ami: float (upperlimited by 1.0) The AMI returns a value of 1 when the two partitions are identical (ie perfectly matched). Random partitions (independent labellings) have an expected AMI around 0 on average hence can be negative. The value is in adjusted nats (based on the natural logarithm). See Also -------- adjusted_rand_score : Adjusted Rand Index. mutual_info_score : Mutual Information (not adjusted for chance). References ---------- .. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for Clusterings Comparison: Variants, Properties, Normalization and Correction for Chance, JMLR <http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>`_ .. [2] `Wikipedia entry for the Adjusted Mutual Information <https://en.wikipedia.org/wiki/Adjusted_Mutual_Information>`_ Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import adjusted_mutual_info_score >>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) ... # doctest: +SKIP 1.0 >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) ... # doctest: +SKIP 1.0 If classes members are completely split across different clusters, the assignment is totally in-complete, hence the AMI is null:: >>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) ... # doctest: +SKIP 0.0 """ labels_true = check_array(labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None) labels_pred = check_array(labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None) type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred) if 'continuous' in (type_pred, type_label): msg = f'Clustering metrics expects discrete values but received {type_label} values for label, and {type_pred} values for target' warnings.warn(msg, UserWarning) if labels_true.ndim != 1: raise ValueError('labels_true must be 1D: shape is %r' % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError('labels_pred must be 1D: shape is %r' % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred) (labels_true, labels_pred) = (labels_true, labels_pred) n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred) if classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0: return 1.0 if eps is not None and True: raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] contingency = sp.coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype) if True: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: contingency = contingency + eps contingency = contingency if contingency is None: (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) else: contingency = check_array(contingency, accept_sparse=['csr', 'csc', 'coo'], dtype=[int, np.int32, np.int64]) if isinstance(contingency, np.ndarray): (nzx, nzy) = np.nonzero(contingency) nz_val = contingency[nzx, nzy] else: (nzx, nzy, nz_val) = sp.find(contingency) contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0)) if pi.size == 1 or pj.size == 1: mi = 0.0 log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(np.int64, copy=False) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) mi = np.clip(mi.sum(), 0.0, None) emi = expected_mutual_information(contingency, n_samples) (h_true, h_pred) = (entropy(labels_true), entropy(labels_pred)) if average_method == 'min': normalizer = min(h_true, h_pred) elif average_method == 'geometric': normalizer = np.sqrt(h_true * h_pred) elif average_method == 'arithmetic': normalizer = np.mean([h_true, h_pred]) elif average_method == 'max': normalizer = max(h_true, h_pred) else: raise ValueError("'average_method' must be 'min', 'geometric', 'arithmetic', or 'max'") denominator = normalizer - emi if denominator < 0: denominator = min(denominator, -np.finfo('float64').eps) else: denominator = max(denominator, np.finfo('float64').eps) ami = (mi - emi) / denominator return ami
@validate_params({'labels_true': ['array-like'], 'labels_pred': ['array-like'], 'average_method': [StrOptions({'arithmetic', 'max', 'min', 'geometric'})]}) def adjusted_mutual_info_score(labels_true, labels_pred, *, average_method='arithmetic'): """Adjusted Mutual Information between two clusterings. Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for chance. It accounts for the fact that the MI is generally higher for two clusterings with a larger number of clusters, regardless of whether there is actually more information shared. For two clusterings :math:`U` and :math:`V`, the AMI is given as:: AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [avg(H(U), H(V)) - E(MI(U, V))] This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching :math:`U` (``label_true``) with :math:`V` (``labels_pred``) will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Be mindful that this function is an order of magnitude slower than other metrics, such as the Adjusted Rand Index. Read more in the :ref:`User Guide <mutual_info_score>`. Parameters ---------- labels_true : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets, called :math:`U` in the above formula. labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets, called :math:`V` in the above formula. average_method : {'min', 'geometric', 'arithmetic', 'max'}, default='arithmetic' How to compute the normalizer in the denominator. .. versionadded:: 0.20 .. versionchanged:: 0.22 The default value of ``average_method`` changed from 'max' to 'arithmetic'. Returns ------- ami: float (upperlimited by 1.0) The AMI returns a value of 1 when the two partitions are identical (ie perfectly matched). Random partitions (independent labellings) have an expected AMI around 0 on average hence can be negative. The value is in adjusted nats (based on the natural logarithm). See Also -------- adjusted_rand_score : Adjusted Rand Index. mutual_info_score : Mutual Information (not adjusted for chance). References ---------- .. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for Clusterings Comparison: Variants, Properties, Normalization and Correction for Chance, JMLR <http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>`_ .. [2] `Wikipedia entry for the Adjusted Mutual Information <https://en.wikipedia.org/wiki/Adjusted_Mutual_Information>`_ Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import adjusted_mutual_info_score >>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) ... # doctest: +SKIP 1.0 >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) ... # doctest: +SKIP 1.0 If classes members are completely split across different clusters, the assignment is totally in-complete, hence the AMI is null:: >>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) ... # doctest: +SKIP 0.0 """ <DeepExtract> labels_true = check_array(labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None) labels_pred = check_array(labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None) type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred) if 'continuous' in (type_pred, type_label): msg = f'Clustering metrics expects discrete values but received {type_label} values for label, and {type_pred} values for target' warnings.warn(msg, UserWarning) if labels_true.ndim != 1: raise ValueError('labels_true must be 1D: shape is %r' % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError('labels_pred must be 1D: shape is %r' % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred) (labels_true, labels_pred) = (labels_true, labels_pred) </DeepExtract> n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred) if classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0: return 1.0 <DeepExtract> if eps is not None and True: raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] contingency = sp.coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype) if True: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: contingency = contingency + eps contingency = contingency </DeepExtract> <DeepExtract> if contingency is None: (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) else: contingency = check_array(contingency, accept_sparse=['csr', 'csc', 'coo'], dtype=[int, np.int32, np.int64]) if isinstance(contingency, np.ndarray): (nzx, nzy) = np.nonzero(contingency) nz_val = contingency[nzx, nzy] else: (nzx, nzy, nz_val) = sp.find(contingency) contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0)) if pi.size == 1 or pj.size == 1: mi = 0.0 log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(np.int64, copy=False) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) mi = np.clip(mi.sum(), 0.0, None) </DeepExtract> emi = expected_mutual_information(contingency, n_samples) (h_true, h_pred) = (entropy(labels_true), entropy(labels_pred)) <DeepExtract> if average_method == 'min': normalizer = min(h_true, h_pred) elif average_method == 'geometric': normalizer = np.sqrt(h_true * h_pred) elif average_method == 'arithmetic': normalizer = np.mean([h_true, h_pred]) elif average_method == 'max': normalizer = max(h_true, h_pred) else: raise ValueError("'average_method' must be 'min', 'geometric', 'arithmetic', or 'max'") </DeepExtract> denominator = normalizer - emi if denominator < 0: denominator = min(denominator, -np.finfo('float64').eps) else: denominator = max(denominator, np.finfo('float64').eps) ami = (mi - emi) / denominator return ami
def fit_transform(self, X, y=None, **fit_params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like of shape (n_samples, n_outputs), default=None Targets for supervised learning. **fit_params : dict, default=None Parameters to pass to the fit method of the estimator. Returns ------- X_t : array-like or sparse matrix of shape (n_samples, sum_n_components) The `hstack` of results of transformers. `sum_n_components` is the sum of `n_components` (output dimension) over transformers. """ self.transformer_list = list(self.transformer_list) self._validate_transformers() self._validate_transformer_weights() transformers = list(self._iter()) results = Parallel(n_jobs=self.n_jobs)((delayed(_fit_transform_one)(transformer, X, y, weight, message_clsname='FeatureUnion', message=self._log_message(name, idx, len(transformers)), **fit_params) for (idx, (name, transformer, weight)) in enumerate(transformers, 1))) if not results: return np.zeros((X.shape[0], 0)) (Xs, transformers) = zip(*results) transformers = iter(transformers) self.transformer_list[:] = [(name, old if old == 'drop' else next(transformers)) for (name, old) in self.transformer_list] return self._hstack(Xs)
def fit_transform(self, X, y=None, **fit_params): """Fit all transformers, transform the data and concatenate results. Parameters ---------- X : iterable or array-like, depending on transformers Input data to be transformed. y : array-like of shape (n_samples, n_outputs), default=None Targets for supervised learning. **fit_params : dict, default=None Parameters to pass to the fit method of the estimator. Returns ------- X_t : array-like or sparse matrix of shape (n_samples, sum_n_components) The `hstack` of results of transformers. `sum_n_components` is the sum of `n_components` (output dimension) over transformers. """ <DeepExtract> self.transformer_list = list(self.transformer_list) self._validate_transformers() self._validate_transformer_weights() transformers = list(self._iter()) results = Parallel(n_jobs=self.n_jobs)((delayed(_fit_transform_one)(transformer, X, y, weight, message_clsname='FeatureUnion', message=self._log_message(name, idx, len(transformers)), **fit_params) for (idx, (name, transformer, weight)) in enumerate(transformers, 1))) </DeepExtract> if not results: return np.zeros((X.shape[0], 0)) (Xs, transformers) = zip(*results) <DeepExtract> transformers = iter(transformers) self.transformer_list[:] = [(name, old if old == 'drop' else next(transformers)) for (name, old) in self.transformer_list] </DeepExtract> return self._hstack(Xs)
def _initialize(self, X, resp): """Initialization of the mixture parameters. Parameters ---------- X : array-like of shape (n_samples, n_features) resp : array-like of shape (n_samples, n_components) """ (nk, xk, sk) = _estimate_gaussian_parameters(X, resp, self.reg_covar, self.covariance_type) if self.weight_concentration_prior_type == 'dirichlet_process': self.weight_concentration_ = (1.0 + nk, self.weight_concentration_prior_ + np.hstack((np.cumsum(nk[::-1])[-2::-1], 0))) else: self.weight_concentration_ = self.weight_concentration_prior_ + nk self.mean_precision_ = self.mean_precision_prior_ + nk self.means_ = (self.mean_precision_prior_ * self.mean_prior_ + nk[:, np.newaxis] * xk) / self.mean_precision_[:, np.newaxis] {'full': self._estimate_wishart_full, 'tied': self._estimate_wishart_tied, 'diag': self._estimate_wishart_diag, 'spherical': self._estimate_wishart_spherical}[self.covariance_type](nk, xk, sk) self.precisions_cholesky_ = _compute_precision_cholesky(self.covariances_, self.covariance_type) </DeepExtract>
def _initialize(self, X, resp): """Initialization of the mixture parameters. Parameters ---------- X : array-like of shape (n_samples, n_features) resp : array-like of shape (n_samples, n_components) """ (nk, xk, sk) = _estimate_gaussian_parameters(X, resp, self.reg_covar, self.covariance_type) <DeepExtract> if self.weight_concentration_prior_type == 'dirichlet_process': self.weight_concentration_ = (1.0 + nk, self.weight_concentration_prior_ + np.hstack((np.cumsum(nk[::-1])[-2::-1], 0))) else: self.weight_concentration_ = self.weight_concentration_prior_ + nk </DeepExtract> <DeepExtract> self.mean_precision_ = self.mean_precision_prior_ + nk self.means_ = (self.mean_precision_prior_ * self.mean_prior_ + nk[:, np.newaxis] * xk) / self.mean_precision_[:, np.newaxis] </DeepExtract> <DeepExtract> {'full': self._estimate_wishart_full, 'tied': self._estimate_wishart_tied, 'diag': self._estimate_wishart_diag, 'spherical': self._estimate_wishart_spherical}[self.covariance_type](nk, xk, sk) self.precisions_cholesky_ = _compute_precision_cholesky(self.covariances_, self.covariance_type) </DeepExtract>
@pytest.mark.filterwarnings('ignore:The max_iter was reached') def test_multiclass_classifier_class_weight(): """tests multiclass with classweights for each class""" alpha = 0.1 n_samples = 20 tol = 1e-05 max_iter = 50 class_weight = {0: 0.45, 1: 0.55, 2: 0.75} fit_intercept = True (X, y) = make_blobs(n_samples=n_samples, centers=3, random_state=0, cluster_std=0.1) if True: step_size = 4.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + 4.0 * alpha) else: step_size = 1.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + alpha) classes = np.unique(y) clf1 = LogisticRegression(solver='sag', C=1.0 / alpha / n_samples, max_iter=max_iter, tol=tol, random_state=77, fit_intercept=fit_intercept, multi_class='ovr', class_weight=class_weight) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) le = LabelEncoder() class_weight_ = compute_class_weight(class_weight, classes=np.unique(y), y=y) sample_weight = class_weight_[le.fit_transform(y)] coef1 = [] intercept1 = [] coef2 = [] intercept2 = [] for cl in classes: y_encoded = np.ones(n_samples) y_encoded[y != cl] = -1 if step_size * alpha == 1.0: raise ZeroDivisionError('Sparse sag does not handle the case step_size * alpha == 1') (n_samples, n_features) = (X.shape[0], X.shape[1]) weights = np.zeros(n_features) sum_gradient = np.zeros(n_features) last_updated = np.zeros(n_features, dtype=int) gradient_memory = np.zeros(n_samples) rng = check_random_state(random_state) intercept = 0.0 intercept_sum_gradient = 0.0 wscale = 1.0 decay = 1.0 seen = set() c_sum = np.zeros(max_iter * n_samples) if sparse: decay = 0.01 counter = 0 for epoch in range(max_iter): for k in range(n_samples): idx = int(rng.rand(1) * n_samples) entry = X[idx] seen.add(idx) if counter >= 1: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter p = wscale * np.dot(entry, weights) + intercept gradient = log_dloss(p, y_encoded[idx]) if sample_weight is not None: gradient *= sample_weight[idx] update = entry * gradient gradient_correction = update - gradient_memory[idx] * entry sum_gradient += gradient_correction if saga: for j in range(n_features): weights[j] -= gradient_correction[j] * step_size * (1 - 1.0 / len(seen)) / wscale if fit_intercept: gradient_correction = gradient - gradient_memory[idx] intercept_sum_gradient += gradient_correction gradient_correction *= step_size * (1.0 - 1.0 / len(seen)) if saga: intercept -= step_size * intercept_sum_gradient / len(seen) * decay + gradient_correction else: intercept -= step_size * intercept_sum_gradient / len(seen) * decay gradient_memory[idx] = gradient wscale *= 1.0 - alpha * step_size if counter == 0: c_sum[0] = step_size / (wscale * len(seen)) else: c_sum[counter] = c_sum[counter - 1] + step_size / (wscale * len(seen)) if counter >= 1 and wscale < 1e-09: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter] * sum_gradient[j] else: weights[j] -= (c_sum[counter] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter + 1 c_sum[counter] = 0 weights *= wscale wscale = 1.0 counter += 1 for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] weights *= wscale (spweights1, spintercept1) = (weights, intercept) if step_size * alpha == 1.0: raise ZeroDivisionError('Sparse sag does not handle the case step_size * alpha == 1') (n_samples, n_features) = (X.shape[0], X.shape[1]) weights = np.zeros(n_features) sum_gradient = np.zeros(n_features) last_updated = np.zeros(n_features, dtype=int) gradient_memory = np.zeros(n_samples) rng = check_random_state(random_state) intercept = 0.0 intercept_sum_gradient = 0.0 wscale = 1.0 decay = 1.0 seen = set() c_sum = np.zeros(max_iter * n_samples) if True: decay = 0.01 counter = 0 for epoch in range(max_iter): for k in range(n_samples): idx = int(rng.rand(1) * n_samples) entry = X[idx] seen.add(idx) if counter >= 1: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter p = wscale * np.dot(entry, weights) + intercept gradient = log_dloss(p, y_encoded[idx]) if sample_weight is not None: gradient *= sample_weight[idx] update = entry * gradient gradient_correction = update - gradient_memory[idx] * entry sum_gradient += gradient_correction if saga: for j in range(n_features): weights[j] -= gradient_correction[j] * step_size * (1 - 1.0 / len(seen)) / wscale if fit_intercept: gradient_correction = gradient - gradient_memory[idx] intercept_sum_gradient += gradient_correction gradient_correction *= step_size * (1.0 - 1.0 / len(seen)) if saga: intercept -= step_size * intercept_sum_gradient / len(seen) * decay + gradient_correction else: intercept -= step_size * intercept_sum_gradient / len(seen) * decay gradient_memory[idx] = gradient wscale *= 1.0 - alpha * step_size if counter == 0: c_sum[0] = step_size / (wscale * len(seen)) else: c_sum[counter] = c_sum[counter - 1] + step_size / (wscale * len(seen)) if counter >= 1 and wscale < 1e-09: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter] * sum_gradient[j] else: weights[j] -= (c_sum[counter] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter + 1 c_sum[counter] = 0 weights *= wscale wscale = 1.0 counter += 1 for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] weights *= wscale (spweights2, spintercept2) = (weights, intercept) coef1.append(spweights1) intercept1.append(spintercept1) coef2.append(spweights2) intercept2.append(spintercept2) coef1 = np.vstack(coef1) intercept1 = np.array(intercept1) coef2 = np.vstack(coef2) intercept2 = np.array(intercept2) for (i, cl) in enumerate(classes): assert_array_almost_equal(clf1.coef_[i].ravel(), coef1[i].ravel(), decimal=2) assert_almost_equal(clf1.intercept_[i], intercept1[i], decimal=1) assert_array_almost_equal(clf2.coef_[i].ravel(), coef2[i].ravel(), decimal=2) assert_almost_equal(clf2.intercept_[i], intercept2[i], decimal=1)
@pytest.mark.filterwarnings('ignore:The max_iter was reached') def test_multiclass_classifier_class_weight(): """tests multiclass with classweights for each class""" alpha = 0.1 n_samples = 20 tol = 1e-05 max_iter = 50 class_weight = {0: 0.45, 1: 0.55, 2: 0.75} fit_intercept = True (X, y) = make_blobs(n_samples=n_samples, centers=3, random_state=0, cluster_std=0.1) <DeepExtract> if True: step_size = 4.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + 4.0 * alpha) else: step_size = 1.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + alpha) </DeepExtract> classes = np.unique(y) clf1 = LogisticRegression(solver='sag', C=1.0 / alpha / n_samples, max_iter=max_iter, tol=tol, random_state=77, fit_intercept=fit_intercept, multi_class='ovr', class_weight=class_weight) clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) le = LabelEncoder() class_weight_ = compute_class_weight(class_weight, classes=np.unique(y), y=y) sample_weight = class_weight_[le.fit_transform(y)] coef1 = [] intercept1 = [] coef2 = [] intercept2 = [] for cl in classes: y_encoded = np.ones(n_samples) y_encoded[y != cl] = -1 <DeepExtract> if step_size * alpha == 1.0: raise ZeroDivisionError('Sparse sag does not handle the case step_size * alpha == 1') (n_samples, n_features) = (X.shape[0], X.shape[1]) weights = np.zeros(n_features) sum_gradient = np.zeros(n_features) last_updated = np.zeros(n_features, dtype=int) gradient_memory = np.zeros(n_samples) rng = check_random_state(random_state) intercept = 0.0 intercept_sum_gradient = 0.0 wscale = 1.0 decay = 1.0 seen = set() c_sum = np.zeros(max_iter * n_samples) if sparse: decay = 0.01 counter = 0 for epoch in range(max_iter): for k in range(n_samples): idx = int(rng.rand(1) * n_samples) entry = X[idx] seen.add(idx) if counter >= 1: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter p = wscale * np.dot(entry, weights) + intercept gradient = log_dloss(p, y_encoded[idx]) if sample_weight is not None: gradient *= sample_weight[idx] update = entry * gradient gradient_correction = update - gradient_memory[idx] * entry sum_gradient += gradient_correction if saga: for j in range(n_features): weights[j] -= gradient_correction[j] * step_size * (1 - 1.0 / len(seen)) / wscale if fit_intercept: gradient_correction = gradient - gradient_memory[idx] intercept_sum_gradient += gradient_correction gradient_correction *= step_size * (1.0 - 1.0 / len(seen)) if saga: intercept -= step_size * intercept_sum_gradient / len(seen) * decay + gradient_correction else: intercept -= step_size * intercept_sum_gradient / len(seen) * decay gradient_memory[idx] = gradient wscale *= 1.0 - alpha * step_size if counter == 0: c_sum[0] = step_size / (wscale * len(seen)) else: c_sum[counter] = c_sum[counter - 1] + step_size / (wscale * len(seen)) if counter >= 1 and wscale < 1e-09: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter] * sum_gradient[j] else: weights[j] -= (c_sum[counter] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter + 1 c_sum[counter] = 0 weights *= wscale wscale = 1.0 counter += 1 for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] weights *= wscale (spweights1, spintercept1) = (weights, intercept) </DeepExtract> <DeepExtract> if step_size * alpha == 1.0: raise ZeroDivisionError('Sparse sag does not handle the case step_size * alpha == 1') (n_samples, n_features) = (X.shape[0], X.shape[1]) weights = np.zeros(n_features) sum_gradient = np.zeros(n_features) last_updated = np.zeros(n_features, dtype=int) gradient_memory = np.zeros(n_samples) rng = check_random_state(random_state) intercept = 0.0 intercept_sum_gradient = 0.0 wscale = 1.0 decay = 1.0 seen = set() c_sum = np.zeros(max_iter * n_samples) if True: decay = 0.01 counter = 0 for epoch in range(max_iter): for k in range(n_samples): idx = int(rng.rand(1) * n_samples) entry = X[idx] seen.add(idx) if counter >= 1: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter p = wscale * np.dot(entry, weights) + intercept gradient = log_dloss(p, y_encoded[idx]) if sample_weight is not None: gradient *= sample_weight[idx] update = entry * gradient gradient_correction = update - gradient_memory[idx] * entry sum_gradient += gradient_correction if saga: for j in range(n_features): weights[j] -= gradient_correction[j] * step_size * (1 - 1.0 / len(seen)) / wscale if fit_intercept: gradient_correction = gradient - gradient_memory[idx] intercept_sum_gradient += gradient_correction gradient_correction *= step_size * (1.0 - 1.0 / len(seen)) if saga: intercept -= step_size * intercept_sum_gradient / len(seen) * decay + gradient_correction else: intercept -= step_size * intercept_sum_gradient / len(seen) * decay gradient_memory[idx] = gradient wscale *= 1.0 - alpha * step_size if counter == 0: c_sum[0] = step_size / (wscale * len(seen)) else: c_sum[counter] = c_sum[counter - 1] + step_size / (wscale * len(seen)) if counter >= 1 and wscale < 1e-09: for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter] * sum_gradient[j] else: weights[j] -= (c_sum[counter] - c_sum[last_updated[j] - 1]) * sum_gradient[j] last_updated[j] = counter + 1 c_sum[counter] = 0 weights *= wscale wscale = 1.0 counter += 1 for j in range(n_features): if last_updated[j] == 0: weights[j] -= c_sum[counter - 1] * sum_gradient[j] else: weights[j] -= (c_sum[counter - 1] - c_sum[last_updated[j] - 1]) * sum_gradient[j] weights *= wscale (spweights2, spintercept2) = (weights, intercept) </DeepExtract> coef1.append(spweights1) intercept1.append(spintercept1) coef2.append(spweights2) intercept2.append(spintercept2) coef1 = np.vstack(coef1) intercept1 = np.array(intercept1) coef2 = np.vstack(coef2) intercept2 = np.array(intercept2) for (i, cl) in enumerate(classes): assert_array_almost_equal(clf1.coef_[i].ravel(), coef1[i].ravel(), decimal=2) assert_almost_equal(clf1.intercept_[i], intercept1[i], decimal=1) assert_array_almost_equal(clf2.coef_[i].ravel(), coef2[i].ravel(), decimal=2) assert_almost_equal(clf2.intercept_[i], intercept2[i], decimal=1)
@ignore_warnings(category=FutureWarning) def check_estimators_fit_returns_self(name, estimator_orig, readonly_memmap=False): """Check if self is returned when calling fit.""" (X, y) = make_blobs(random_state=0, n_samples=21) if '1darray' in _safe_tags(estimator_orig, key='X_types'): X = X[:, 0] if _safe_tags(estimator_orig, key='requires_positive_X'): X = X - X.min() if 'categorical' in _safe_tags(estimator_orig, key='X_types'): X = (X - X.min()).astype(np.int32) if estimator_orig.__class__.__name__ == 'SkewedChi2Sampler': X = X - X.min() if _is_pairwise_metric(estimator_orig): X = pairwise_distances(X, metric='euclidean') elif _safe_tags(estimator_orig, key='pairwise'): X = kernel(X, X) X = X estimator = clone(estimator_orig) if _safe_tags(estimator, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(estimator, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(estimator, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y if readonly_memmap: (X, y) = create_memmap_backed_data([X, y]) set_random_state(estimator) assert estimator.fit(X, y) is estimator
@ignore_warnings(category=FutureWarning) def check_estimators_fit_returns_self(name, estimator_orig, readonly_memmap=False): """Check if self is returned when calling fit.""" (X, y) = make_blobs(random_state=0, n_samples=21) <DeepExtract> if '1darray' in _safe_tags(estimator_orig, key='X_types'): X = X[:, 0] if _safe_tags(estimator_orig, key='requires_positive_X'): X = X - X.min() if 'categorical' in _safe_tags(estimator_orig, key='X_types'): X = (X - X.min()).astype(np.int32) if estimator_orig.__class__.__name__ == 'SkewedChi2Sampler': X = X - X.min() if _is_pairwise_metric(estimator_orig): X = pairwise_distances(X, metric='euclidean') elif _safe_tags(estimator_orig, key='pairwise'): X = kernel(X, X) X = X </DeepExtract> estimator = clone(estimator_orig) <DeepExtract> if _safe_tags(estimator, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(estimator, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(estimator, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y </DeepExtract> if readonly_memmap: (X, y) = create_memmap_backed_data([X, y]) set_random_state(estimator) assert estimator.fit(X, y) is estimator
def transform(self, X): """ Transform X to ordinal codes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to encode. Returns ------- X_out : ndarray of shape (n_samples, n_features) Transformed input. """ self._check_feature_names(X, reset=False) self._check_n_features(X, reset=False) (X_list, n_samples, n_features) = self._check_X(X, force_all_finite='allow-nan') X_int = np.zeros((n_samples, n_features), dtype=int) X_mask = np.ones((n_samples, n_features), dtype=bool) columns_with_unknown = [] for i in range(n_features): Xi = X_list[i] (diff, valid_mask) = _check_unknown(Xi, self.categories_[i], return_mask=True) if not np.all(valid_mask): if self.handle_unknown == 'error': msg = 'Found unknown categories {0} in column {1} during transform'.format(diff, i) raise ValueError(msg) else: if warn_on_unknown: columns_with_unknown.append(i) X_mask[:, i] = valid_mask if self.categories_[i].dtype.kind in ('U', 'S') and self.categories_[i].itemsize > Xi.itemsize: Xi = Xi.astype(self.categories_[i].dtype) elif self.categories_[i].dtype.kind == 'O' and Xi.dtype.kind == 'U': Xi = Xi.astype('O') else: Xi = Xi.copy() Xi[~valid_mask] = self.categories_[i][0] X_int[:, i] = _encode(Xi, uniques=self.categories_[i], check_unknown=False) if columns_with_unknown: warnings.warn(f'Found unknown categories in columns {columns_with_unknown} during transform. These unknown categories will be encoded as all zeros', UserWarning) self._map_infrequent_categories(X_int, X_mask, self._missing_indices) (X_int, X_mask) = (X_int, X_mask) X_trans = X_int.astype(self.dtype, copy=False) for (cat_idx, missing_idx) in self._missing_indices.items(): X_missing_mask = X_int[:, cat_idx] == missing_idx X_trans[X_missing_mask, cat_idx] = self.encoded_missing_value if self.handle_unknown == 'use_encoded_value': X_trans[~X_mask] = self.unknown_value return X_trans
def transform(self, X): """ Transform X to ordinal codes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to encode. Returns ------- X_out : ndarray of shape (n_samples, n_features) Transformed input. """ <DeepExtract> self._check_feature_names(X, reset=False) self._check_n_features(X, reset=False) (X_list, n_samples, n_features) = self._check_X(X, force_all_finite='allow-nan') X_int = np.zeros((n_samples, n_features), dtype=int) X_mask = np.ones((n_samples, n_features), dtype=bool) columns_with_unknown = [] for i in range(n_features): Xi = X_list[i] (diff, valid_mask) = _check_unknown(Xi, self.categories_[i], return_mask=True) if not np.all(valid_mask): if self.handle_unknown == 'error': msg = 'Found unknown categories {0} in column {1} during transform'.format(diff, i) raise ValueError(msg) else: if warn_on_unknown: columns_with_unknown.append(i) X_mask[:, i] = valid_mask if self.categories_[i].dtype.kind in ('U', 'S') and self.categories_[i].itemsize > Xi.itemsize: Xi = Xi.astype(self.categories_[i].dtype) elif self.categories_[i].dtype.kind == 'O' and Xi.dtype.kind == 'U': Xi = Xi.astype('O') else: Xi = Xi.copy() Xi[~valid_mask] = self.categories_[i][0] X_int[:, i] = _encode(Xi, uniques=self.categories_[i], check_unknown=False) if columns_with_unknown: warnings.warn(f'Found unknown categories in columns {columns_with_unknown} during transform. These unknown categories will be encoded as all zeros', UserWarning) self._map_infrequent_categories(X_int, X_mask, self._missing_indices) (X_int, X_mask) = (X_int, X_mask) </DeepExtract> X_trans = X_int.astype(self.dtype, copy=False) for (cat_idx, missing_idx) in self._missing_indices.items(): X_missing_mask = X_int[:, cat_idx] == missing_idx X_trans[X_missing_mask, cat_idx] = self.encoded_missing_value if self.handle_unknown == 'use_encoded_value': X_trans[~X_mask] = self.unknown_value return X_trans
def _check_precomputed(X): """Check precomputed distance matrix. If the precomputed distance matrix is sparse, it checks that the non-zero entries are sorted by distances. If not, the matrix is copied and sorted. Parameters ---------- X : {sparse matrix, array-like}, (n_samples, n_samples) Distance matrix to other samples. X may be a sparse matrix, in which case only non-zero elements may be considered neighbors. Returns ------- X : {sparse matrix, array-like}, (n_samples, n_samples) Distance matrix to other samples. X may be a sparse matrix, in which case only non-zero elements may be considered neighbors. """ if not issparse(X): X = check_array(X) check_non_negative(X, whom='precomputed distance matrix.') return X else: graph = X if graph.format not in ('csr', 'csc', 'coo', 'lil'): raise TypeError('Sparse matrix in {!r} format is not supported due to its handling of explicit zeros'.format(graph.format)) copied = graph.format != 'csr' graph = check_array(graph, accept_sparse='csr') check_non_negative(graph, whom='precomputed distance matrix.') if not issparse(graph): raise TypeError(f'Input graph must be a sparse matrix, got {graph!r} instead.') if graph.format == 'csr' and _is_sorted_by_data(graph): graph = graph if True: warnings.warn('Precomputed sparse input was not sorted by row values. Use the function sklearn.neighbors.sort_graph_by_row_values to sort the input by row values, with warn_when_not_sorted=False to remove this warning.', EfficiencyWarning) if graph.format not in ('csr', 'csc', 'coo', 'lil'): raise TypeError(f'Sparse matrix in {graph.format!r} format is not supported due to its handling of explicit zeros') elif graph.format != 'csr': if not not copied: raise ValueError('The input graph is not in CSR format. Use copy=True to allow the conversion to CSR format.') graph = graph.asformat('csr') elif not copied: graph = graph.copy() row_nnz = np.diff(graph.indptr) if row_nnz.max() == row_nnz.min(): n_samples = graph.shape[0] distances = graph.data.reshape(n_samples, -1) order = np.argsort(distances, kind='mergesort') order += np.arange(n_samples)[:, None] * row_nnz[0] order = order.ravel() graph.data = graph.data[order] graph.indices = graph.indices[order] else: for (start, stop) in zip(graph.indptr, graph.indptr[1:]): order = np.argsort(graph.data[start:stop], kind='mergesort') graph.data[start:stop] = graph.data[start:stop][order] graph.indices[start:stop] = graph.indices[start:stop][order] graph = graph return graph
def _check_precomputed(X): """Check precomputed distance matrix. If the precomputed distance matrix is sparse, it checks that the non-zero entries are sorted by distances. If not, the matrix is copied and sorted. Parameters ---------- X : {sparse matrix, array-like}, (n_samples, n_samples) Distance matrix to other samples. X may be a sparse matrix, in which case only non-zero elements may be considered neighbors. Returns ------- X : {sparse matrix, array-like}, (n_samples, n_samples) Distance matrix to other samples. X may be a sparse matrix, in which case only non-zero elements may be considered neighbors. """ if not issparse(X): X = check_array(X) check_non_negative(X, whom='precomputed distance matrix.') return X else: graph = X if graph.format not in ('csr', 'csc', 'coo', 'lil'): raise TypeError('Sparse matrix in {!r} format is not supported due to its handling of explicit zeros'.format(graph.format)) copied = graph.format != 'csr' graph = check_array(graph, accept_sparse='csr') check_non_negative(graph, whom='precomputed distance matrix.') <DeepExtract> if not issparse(graph): raise TypeError(f'Input graph must be a sparse matrix, got {graph!r} instead.') if graph.format == 'csr' and _is_sorted_by_data(graph): graph = graph if True: warnings.warn('Precomputed sparse input was not sorted by row values. Use the function sklearn.neighbors.sort_graph_by_row_values to sort the input by row values, with warn_when_not_sorted=False to remove this warning.', EfficiencyWarning) if graph.format not in ('csr', 'csc', 'coo', 'lil'): raise TypeError(f'Sparse matrix in {graph.format!r} format is not supported due to its handling of explicit zeros') elif graph.format != 'csr': if not not copied: raise ValueError('The input graph is not in CSR format. Use copy=True to allow the conversion to CSR format.') graph = graph.asformat('csr') elif not copied: graph = graph.copy() row_nnz = np.diff(graph.indptr) if row_nnz.max() == row_nnz.min(): n_samples = graph.shape[0] distances = graph.data.reshape(n_samples, -1) order = np.argsort(distances, kind='mergesort') order += np.arange(n_samples)[:, None] * row_nnz[0] order = order.ravel() graph.data = graph.data[order] graph.indices = graph.indices[order] else: for (start, stop) in zip(graph.indptr, graph.indptr[1:]): order = np.argsort(graph.data[start:stop], kind='mergesort') graph.data[start:stop] = graph.data[start:stop][order] graph.indices[start:stop] = graph.indices[start:stop][order] graph = graph </DeepExtract> return graph
def plot_species_distribution(species=('bradypus_variegatus_0', 'microryzomys_minutus_0')): """ Plot the species distribution. """ if len(species) > 2: print('Note: when more than two species are provided, only the first two will be used') t0 = time() data = fetch_species_distributions() xmin = data.x_left_lower_corner + data.grid_size xmax = xmin + data.Nx * data.grid_size ymin = data.y_left_lower_corner + data.grid_size ymax = ymin + data.Ny * data.grid_size xgrid = np.arange(xmin, xmax, data.grid_size) ygrid = np.arange(ymin, ymax, data.grid_size) (xgrid, ygrid) = (xgrid, ygrid) (X, Y) = np.meshgrid(xgrid, ygrid[::-1]) bunch = Bunch(name=' '.join(species[0].split('_')[:2])) species[0] = species[0].encode('ascii') points = dict(test=data.test, train=data.train) for (label, pts) in points.items(): pts = pts[pts['species'] == species[0]] bunch['pts_%s' % label] = pts ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = data.coverages[:, -iy, ix].T BV_bunch = bunch bunch = Bunch(name=' '.join(species[1].split('_')[:2])) species[1] = species[1].encode('ascii') points = dict(test=data.test, train=data.train) for (label, pts) in points.items(): pts = pts[pts['species'] == species[1]] bunch['pts_%s' % label] = pts ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = data.coverages[:, -iy, ix].T MM_bunch = bunch np.random.seed(13) background_points = np.c_[np.random.randint(low=0, high=data.Ny, size=10000), np.random.randint(low=0, high=data.Nx, size=10000)].T land_reference = data.coverages[6] for (i, species) in enumerate([BV_bunch, MM_bunch]): print('_' * 80) print("Modeling distribution of species '%s'" % species.name) mean = species.cov_train.mean(axis=0) std = species.cov_train.std(axis=0) train_cover_std = (species.cov_train - mean) / std print(' - fit OneClassSVM ... ', end='') clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.5) clf.fit(train_cover_std) print('done.') plt.subplot(1, 2, i + 1) if basemap: print(' - plot coastlines using basemap') m = Basemap(projection='cyl', llcrnrlat=Y.min(), urcrnrlat=Y.max(), llcrnrlon=X.min(), urcrnrlon=X.max(), resolution='c') m.drawcoastlines() m.drawcountries() else: print(' - plot coastlines from coverage') plt.contour(X, Y, land_reference, levels=[-9998], colors='k', linestyles='solid') plt.xticks([]) plt.yticks([]) print(' - predict species distribution') Z = np.ones((data.Ny, data.Nx), dtype=np.float64) idx = np.where(land_reference > -9999) coverages_land = data.coverages[:, idx[0], idx[1]].T pred = clf.decision_function((coverages_land - mean) / std) Z *= pred.min() Z[idx[0], idx[1]] = pred levels = np.linspace(Z.min(), Z.max(), 25) Z[land_reference == -9999] = -9999 plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) plt.colorbar(format='%.2f') plt.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], s=2 ** 2, c='black', marker='^', label='train') plt.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], s=2 ** 2, c='black', marker='x', label='test') plt.legend() plt.title(species.name) plt.axis('equal') pred_background = Z[background_points[0], background_points[1]] pred_test = clf.decision_function((species.cov_test - mean) / std) scores = np.r_[pred_test, pred_background] y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)] (fpr, tpr, thresholds) = metrics.roc_curve(y, scores) roc_auc = metrics.auc(fpr, tpr) plt.text(-35, -70, 'AUC: %.3f' % roc_auc, ha='right') print('\n Area under the ROC curve : %f' % roc_auc) print('\ntime elapsed: %.2fs' % (time() - t0))
def plot_species_distribution(species=('bradypus_variegatus_0', 'microryzomys_minutus_0')): """ Plot the species distribution. """ if len(species) > 2: print('Note: when more than two species are provided, only the first two will be used') t0 = time() data = fetch_species_distributions() <DeepExtract> xmin = data.x_left_lower_corner + data.grid_size xmax = xmin + data.Nx * data.grid_size ymin = data.y_left_lower_corner + data.grid_size ymax = ymin + data.Ny * data.grid_size xgrid = np.arange(xmin, xmax, data.grid_size) ygrid = np.arange(ymin, ymax, data.grid_size) (xgrid, ygrid) = (xgrid, ygrid) </DeepExtract> (X, Y) = np.meshgrid(xgrid, ygrid[::-1]) <DeepExtract> bunch = Bunch(name=' '.join(species[0].split('_')[:2])) species[0] = species[0].encode('ascii') points = dict(test=data.test, train=data.train) for (label, pts) in points.items(): pts = pts[pts['species'] == species[0]] bunch['pts_%s' % label] = pts ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = data.coverages[:, -iy, ix].T BV_bunch = bunch </DeepExtract> <DeepExtract> bunch = Bunch(name=' '.join(species[1].split('_')[:2])) species[1] = species[1].encode('ascii') points = dict(test=data.test, train=data.train) for (label, pts) in points.items(): pts = pts[pts['species'] == species[1]] bunch['pts_%s' % label] = pts ix = np.searchsorted(xgrid, pts['dd long']) iy = np.searchsorted(ygrid, pts['dd lat']) bunch['cov_%s' % label] = data.coverages[:, -iy, ix].T MM_bunch = bunch </DeepExtract> np.random.seed(13) background_points = np.c_[np.random.randint(low=0, high=data.Ny, size=10000), np.random.randint(low=0, high=data.Nx, size=10000)].T land_reference = data.coverages[6] for (i, species) in enumerate([BV_bunch, MM_bunch]): print('_' * 80) print("Modeling distribution of species '%s'" % species.name) mean = species.cov_train.mean(axis=0) std = species.cov_train.std(axis=0) train_cover_std = (species.cov_train - mean) / std print(' - fit OneClassSVM ... ', end='') clf = svm.OneClassSVM(nu=0.1, kernel='rbf', gamma=0.5) clf.fit(train_cover_std) print('done.') plt.subplot(1, 2, i + 1) if basemap: print(' - plot coastlines using basemap') m = Basemap(projection='cyl', llcrnrlat=Y.min(), urcrnrlat=Y.max(), llcrnrlon=X.min(), urcrnrlon=X.max(), resolution='c') m.drawcoastlines() m.drawcountries() else: print(' - plot coastlines from coverage') plt.contour(X, Y, land_reference, levels=[-9998], colors='k', linestyles='solid') plt.xticks([]) plt.yticks([]) print(' - predict species distribution') Z = np.ones((data.Ny, data.Nx), dtype=np.float64) idx = np.where(land_reference > -9999) coverages_land = data.coverages[:, idx[0], idx[1]].T pred = clf.decision_function((coverages_land - mean) / std) Z *= pred.min() Z[idx[0], idx[1]] = pred levels = np.linspace(Z.min(), Z.max(), 25) Z[land_reference == -9999] = -9999 plt.contourf(X, Y, Z, levels=levels, cmap=plt.cm.Reds) plt.colorbar(format='%.2f') plt.scatter(species.pts_train['dd long'], species.pts_train['dd lat'], s=2 ** 2, c='black', marker='^', label='train') plt.scatter(species.pts_test['dd long'], species.pts_test['dd lat'], s=2 ** 2, c='black', marker='x', label='test') plt.legend() plt.title(species.name) plt.axis('equal') pred_background = Z[background_points[0], background_points[1]] pred_test = clf.decision_function((species.cov_test - mean) / std) scores = np.r_[pred_test, pred_background] y = np.r_[np.ones(pred_test.shape), np.zeros(pred_background.shape)] (fpr, tpr, thresholds) = metrics.roc_curve(y, scores) roc_auc = metrics.auc(fpr, tpr) plt.text(-35, -70, 'AUC: %.3f' % roc_auc, ha='right') print('\n Area under the ROC curve : %f' % roc_auc) print('\ntime elapsed: %.2fs' % (time() - t0))
def _infer_dimension(spectrum, n_samples): """Infers the dimension of a dataset with a given spectrum. The returned value will be in [1, n_features - 1]. """ ll = np.empty_like(spectrum) ll[0] = -np.inf for rank in range(1, spectrum.shape[0]): n_features = spectrum.shape[0] if not 1 <= rank < n_features: raise ValueError('the tested rank should be in [1, n_features - 1]') eps = 1e-15 if spectrum[rank - 1] < eps: ll[rank] = -np.inf pu = -rank * log(2.0) for i in range(1, rank + 1): pu += gammaln((n_features - i + 1) / 2.0) - log(np.pi) * (n_features - i + 1) / 2.0 pl = np.sum(np.log(spectrum[:rank])) pl = -pl * n_samples / 2.0 v = max(eps, np.sum(spectrum[rank:]) / (n_features - rank)) pv = -np.log(v) * n_samples * (n_features - rank) / 2.0 m = n_features * rank - rank * (rank + 1.0) / 2.0 pp = log(2.0 * np.pi) * (m + rank) / 2.0 pa = 0.0 spectrum_ = spectrum.copy() spectrum_[rank:n_features] = v for i in range(rank): for j in range(i + 1, len(spectrum)): pa += log((spectrum[i] - spectrum[j]) * (1.0 / spectrum_[j] - 1.0 / spectrum_[i])) + log(n_samples) ll = pu + pl + pv + pp - pa / 2.0 - rank * log(n_samples) / 2.0 ll[rank] = ll return ll.argmax()
def _infer_dimension(spectrum, n_samples): """Infers the dimension of a dataset with a given spectrum. The returned value will be in [1, n_features - 1]. """ ll = np.empty_like(spectrum) ll[0] = -np.inf for rank in range(1, spectrum.shape[0]): <DeepExtract> n_features = spectrum.shape[0] if not 1 <= rank < n_features: raise ValueError('the tested rank should be in [1, n_features - 1]') eps = 1e-15 if spectrum[rank - 1] < eps: ll[rank] = -np.inf pu = -rank * log(2.0) for i in range(1, rank + 1): pu += gammaln((n_features - i + 1) / 2.0) - log(np.pi) * (n_features - i + 1) / 2.0 pl = np.sum(np.log(spectrum[:rank])) pl = -pl * n_samples / 2.0 v = max(eps, np.sum(spectrum[rank:]) / (n_features - rank)) pv = -np.log(v) * n_samples * (n_features - rank) / 2.0 m = n_features * rank - rank * (rank + 1.0) / 2.0 pp = log(2.0 * np.pi) * (m + rank) / 2.0 pa = 0.0 spectrum_ = spectrum.copy() spectrum_[rank:n_features] = v for i in range(rank): for j in range(i + 1, len(spectrum)): pa += log((spectrum[i] - spectrum[j]) * (1.0 / spectrum_[j] - 1.0 / spectrum_[i])) + log(n_samples) ll = pu + pl + pv + pp - pa / 2.0 - rank * log(n_samples) / 2.0 ll[rank] = ll </DeepExtract> return ll.argmax()
def fit(self, X, y, sample_weight=None): """Fit Ridge regression model. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) Training data. y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values. sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. Returns ------- self : object Fitted estimator. """ self._validate_params() if sparse.issparse(X) and self.solver in ['auto', 'sag', 'saga']: _accept_sparse = 'csr' else: _accept_sparse = ['csr', 'csc', 'coo'] (X, y) = self._validate_data(X, y, accept_sparse=_accept_sparse, dtype=[np.float64, np.float32], multi_output=True, y_numeric=True) return super().fit(X, y, sample_weight=sample_weight)
def fit(self, X, y, sample_weight=None): """Fit Ridge regression model. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) Training data. y : ndarray of shape (n_samples,) or (n_samples, n_targets) Target values. sample_weight : float or ndarray of shape (n_samples,), default=None Individual weights for each sample. If given a float, every sample will have the same weight. Returns ------- self : object Fitted estimator. """ self._validate_params() <DeepExtract> if sparse.issparse(X) and self.solver in ['auto', 'sag', 'saga']: _accept_sparse = 'csr' else: _accept_sparse = ['csr', 'csc', 'coo'] </DeepExtract> (X, y) = self._validate_data(X, y, accept_sparse=_accept_sparse, dtype=[np.float64, np.float32], multi_output=True, y_numeric=True) return super().fit(X, y, sample_weight=sample_weight)
def __init__(self, ws=' \t\r\n', min=1, max=0, exact=0): super(White, self).__init__() self.matchWhite = ws self.skipWhitespace = True self.whiteChars = ''.join((c for c in self.whiteChars if c not in self.matchWhite)) self.copyDefaultWhiteChars = False return self self.name = ''.join((White.whiteStrs[c] for c in self.matchWhite)) self.mayReturnEmpty = True self.errmsg = 'Expected ' + self.name self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = _MAX_INT if exact > 0: self.maxLen = exact self.minLen = exact
def __init__(self, ws=' \t\r\n', min=1, max=0, exact=0): super(White, self).__init__() self.matchWhite = ws <DeepExtract> self.skipWhitespace = True self.whiteChars = ''.join((c for c in self.whiteChars if c not in self.matchWhite)) self.copyDefaultWhiteChars = False return self </DeepExtract> self.name = ''.join((White.whiteStrs[c] for c in self.matchWhite)) self.mayReturnEmpty = True self.errmsg = 'Expected ' + self.name self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = _MAX_INT if exact > 0: self.maxLen = exact self.minLen = exact
def test_score_scale_invariance(): if dataset is None: dataset = datasets.load_iris() X = dataset.data y = dataset.target if True: (X, y) = (X[y < 2], y[y < 2]) (n_samples, n_features) = X.shape p = np.arange(n_samples) rng = check_random_state(37) rng.shuffle(p) (X, y) = (X[p], y[p]) half = int(n_samples / 2) rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)] clf = svm.SVC(kernel='linear', probability=True, random_state=0) y_score = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if True: y_score = y_score[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] (y_true, _, y_score) = (y_true, y_pred, y_score) roc_auc = roc_auc_score(y_true, y_score) roc_auc_scaled_up = roc_auc_score(y_true, 100 * y_score) roc_auc_scaled_down = roc_auc_score(y_true, 1e-06 * y_score) roc_auc_shifted = roc_auc_score(y_true, y_score - 10) assert roc_auc == roc_auc_scaled_up assert roc_auc == roc_auc_scaled_down assert roc_auc == roc_auc_shifted pr_auc = average_precision_score(y_true, y_score) pr_auc_scaled_up = average_precision_score(y_true, 100 * y_score) pr_auc_scaled_down = average_precision_score(y_true, 1e-06 * y_score) pr_auc_shifted = average_precision_score(y_true, y_score - 10) assert pr_auc == pr_auc_scaled_up assert pr_auc == pr_auc_scaled_down assert pr_auc == pr_auc_shifted
def test_score_scale_invariance(): <DeepExtract> if dataset is None: dataset = datasets.load_iris() X = dataset.data y = dataset.target if True: (X, y) = (X[y < 2], y[y < 2]) (n_samples, n_features) = X.shape p = np.arange(n_samples) rng = check_random_state(37) rng.shuffle(p) (X, y) = (X[p], y[p]) half = int(n_samples / 2) rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)] clf = svm.SVC(kernel='linear', probability=True, random_state=0) y_score = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if True: y_score = y_score[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] (y_true, _, y_score) = (y_true, y_pred, y_score) </DeepExtract> roc_auc = roc_auc_score(y_true, y_score) roc_auc_scaled_up = roc_auc_score(y_true, 100 * y_score) roc_auc_scaled_down = roc_auc_score(y_true, 1e-06 * y_score) roc_auc_shifted = roc_auc_score(y_true, y_score - 10) assert roc_auc == roc_auc_scaled_up assert roc_auc == roc_auc_scaled_down assert roc_auc == roc_auc_shifted pr_auc = average_precision_score(y_true, y_score) pr_auc_scaled_up = average_precision_score(y_true, 100 * y_score) pr_auc_scaled_down = average_precision_score(y_true, 1e-06 * y_score) pr_auc_shifted = average_precision_score(y_true, y_score - 10) assert pr_auc == pr_auc_scaled_up assert pr_auc == pr_auc_scaled_down assert pr_auc == pr_auc_shifted
def partial_fit(self, X, y, classes=None, sample_weight=None): """Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance overhead hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. classes : array-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- self : object Returns the instance itself. """ first_call = not hasattr(self, 'classes_') if first_call: self._validate_params() (X, y) = self._validate_data(X, y, accept_sparse='csr', reset=first_call) (_, n_features) = X.shape if _check_partial_fit_first_call(self, classes): n_classes = len(classes) self.class_count_ = np.zeros(n_classes, dtype=np.float64) self.feature_count_ = np.zeros((n_classes, n_features), dtype=np.float64) Y = label_binarize(y, classes=self.classes_) if Y.shape[1] == 1: if len(self.classes_) == 2: Y = np.concatenate((1 - Y, Y), axis=1) else: Y = np.ones_like(Y) if X.shape[0] != Y.shape[0]: msg = 'X.shape[0]=%d and y.shape[0]=%d are incompatible.' raise ValueError(msg % (X.shape[0], y.shape[0])) Y = Y.astype(np.float64, copy=False) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X) sample_weight = np.atleast_2d(sample_weight) Y *= sample_weight.T class_prior = self.class_prior alpha = np.asarray(self.alpha) if not isinstance(self.alpha, Real) else self.alpha alpha_min = np.min(alpha) if isinstance(alpha, np.ndarray): if not alpha.shape[0] == self.n_features_in_: raise ValueError(f'When alpha is an array, it should contains `n_features`. Got {alpha.shape[0]} elements instead of {self.n_features_in_}.') if alpha_min < 0: raise ValueError('All values in alpha must be greater than 0.') alpha_lower_bound = 1e-10 _force_alpha = self.force_alpha if _force_alpha == 'warn' and alpha_min < alpha_lower_bound: _force_alpha = False warnings.warn('The default value for `force_alpha` will change to `True` in 1.4. To suppress this warning, manually set the value of `force_alpha`.', FutureWarning) if alpha_min < alpha_lower_bound and (not _force_alpha): warnings.warn(f'alpha too small will result in numeric errors, setting alpha = {alpha_lower_bound:.1e}. Use `force_alpha=True` to keep alpha unchanged.') alpha = np.maximum(alpha, alpha_lower_bound) alpha = alpha n_classes = len(self.classes_) if class_prior is not None: if len(class_prior) != n_classes: raise ValueError('Number of priors must match number of classes.') self.class_log_prior_ = np.log(class_prior) elif self.fit_prior: with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) log_class_count = np.log(self.class_count_) self.class_log_prior_ = log_class_count - np.log(self.class_count_.sum()) else: self.class_log_prior_ = np.full(n_classes, -np.log(n_classes)) return self
def partial_fit(self, X, y, classes=None, sample_weight=None): """Incremental fit on a batch of samples. This method is expected to be called several times consecutively on different chunks of a dataset so as to implement out-of-core or online learning. This is especially useful when the whole dataset is too big to fit in memory at once. This method has some performance overhead hence it is better to call partial_fit on chunks of data that are as large as possible (as long as fitting in the memory budget) to hide the overhead. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vectors, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. classes : array-like of shape (n_classes,), default=None List of all the classes that can possibly appear in the y vector. Must be provided at the first call to partial_fit, can be omitted in subsequent calls. sample_weight : array-like of shape (n_samples,), default=None Weights applied to individual samples (1. for unweighted). Returns ------- self : object Returns the instance itself. """ first_call = not hasattr(self, 'classes_') if first_call: self._validate_params() <DeepExtract> (X, y) = self._validate_data(X, y, accept_sparse='csr', reset=first_call) </DeepExtract> (_, n_features) = X.shape if _check_partial_fit_first_call(self, classes): n_classes = len(classes) <DeepExtract> self.class_count_ = np.zeros(n_classes, dtype=np.float64) self.feature_count_ = np.zeros((n_classes, n_features), dtype=np.float64) </DeepExtract> Y = label_binarize(y, classes=self.classes_) if Y.shape[1] == 1: if len(self.classes_) == 2: Y = np.concatenate((1 - Y, Y), axis=1) else: Y = np.ones_like(Y) if X.shape[0] != Y.shape[0]: msg = 'X.shape[0]=%d and y.shape[0]=%d are incompatible.' raise ValueError(msg % (X.shape[0], y.shape[0])) Y = Y.astype(np.float64, copy=False) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X) sample_weight = np.atleast_2d(sample_weight) Y *= sample_weight.T class_prior = self.class_prior <DeepExtract> </DeepExtract> <DeepExtract> alpha = np.asarray(self.alpha) if not isinstance(self.alpha, Real) else self.alpha alpha_min = np.min(alpha) if isinstance(alpha, np.ndarray): if not alpha.shape[0] == self.n_features_in_: raise ValueError(f'When alpha is an array, it should contains `n_features`. Got {alpha.shape[0]} elements instead of {self.n_features_in_}.') if alpha_min < 0: raise ValueError('All values in alpha must be greater than 0.') alpha_lower_bound = 1e-10 _force_alpha = self.force_alpha if _force_alpha == 'warn' and alpha_min < alpha_lower_bound: _force_alpha = False warnings.warn('The default value for `force_alpha` will change to `True` in 1.4. To suppress this warning, manually set the value of `force_alpha`.', FutureWarning) if alpha_min < alpha_lower_bound and (not _force_alpha): warnings.warn(f'alpha too small will result in numeric errors, setting alpha = {alpha_lower_bound:.1e}. Use `force_alpha=True` to keep alpha unchanged.') alpha = np.maximum(alpha, alpha_lower_bound) alpha = alpha </DeepExtract> <DeepExtract> </DeepExtract> <DeepExtract> n_classes = len(self.classes_) if class_prior is not None: if len(class_prior) != n_classes: raise ValueError('Number of priors must match number of classes.') self.class_log_prior_ = np.log(class_prior) elif self.fit_prior: with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) log_class_count = np.log(self.class_count_) self.class_log_prior_ = log_class_count - np.log(self.class_count_.sum()) else: self.class_log_prior_ = np.full(n_classes, -np.log(n_classes)) </DeepExtract> return self
@pytest.mark.parametrize('aligned', [False, True]) def test_create_memmap_backed_data(monkeypatch, aligned): registration_counter = RegistrationCounter() monkeypatch.setattr(atexit, 'register', registration_counter) input_array = np.ones(3) data = create_memmap_backed_data(input_array, aligned=aligned) assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) assert registration_counter.nb_calls == 1 (data, folder) = create_memmap_backed_data(input_array, return_folder=True, aligned=aligned) assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) assert folder == os.path.dirname(data.filename) assert registration_counter.nb_calls == 2 mmap_mode = 'r+' data = create_memmap_backed_data(input_array, mmap_mode=mmap_mode, aligned=aligned) assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) assert registration_counter.nb_calls == 3 input_list = [input_array, input_array + 1, input_array + 2] mmap_data_list = create_memmap_backed_data(input_list, aligned=aligned) for (input_array, data) in zip(input_list, mmap_data_list): assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) assert registration_counter.nb_calls == 4 with pytest.raises(ValueError, match='When creating aligned memmap-backed arrays, input must be a single array or a sequence of arrays'): create_memmap_backed_data([input_array, 'not-an-array'], aligned=True)
@pytest.mark.parametrize('aligned', [False, True]) def test_create_memmap_backed_data(monkeypatch, aligned): registration_counter = RegistrationCounter() monkeypatch.setattr(atexit, 'register', registration_counter) input_array = np.ones(3) data = create_memmap_backed_data(input_array, aligned=aligned) <DeepExtract> assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) </DeepExtract> assert registration_counter.nb_calls == 1 (data, folder) = create_memmap_backed_data(input_array, return_folder=True, aligned=aligned) <DeepExtract> assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) </DeepExtract> assert folder == os.path.dirname(data.filename) assert registration_counter.nb_calls == 2 mmap_mode = 'r+' data = create_memmap_backed_data(input_array, mmap_mode=mmap_mode, aligned=aligned) <DeepExtract> assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) </DeepExtract> assert registration_counter.nb_calls == 3 input_list = [input_array, input_array + 1, input_array + 2] mmap_data_list = create_memmap_backed_data(input_list, aligned=aligned) for (input_array, data) in zip(input_list, mmap_data_list): <DeepExtract> assert isinstance(data, np.memmap) writeable = mmap_mode != 'r' assert data.flags.writeable is writeable np.testing.assert_array_equal(input_array, data) </DeepExtract> assert registration_counter.nb_calls == 4 with pytest.raises(ValueError, match='When creating aligned memmap-backed arrays, input must be a single array or a sequence of arrays'): create_memmap_backed_data([input_array, 'not-an-array'], aligned=True)
def normalized_mutual_info_score(labels_true, labels_pred, *, average_method='arithmetic'): """Normalized Mutual Information between two clusterings. Normalized Mutual Information (NMI) is a normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by some generalized mean of ``H(labels_true)`` and ``H(labels_pred))``, defined by the `average_method`. This measure is not adjusted for chance. Therefore :func:`adjusted_mutual_info_score` might be preferred. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Read more in the :ref:`User Guide <mutual_info_score>`. Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets. labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets. average_method : str, default='arithmetic' How to compute the normalizer in the denominator. Possible options are 'min', 'geometric', 'arithmetic', and 'max'. .. versionadded:: 0.20 .. versionchanged:: 0.22 The default value of ``average_method`` changed from 'geometric' to 'arithmetic'. Returns ------- nmi : float Score between 0.0 and 1.0 in normalized nats (based on the natural logarithm). 1.0 stands for perfectly complete labeling. See Also -------- v_measure_score : V-Measure (NMI with arithmetic mean option). adjusted_rand_score : Adjusted Rand Index. adjusted_mutual_info_score : Adjusted Mutual Information (adjusted against chance). Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import normalized_mutual_info_score >>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) ... # doctest: +SKIP 1.0 >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) ... # doctest: +SKIP 1.0 If classes members are completely split across different clusters, the assignment is totally in-complete, hence the NMI is null:: >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) ... # doctest: +SKIP 0.0 """ labels_true = check_array(labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None) labels_pred = check_array(labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None) type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred) if 'continuous' in (type_pred, type_label): msg = f'Clustering metrics expects discrete values but received {type_label} values for label, and {type_pred} values for target' warnings.warn(msg, UserWarning) if labels_true.ndim != 1: raise ValueError('labels_true must be 1D: shape is %r' % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError('labels_pred must be 1D: shape is %r' % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred) (labels_true, labels_pred) = (labels_true, labels_pred) classes = np.unique(labels_true) clusters = np.unique(labels_pred) if classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0: return 1.0 if eps is not None and True: raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] contingency = sp.coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype) if True: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: contingency = contingency + eps contingency = contingency contingency = contingency.astype(np.float64, copy=False) if contingency is None: (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) else: contingency = check_array(contingency, accept_sparse=['csr', 'csc', 'coo'], dtype=[int, np.int32, np.int64]) if isinstance(contingency, np.ndarray): (nzx, nzy) = np.nonzero(contingency) nz_val = contingency[nzx, nzy] else: (nzx, nzy, nz_val) = sp.find(contingency) contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0)) if pi.size == 1 or pj.size == 1: mi = 0.0 log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(np.int64, copy=False) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) mi = np.clip(mi.sum(), 0.0, None) if mi == 0: return 0.0 (h_true, h_pred) = (entropy(labels_true), entropy(labels_pred)) if average_method == 'min': normalizer = min(h_true, h_pred) elif average_method == 'geometric': normalizer = np.sqrt(h_true * h_pred) elif average_method == 'arithmetic': normalizer = np.mean([h_true, h_pred]) elif average_method == 'max': normalizer = max(h_true, h_pred) else: raise ValueError("'average_method' must be 'min', 'geometric', 'arithmetic', or 'max'") return mi / normalizer
def normalized_mutual_info_score(labels_true, labels_pred, *, average_method='arithmetic'): """Normalized Mutual Information between two clusterings. Normalized Mutual Information (NMI) is a normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by some generalized mean of ``H(labels_true)`` and ``H(labels_pred))``, defined by the `average_method`. This measure is not adjusted for chance. Therefore :func:`adjusted_mutual_info_score` might be preferred. This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way. This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known. Read more in the :ref:`User Guide <mutual_info_score>`. Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets. labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets. average_method : str, default='arithmetic' How to compute the normalizer in the denominator. Possible options are 'min', 'geometric', 'arithmetic', and 'max'. .. versionadded:: 0.20 .. versionchanged:: 0.22 The default value of ``average_method`` changed from 'geometric' to 'arithmetic'. Returns ------- nmi : float Score between 0.0 and 1.0 in normalized nats (based on the natural logarithm). 1.0 stands for perfectly complete labeling. See Also -------- v_measure_score : V-Measure (NMI with arithmetic mean option). adjusted_rand_score : Adjusted Rand Index. adjusted_mutual_info_score : Adjusted Mutual Information (adjusted against chance). Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0:: >>> from sklearn.metrics.cluster import normalized_mutual_info_score >>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) ... # doctest: +SKIP 1.0 >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) ... # doctest: +SKIP 1.0 If classes members are completely split across different clusters, the assignment is totally in-complete, hence the NMI is null:: >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) ... # doctest: +SKIP 0.0 """ <DeepExtract> labels_true = check_array(labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None) labels_pred = check_array(labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None) type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred) if 'continuous' in (type_pred, type_label): msg = f'Clustering metrics expects discrete values but received {type_label} values for label, and {type_pred} values for target' warnings.warn(msg, UserWarning) if labels_true.ndim != 1: raise ValueError('labels_true must be 1D: shape is %r' % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError('labels_pred must be 1D: shape is %r' % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred) (labels_true, labels_pred) = (labels_true, labels_pred) </DeepExtract> classes = np.unique(labels_true) clusters = np.unique(labels_pred) if classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0: return 1.0 <DeepExtract> if eps is not None and True: raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] contingency = sp.coo_matrix((np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype) if True: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: contingency = contingency + eps contingency = contingency </DeepExtract> contingency = contingency.astype(np.float64, copy=False) <DeepExtract> if contingency is None: (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) else: contingency = check_array(contingency, accept_sparse=['csr', 'csc', 'coo'], dtype=[int, np.int32, np.int64]) if isinstance(contingency, np.ndarray): (nzx, nzy) = np.nonzero(contingency) nz_val = contingency[nzx, nzy] else: (nzx, nzy, nz_val) = sp.find(contingency) contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0)) if pi.size == 1 or pj.size == 1: mi = 0.0 log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(np.int64, copy=False) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) mi = np.clip(mi.sum(), 0.0, None) </DeepExtract> if mi == 0: return 0.0 (h_true, h_pred) = (entropy(labels_true), entropy(labels_pred)) <DeepExtract> if average_method == 'min': normalizer = min(h_true, h_pred) elif average_method == 'geometric': normalizer = np.sqrt(h_true * h_pred) elif average_method == 'arithmetic': normalizer = np.mean([h_true, h_pred]) elif average_method == 'max': normalizer = max(h_true, h_pred) else: raise ValueError("'average_method' must be 'min', 'geometric', 'arithmetic', or 'max'") </DeepExtract> return mi / normalizer
def test_elasticnet_precompute_gram_weighted_samples(): random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(n_features, n_targets) else: w = random_state.randn(n_features) w[n_informative_features:] = 0.0 X = random_state.randn(n_samples, n_features) y = np.dot(X, w) X_test = random_state.randn(n_samples, n_features) y_test = np.dot(X_test, w) (X, y, _, _) = (X, y, X_test, y_test) rng = np.random.RandomState(0) sample_weight = rng.lognormal(size=y.shape) w_norm = sample_weight * (y.shape / np.sum(sample_weight)) X_c = X - np.average(X, axis=0, weights=w_norm) X_r = X_c * np.sqrt(w_norm)[:, np.newaxis] gram = np.dot(X_r.T, X_r) clf1 = ElasticNet(alpha=0.01, precompute=gram) clf1.fit(X_c, y, sample_weight=sample_weight) clf2 = ElasticNet(alpha=0.01, precompute=False) clf2.fit(X, y, sample_weight=sample_weight) assert_allclose(clf1.coef_, clf2.coef_)
def test_elasticnet_precompute_gram_weighted_samples(): <DeepExtract> random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(n_features, n_targets) else: w = random_state.randn(n_features) w[n_informative_features:] = 0.0 X = random_state.randn(n_samples, n_features) y = np.dot(X, w) X_test = random_state.randn(n_samples, n_features) y_test = np.dot(X_test, w) (X, y, _, _) = (X, y, X_test, y_test) </DeepExtract> rng = np.random.RandomState(0) sample_weight = rng.lognormal(size=y.shape) w_norm = sample_weight * (y.shape / np.sum(sample_weight)) X_c = X - np.average(X, axis=0, weights=w_norm) X_r = X_c * np.sqrt(w_norm)[:, np.newaxis] gram = np.dot(X_r.T, X_r) clf1 = ElasticNet(alpha=0.01, precompute=gram) clf1.fit(X_c, y, sample_weight=sample_weight) clf2 = ElasticNet(alpha=0.01, precompute=False) clf2.fit(X, y, sample_weight=sample_weight) assert_allclose(clf1.coef_, clf2.coef_)
@validate_params({'n_samples': [Interval(Integral, 1, None, closed='left')], 'n_features': [Interval(Integral, 1, None, closed='left')], 'n_informative': [Interval(Integral, 0, None, closed='left')], 'n_targets': [Interval(Integral, 1, None, closed='left')], 'bias': [Interval(Real, None, None, closed='neither')], 'effective_rank': [Interval(Integral, 1, None, closed='left'), None], 'tail_strength': [Interval(Real, 0, 1, closed='both')], 'noise': [Interval(Real, 0, None, closed='left')], 'shuffle': ['boolean'], 'coef': ['boolean'], 'random_state': ['random_state']}) def make_regression(n_samples=100, n_features=100, *, n_informative=10, n_targets=1, bias=0.0, effective_rank=None, tail_strength=0.5, noise=0.0, shuffle=True, coef=False, random_state=None): """Generate a random regression problem. The input set can either be well conditioned (by default) or have a low rank-fat tail singular profile. See :func:`make_low_rank_matrix` for more details. The output is generated by applying a (potentially biased) random linear regression model with `n_informative` nonzero regressors to the previously generated input and some gaussian centered noise with some adjustable scale. Read more in the :ref:`User Guide <sample_generators>`. Parameters ---------- n_samples : int, default=100 The number of samples. n_features : int, default=100 The number of features. n_informative : int, default=10 The number of informative features, i.e., the number of features used to build the linear model used to generate the output. n_targets : int, default=1 The number of regression targets, i.e., the dimension of the y output vector associated with a sample. By default, the output is a scalar. bias : float, default=0.0 The bias term in the underlying linear model. effective_rank : int, default=None If not None: The approximate number of singular vectors required to explain most of the input data by linear combinations. Using this kind of singular spectrum in the input allows the generator to reproduce the correlations often observed in practice. If None: The input set is well conditioned, centered and gaussian with unit variance. tail_strength : float, default=0.5 The relative importance of the fat noisy tail of the singular values profile if `effective_rank` is not None. When a float, it should be between 0 and 1. noise : float, default=0.0 The standard deviation of the gaussian noise applied to the output. shuffle : bool, default=True Shuffle the samples and the features. coef : bool, default=False If True, the coefficients of the underlying linear model are returned. random_state : int, RandomState instance or None, default=None Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. Returns ------- X : ndarray of shape (n_samples, n_features) The input samples. y : ndarray of shape (n_samples,) or (n_samples, n_targets) The output values. coef : ndarray of shape (n_features,) or (n_features, n_targets) The coefficient of the underlying linear model. It is returned only if coef is True. Examples -------- >>> from sklearn.datasets import make_regression >>> X, y = make_regression(n_samples=5, n_features=2, noise=1, random_state=42) >>> X array([[ 0.4967..., -0.1382... ], [ 0.6476..., 1.523...], [-0.2341..., -0.2341...], [-0.4694..., 0.5425...], [ 1.579..., 0.7674...]]) >>> y array([ 6.737..., 37.79..., -10.27..., 0.4017..., 42.22...]) """ n_informative = min(n_features, n_informative) generator = check_random_state(random_state) if effective_rank is None: X = generator.standard_normal(size=(n_samples, n_features)) else: generator = check_random_state(generator) n = min(n_samples, n_features) (u, _) = linalg.qr(generator.standard_normal(size=(n_samples, n)), mode='economic', check_finite=False) (v, _) = linalg.qr(generator.standard_normal(size=(n_features, n)), mode='economic', check_finite=False) singular_ind = np.arange(n, dtype=np.float64) low_rank = (1 - tail_strength) * np.exp(-1.0 * (singular_ind / effective_rank) ** 2) tail = tail_strength * np.exp(-0.1 * singular_ind / effective_rank) s = np.identity(n) * (low_rank + tail) X = np.dot(np.dot(u, s), v.T) ground_truth = np.zeros((n_features, n_targets)) ground_truth[:n_informative, :] = 100 * generator.uniform(size=(n_informative, n_targets)) y = np.dot(X, ground_truth) + bias if noise > 0.0: y += generator.normal(scale=noise, size=y.shape) if shuffle: (X, y) = util_shuffle(X, y, random_state=generator) indices = np.arange(n_features) generator.shuffle(indices) X[:, :] = X[:, indices] ground_truth = ground_truth[indices] y = np.squeeze(y) if coef: return (X, y, np.squeeze(ground_truth)) else: return (X, y)
@validate_params({'n_samples': [Interval(Integral, 1, None, closed='left')], 'n_features': [Interval(Integral, 1, None, closed='left')], 'n_informative': [Interval(Integral, 0, None, closed='left')], 'n_targets': [Interval(Integral, 1, None, closed='left')], 'bias': [Interval(Real, None, None, closed='neither')], 'effective_rank': [Interval(Integral, 1, None, closed='left'), None], 'tail_strength': [Interval(Real, 0, 1, closed='both')], 'noise': [Interval(Real, 0, None, closed='left')], 'shuffle': ['boolean'], 'coef': ['boolean'], 'random_state': ['random_state']}) def make_regression(n_samples=100, n_features=100, *, n_informative=10, n_targets=1, bias=0.0, effective_rank=None, tail_strength=0.5, noise=0.0, shuffle=True, coef=False, random_state=None): """Generate a random regression problem. The input set can either be well conditioned (by default) or have a low rank-fat tail singular profile. See :func:`make_low_rank_matrix` for more details. The output is generated by applying a (potentially biased) random linear regression model with `n_informative` nonzero regressors to the previously generated input and some gaussian centered noise with some adjustable scale. Read more in the :ref:`User Guide <sample_generators>`. Parameters ---------- n_samples : int, default=100 The number of samples. n_features : int, default=100 The number of features. n_informative : int, default=10 The number of informative features, i.e., the number of features used to build the linear model used to generate the output. n_targets : int, default=1 The number of regression targets, i.e., the dimension of the y output vector associated with a sample. By default, the output is a scalar. bias : float, default=0.0 The bias term in the underlying linear model. effective_rank : int, default=None If not None: The approximate number of singular vectors required to explain most of the input data by linear combinations. Using this kind of singular spectrum in the input allows the generator to reproduce the correlations often observed in practice. If None: The input set is well conditioned, centered and gaussian with unit variance. tail_strength : float, default=0.5 The relative importance of the fat noisy tail of the singular values profile if `effective_rank` is not None. When a float, it should be between 0 and 1. noise : float, default=0.0 The standard deviation of the gaussian noise applied to the output. shuffle : bool, default=True Shuffle the samples and the features. coef : bool, default=False If True, the coefficients of the underlying linear model are returned. random_state : int, RandomState instance or None, default=None Determines random number generation for dataset creation. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. Returns ------- X : ndarray of shape (n_samples, n_features) The input samples. y : ndarray of shape (n_samples,) or (n_samples, n_targets) The output values. coef : ndarray of shape (n_features,) or (n_features, n_targets) The coefficient of the underlying linear model. It is returned only if coef is True. Examples -------- >>> from sklearn.datasets import make_regression >>> X, y = make_regression(n_samples=5, n_features=2, noise=1, random_state=42) >>> X array([[ 0.4967..., -0.1382... ], [ 0.6476..., 1.523...], [-0.2341..., -0.2341...], [-0.4694..., 0.5425...], [ 1.579..., 0.7674...]]) >>> y array([ 6.737..., 37.79..., -10.27..., 0.4017..., 42.22...]) """ n_informative = min(n_features, n_informative) generator = check_random_state(random_state) if effective_rank is None: X = generator.standard_normal(size=(n_samples, n_features)) else: <DeepExtract> generator = check_random_state(generator) n = min(n_samples, n_features) (u, _) = linalg.qr(generator.standard_normal(size=(n_samples, n)), mode='economic', check_finite=False) (v, _) = linalg.qr(generator.standard_normal(size=(n_features, n)), mode='economic', check_finite=False) singular_ind = np.arange(n, dtype=np.float64) low_rank = (1 - tail_strength) * np.exp(-1.0 * (singular_ind / effective_rank) ** 2) tail = tail_strength * np.exp(-0.1 * singular_ind / effective_rank) s = np.identity(n) * (low_rank + tail) X = np.dot(np.dot(u, s), v.T) </DeepExtract> ground_truth = np.zeros((n_features, n_targets)) ground_truth[:n_informative, :] = 100 * generator.uniform(size=(n_informative, n_targets)) y = np.dot(X, ground_truth) + bias if noise > 0.0: y += generator.normal(scale=noise, size=y.shape) if shuffle: (X, y) = util_shuffle(X, y, random_state=generator) indices = np.arange(n_features) generator.shuffle(indices) X[:, :] = X[:, indices] ground_truth = ground_truth[indices] y = np.squeeze(y) if coef: return (X, y, np.squeeze(ground_truth)) else: return (X, y)
@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES) def test_discretenb_prior(DiscreteNaiveBayes, global_random_seed): rng = np.random.RandomState(global_random_seed) X2 = rng.randint(5, size=(6, 100)) y2 = np.array([1, 1, 2, 2, 3, 3]) (X2, y2) = (X2, y2) clf = DiscreteNaiveBayes().fit(X2, y2) assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0), clf.class_log_prior_, 8)
@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES) def test_discretenb_prior(DiscreteNaiveBayes, global_random_seed): <DeepExtract> rng = np.random.RandomState(global_random_seed) X2 = rng.randint(5, size=(6, 100)) y2 = np.array([1, 1, 2, 2, 3, 3]) (X2, y2) = (X2, y2) </DeepExtract> clf = DiscreteNaiveBayes().fit(X2, y2) assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0), clf.class_log_prior_, 8)
def _check_params(self, X): self._n_components = self.n_components if self._n_components is None: self._n_components = X.shape[1] if self.positive_code and self.fit_algorithm in ['omp', 'lars']: raise ValueError("Positive constraint not supported for '{}' coding method.".format(self.fit_algorithm)) self._fit_algorithm = 'lasso_' + self.fit_algorithm self._batch_size = min(self.batch_size, X.shape[0])
def _check_params(self, X): self._n_components = self.n_components if self._n_components is None: self._n_components = X.shape[1] <DeepExtract> if self.positive_code and self.fit_algorithm in ['omp', 'lars']: raise ValueError("Positive constraint not supported for '{}' coding method.".format(self.fit_algorithm)) </DeepExtract> self._fit_algorithm = 'lasso_' + self.fit_algorithm self._batch_size = min(self.batch_size, X.shape[0])
def _unnormalized_transform(self, X): """Transform data X according to fitted model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Document word matrix. Returns ------- doc_topic_distr : ndarray of shape (n_samples, n_components) Document topic distribution for X. """ random_state = self.random_state_ if False else None n_jobs = effective_n_jobs(self.n_jobs) if parallel is None: parallel = Parallel(n_jobs=n_jobs, verbose=max(0, self.verbose - 1)) results = parallel((delayed(_update_doc_distribution)(X[idx_slice, :], self.exp_dirichlet_component_, self.doc_topic_prior_, self.max_doc_update_iter, self.mean_change_tol, False, random_state) for idx_slice in gen_even_slices(X.shape[0], n_jobs))) (doc_topics, sstats_list) = zip(*results) doc_topic_distr = np.vstack(doc_topics) if False: suff_stats = np.zeros(self.components_.shape, dtype=self.components_.dtype) for sstats in sstats_list: suff_stats += sstats suff_stats *= self.exp_dirichlet_component_ else: suff_stats = None (doc_topic_distr, _) = (doc_topic_distr, suff_stats) return doc_topic_distr
def _unnormalized_transform(self, X): """Transform data X according to fitted model. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Document word matrix. Returns ------- doc_topic_distr : ndarray of shape (n_samples, n_components) Document topic distribution for X. """ <DeepExtract> random_state = self.random_state_ if False else None n_jobs = effective_n_jobs(self.n_jobs) if parallel is None: parallel = Parallel(n_jobs=n_jobs, verbose=max(0, self.verbose - 1)) results = parallel((delayed(_update_doc_distribution)(X[idx_slice, :], self.exp_dirichlet_component_, self.doc_topic_prior_, self.max_doc_update_iter, self.mean_change_tol, False, random_state) for idx_slice in gen_even_slices(X.shape[0], n_jobs))) (doc_topics, sstats_list) = zip(*results) doc_topic_distr = np.vstack(doc_topics) if False: suff_stats = np.zeros(self.components_.shape, dtype=self.components_.dtype) for sstats in sstats_list: suff_stats += sstats suff_stats *= self.exp_dirichlet_component_ else: suff_stats = None (doc_topic_distr, _) = (doc_topic_distr, suff_stats) </DeepExtract> return doc_topic_distr
def test_enet_copy_X_False_check_input_False(): random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(n_features, n_targets) else: w = random_state.randn(n_features) w[n_informative_features:] = 0.0 X = random_state.randn(n_samples, n_features) y = np.dot(X, w) X_test = random_state.randn(n_samples, n_features) y_test = np.dot(X_test, w) (X, y, _, _) = (X, y, X_test, y_test) X = X.copy(order='F') original_X = X.copy() enet = ElasticNet(copy_X=False) enet.fit(X, y, check_input=False) assert np.any(np.not_equal(original_X, X))
def test_enet_copy_X_False_check_input_False(): <DeepExtract> random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(n_features, n_targets) else: w = random_state.randn(n_features) w[n_informative_features:] = 0.0 X = random_state.randn(n_samples, n_features) y = np.dot(X, w) X_test = random_state.randn(n_samples, n_features) y_test = np.dot(X_test, w) (X, y, _, _) = (X, y, X_test, y_test) </DeepExtract> X = X.copy(order='F') original_X = X.copy() enet = ElasticNet(copy_X=False) enet.fit(X, y, check_input=False) assert np.any(np.not_equal(original_X, X))
def test_kwargs_in_init(): class WithKWargs(BaseEstimator): def __init__(self, a='willchange', b='unchanged', **kwargs): self.a = a self.b = b self._other_params = {} for (key, value) in params.items(): setattr(self, key, value) self._other_params[key] = value return self def get_params(self, deep=True): params = super().get_params(deep=deep) params.update(self._other_params) return params def set_params(self, **params): for (key, value) in params.items(): setattr(self, key, value) self._other_params[key] = value return self est = WithKWargs(a='something', c='abcd', d=None) expected = "WithKWargs(a='something', c='abcd', d=None)" assert expected == est.__repr__() with config_context(print_changed_only=False): expected = "WithKWargs(a='something', b='unchanged', c='abcd', d=None)" assert expected == est.__repr__()
def test_kwargs_in_init(): class WithKWargs(BaseEstimator): def __init__(self, a='willchange', b='unchanged', **kwargs): self.a = a self.b = b self._other_params = {} <DeepExtract> for (key, value) in params.items(): setattr(self, key, value) self._other_params[key] = value return self </DeepExtract> def get_params(self, deep=True): params = super().get_params(deep=deep) params.update(self._other_params) return params def set_params(self, **params): for (key, value) in params.items(): setattr(self, key, value) self._other_params[key] = value return self est = WithKWargs(a='something', c='abcd', d=None) expected = "WithKWargs(a='something', c='abcd', d=None)" assert expected == est.__repr__() with config_context(print_changed_only=False): expected = "WithKWargs(a='something', b='unchanged', c='abcd', d=None)" assert expected == est.__repr__()
def score(self, X=None, Y=None): """Fake score. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data, where `n_samples` is the number of samples and `n_features` is the number of features. Y : array-like of shape (n_samples, n_output) or (n_samples,) Target relative to X for classification or regression; None for unsupervised learning. Returns ------- score : float Either 0 or 1 depending of `foo_param` (i.e. `foo_param > 1 => score=1` otherwise `score=0`). """ if self.methods_to_check == 'all' or 'score' in self.methods_to_check: if should_be_fitted: check_is_fitted(self) if self.check_X is not None: params = {} if self.check_X_params is None else self.check_X_params checked_X = self.check_X(X, **params) if isinstance(checked_X, (bool, np.bool_)): assert checked_X else: X = checked_X if Y is not None and self.check_y is not None: params = {} if self.check_y_params is None else self.check_y_params checked_y = self.check_y(Y, **params) if isinstance(checked_y, (bool, np.bool_)): assert checked_y else: Y = checked_y return (X, Y) if self.foo_param > 1: score = 1.0 else: score = 0.0 return score
def score(self, X=None, Y=None): """Fake score. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data, where `n_samples` is the number of samples and `n_features` is the number of features. Y : array-like of shape (n_samples, n_output) or (n_samples,) Target relative to X for classification or regression; None for unsupervised learning. Returns ------- score : float Either 0 or 1 depending of `foo_param` (i.e. `foo_param > 1 => score=1` otherwise `score=0`). """ if self.methods_to_check == 'all' or 'score' in self.methods_to_check: <DeepExtract> if should_be_fitted: check_is_fitted(self) if self.check_X is not None: params = {} if self.check_X_params is None else self.check_X_params checked_X = self.check_X(X, **params) if isinstance(checked_X, (bool, np.bool_)): assert checked_X else: X = checked_X if Y is not None and self.check_y is not None: params = {} if self.check_y_params is None else self.check_y_params checked_y = self.check_y(Y, **params) if isinstance(checked_y, (bool, np.bool_)): assert checked_y else: Y = checked_y return (X, Y) </DeepExtract> if self.foo_param > 1: score = 1.0 else: score = 0.0 return score
def test_select_percentile_regression_full(): (X, y) = make_regression(n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0) univariate_filter = SelectPercentile(f_regression, percentile=100) X_r = univariate_filter.fit(X, y).transform(X) scores = univariate_filter.scores_ support = univariate_filter.get_support() assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():]) X_r2 = GenericUnivariateSelect(f_regression, mode='percentile', param=100).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.ones(20) assert_array_equal(support, gtruth)
def test_select_percentile_regression_full(): (X, y) = make_regression(n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0) univariate_filter = SelectPercentile(f_regression, percentile=100) X_r = univariate_filter.fit(X, y).transform(X) <DeepExtract> scores = univariate_filter.scores_ support = univariate_filter.get_support() assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum():]) </DeepExtract> X_r2 = GenericUnivariateSelect(f_regression, mode='percentile', param=100).fit(X, y).transform(X) assert_array_equal(X_r, X_r2) support = univariate_filter.get_support() gtruth = np.ones(20) assert_array_equal(support, gtruth)
def assert_radius_neighbors_results_quasi_equality(ref_dist, dist, ref_indices, indices, radius, rtol=0.0001): """Assert that radius neighborhood results are valid up to: - relative tolerance on computed distance values - permutations of indices for distances values that differ up to a precision level - missing or extra last elements if their distance is close to the radius To be used for testing neighbors queries on float32 datasets: we accept neighbors rank swaps only if they are caused by small rounding errors on the distance computations. Input arrays must be sorted w.r.t distances. """ is_sorted = lambda a: np.all(a[:-1] <= a[1:]) n_significant_digits = -(int(floor(log10(abs(rtol)))) + 1) assert len(ref_dist) == len(dist) == len(ref_indices) == len(indices), 'Arrays of results have various lengths.' n_queries = len(ref_dist) for query_idx in range(n_queries): ref_dist_row = ref_dist[query_idx] dist_row = dist[query_idx] assert is_sorted(ref_dist_row), f"Reference distances aren't sorted on row {query_idx}" assert is_sorted(dist_row), f"Distances aren't sorted on row {query_idx}" largest_row = ref_dist_row if len(ref_dist_row) > len(dist_row) else dist_row min_length = min(len(ref_dist_row), len(dist_row)) last_extra_elements = largest_row[min_length:] if last_extra_elements.size > 0: assert np.all(radius - rtol <= last_extra_elements <= radius + rtol), f"The last extra elements ({last_extra_elements}) aren't in [radius ± rtol]=[{radius} ± {rtol}]" ref_dist_row = ref_dist_row[:min_length] dist_row = dist_row[:min_length] assert_allclose(ref_dist_row, dist_row, rtol=rtol) ref_indices_row = ref_indices[query_idx] indices_row = indices[query_idx] reference_neighbors_groups = defaultdict(set) effective_neighbors_groups = defaultdict(set) for neighbor_rank in range(min_length): if ref_dist_row[neighbor_rank] == 0: rounded_dist = 0.0 magnitude = int(floor(log10(abs(ref_dist_row[neighbor_rank])))) + 1 rounded_dist = round(ref_dist_row[neighbor_rank], n_significant_digits - magnitude) reference_neighbors_groups[rounded_dist].add(ref_indices_row[neighbor_rank]) effective_neighbors_groups[rounded_dist].add(indices_row[neighbor_rank]) msg = f'Neighbors indices for query {query_idx} are not matching when rounding distances at {n_significant_digits} significant digits derived from rtol={rtol:.1e}' for rounded_distance in reference_neighbors_groups.keys(): assert reference_neighbors_groups[rounded_distance] == effective_neighbors_groups[rounded_distance], msg
def assert_radius_neighbors_results_quasi_equality(ref_dist, dist, ref_indices, indices, radius, rtol=0.0001): """Assert that radius neighborhood results are valid up to: - relative tolerance on computed distance values - permutations of indices for distances values that differ up to a precision level - missing or extra last elements if their distance is close to the radius To be used for testing neighbors queries on float32 datasets: we accept neighbors rank swaps only if they are caused by small rounding errors on the distance computations. Input arrays must be sorted w.r.t distances. """ is_sorted = lambda a: np.all(a[:-1] <= a[1:]) n_significant_digits = -(int(floor(log10(abs(rtol)))) + 1) assert len(ref_dist) == len(dist) == len(ref_indices) == len(indices), 'Arrays of results have various lengths.' n_queries = len(ref_dist) for query_idx in range(n_queries): ref_dist_row = ref_dist[query_idx] dist_row = dist[query_idx] assert is_sorted(ref_dist_row), f"Reference distances aren't sorted on row {query_idx}" assert is_sorted(dist_row), f"Distances aren't sorted on row {query_idx}" largest_row = ref_dist_row if len(ref_dist_row) > len(dist_row) else dist_row min_length = min(len(ref_dist_row), len(dist_row)) last_extra_elements = largest_row[min_length:] if last_extra_elements.size > 0: assert np.all(radius - rtol <= last_extra_elements <= radius + rtol), f"The last extra elements ({last_extra_elements}) aren't in [radius ± rtol]=[{radius} ± {rtol}]" ref_dist_row = ref_dist_row[:min_length] dist_row = dist_row[:min_length] assert_allclose(ref_dist_row, dist_row, rtol=rtol) ref_indices_row = ref_indices[query_idx] indices_row = indices[query_idx] reference_neighbors_groups = defaultdict(set) effective_neighbors_groups = defaultdict(set) for neighbor_rank in range(min_length): <DeepExtract> if ref_dist_row[neighbor_rank] == 0: rounded_dist = 0.0 magnitude = int(floor(log10(abs(ref_dist_row[neighbor_rank])))) + 1 rounded_dist = round(ref_dist_row[neighbor_rank], n_significant_digits - magnitude) </DeepExtract> reference_neighbors_groups[rounded_dist].add(ref_indices_row[neighbor_rank]) effective_neighbors_groups[rounded_dist].add(indices_row[neighbor_rank]) msg = f'Neighbors indices for query {query_idx} are not matching when rounding distances at {n_significant_digits} significant digits derived from rtol={rtol:.1e}' for rounded_distance in reference_neighbors_groups.keys(): assert reference_neighbors_groups[rounded_distance] == effective_neighbors_groups[rounded_distance], msg
def reduce_tree_with_different_bitness(tree): new_dtype = np.int64 if _IS_32BIT else np.int32 (tree_cls, (n_features, n_classes, n_outputs), state) = tree.__reduce__() new_n_classes = n_classes.astype(new_dtype, casting='same_kind') new_state = state.copy() new_dtype_for_indexing_fields = np.int64 if _IS_32BIT else np.int32 indexing_field_names = ['left_child', 'right_child', 'feature', 'n_node_samples'] new_dtype_dict = {name: dtype for (name, (dtype, _)) in new_state['nodes'].dtype.fields.items()} for name in indexing_field_names: new_dtype_dict[name] = new_dtype_for_indexing_fields new_dtype = np.dtype({'names': list(new_dtype_dict.keys()), 'formats': list(new_dtype_dict.values())}) new_state['nodes'] = new_state['nodes'].astype(new_dtype, casting='same_kind') return (tree_cls, (n_features, new_n_classes, n_outputs), new_state)
def reduce_tree_with_different_bitness(tree): new_dtype = np.int64 if _IS_32BIT else np.int32 (tree_cls, (n_features, n_classes, n_outputs), state) = tree.__reduce__() new_n_classes = n_classes.astype(new_dtype, casting='same_kind') new_state = state.copy() <DeepExtract> new_dtype_for_indexing_fields = np.int64 if _IS_32BIT else np.int32 indexing_field_names = ['left_child', 'right_child', 'feature', 'n_node_samples'] new_dtype_dict = {name: dtype for (name, (dtype, _)) in new_state['nodes'].dtype.fields.items()} for name in indexing_field_names: new_dtype_dict[name] = new_dtype_for_indexing_fields new_dtype = np.dtype({'names': list(new_dtype_dict.keys()), 'formats': list(new_dtype_dict.values())}) new_state['nodes'] = new_state['nodes'].astype(new_dtype, casting='same_kind') </DeepExtract> return (tree_cls, (n_features, new_n_classes, n_outputs), new_state)
def fit_transform(self, raw_documents, y=None): """Learn the vocabulary dictionary and return document-term matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable An iterable which generates either str, unicode or file objects. y : None This parameter is ignored. Returns ------- X : array of shape (n_samples, n_features) Document-term matrix. """ if isinstance(raw_documents, str): raise ValueError('Iterable over raw text documents expected, string object received.') self._validate_params() (min_n, max_m) = self.ngram_range if min_n > max_m: raise ValueError('Invalid value for ngram_range=%s lower boundary larger than the upper boundary.' % str(self.ngram_range)) if self.tokenizer is not None and self.token_pattern is not None: warnings.warn("The parameter 'token_pattern' will not be used since 'tokenizer' is not None'") if self.preprocessor is not None and callable(self.analyzer): warnings.warn("The parameter 'preprocessor' will not be used since 'analyzer' is callable'") if self.ngram_range != (1, 1) and self.ngram_range is not None and callable(self.analyzer): warnings.warn("The parameter 'ngram_range' will not be used since 'analyzer' is callable'") if self.analyzer != 'word' or callable(self.analyzer): if self.stop_words is not None: warnings.warn("The parameter 'stop_words' will not be used since 'analyzer' != 'word'") if self.token_pattern is not None and self.token_pattern != '(?u)\\b\\w\\w+\\b': warnings.warn("The parameter 'token_pattern' will not be used since 'analyzer' != 'word'") if self.tokenizer is not None: warnings.warn("The parameter 'tokenizer' will not be used since 'analyzer' != 'word'") vocabulary = self.vocabulary if vocabulary is not None: if isinstance(vocabulary, set): vocabulary = sorted(vocabulary) if not isinstance(vocabulary, Mapping): vocab = {} for (i, t) in enumerate(vocabulary): if vocab.setdefault(t, i) != i: msg = 'Duplicate term in vocabulary: %r' % t raise ValueError(msg) vocabulary = vocab else: indices = set(vocabulary.values()) if len(indices) != len(vocabulary): raise ValueError('Vocabulary contains repeated indices.') for i in range(len(vocabulary)): if i not in indices: msg = "Vocabulary of size %d doesn't contain index %d." % (len(vocabulary), i) raise ValueError(msg) if not vocabulary: raise ValueError('empty vocabulary passed to fit') self.fixed_vocabulary_ = True self.vocabulary_ = dict(vocabulary) else: self.fixed_vocabulary_ = False max_df = self.max_df min_df = self.min_df max_features = self.max_features if self.fixed_vocabulary_ and self.lowercase: for term in self.vocabulary: if any(map(str.isupper, term)): warnings.warn("Upper case characters found in vocabulary while 'lowercase' is True. These entries will not be matched with any documents") break if self.fixed_vocabulary_: vocabulary = self.vocabulary_ else: vocabulary = defaultdict() vocabulary.default_factory = vocabulary.__len__ analyze = self.build_analyzer() j_indices = [] indptr = [] values = _make_int_array() indptr.append(0) for doc in raw_documents: feature_counter = {} for feature in analyze(doc): try: feature_idx = vocabulary[feature] if feature_idx not in feature_counter: feature_counter[feature_idx] = 1 else: feature_counter[feature_idx] += 1 except KeyError: continue j_indices.extend(feature_counter.keys()) values.extend(feature_counter.values()) indptr.append(len(j_indices)) if not self.fixed_vocabulary_: vocabulary = dict(vocabulary) if not vocabulary: raise ValueError('empty vocabulary; perhaps the documents only contain stop words') if indptr[-1] > np.iinfo(np.int32).max: if _IS_32BIT: raise ValueError('sparse CSR array has {} non-zero elements and requires 64 bit indexing, which is unsupported with 32 bit Python.'.format(indptr[-1])) indices_dtype = np.int64 else: indices_dtype = np.int32 j_indices = np.asarray(j_indices, dtype=indices_dtype) indptr = np.asarray(indptr, dtype=indices_dtype) values = np.frombuffer(values, dtype=np.intc) X = sp.csr_matrix((values, j_indices, indptr), shape=(len(indptr) - 1, len(vocabulary)), dtype=self.dtype) X.sort_indices() (vocabulary, X) = (vocabulary, X) if self.binary: X.data.fill(1) if not self.fixed_vocabulary_: n_doc = X.shape[0] max_doc_count = max_df if isinstance(max_df, Integral) else max_df * n_doc min_doc_count = min_df if isinstance(min_df, Integral) else min_df * n_doc if max_doc_count < min_doc_count: raise ValueError('max_df corresponds to < documents than min_df') if max_features is not None: sorted_features = sorted(vocabulary.items()) map_index = np.empty(len(sorted_features), dtype=X.indices.dtype) for (new_val, (term, old_val)) in enumerate(sorted_features): vocabulary[term] = new_val map_index[old_val] = new_val X.indices = map_index.take(X.indices, mode='clip') X = X if max_doc_count is None and min_doc_count is None and (max_features is None): (X, self.stop_words_) = (X, set()) dfs = _document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if max_doc_count is not None: mask &= dfs <= max_doc_count if min_doc_count is not None: mask &= dfs >= min_doc_count if max_features is not None and mask.sum() > max_features: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:max_features] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices = np.cumsum(mask) - 1 removed_terms = set() for (term, old_index) in list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) == 0: raise ValueError('After pruning, no terms remain. Try a lower min_df or a higher max_df.') (X, self.stop_words_) = (X[:, kept_indices], removed_terms) if max_features is None: sorted_features = sorted(vocabulary.items()) map_index = np.empty(len(sorted_features), dtype=X.indices.dtype) for (new_val, (term, old_val)) in enumerate(sorted_features): vocabulary[term] = new_val map_index[old_val] = new_val X.indices = map_index.take(X.indices, mode='clip') X = X self.vocabulary_ = vocabulary return X
def fit_transform(self, raw_documents, y=None): """Learn the vocabulary dictionary and return document-term matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable An iterable which generates either str, unicode or file objects. y : None This parameter is ignored. Returns ------- X : array of shape (n_samples, n_features) Document-term matrix. """ if isinstance(raw_documents, str): raise ValueError('Iterable over raw text documents expected, string object received.') self._validate_params() <DeepExtract> (min_n, max_m) = self.ngram_range if min_n > max_m: raise ValueError('Invalid value for ngram_range=%s lower boundary larger than the upper boundary.' % str(self.ngram_range)) </DeepExtract> <DeepExtract> if self.tokenizer is not None and self.token_pattern is not None: warnings.warn("The parameter 'token_pattern' will not be used since 'tokenizer' is not None'") if self.preprocessor is not None and callable(self.analyzer): warnings.warn("The parameter 'preprocessor' will not be used since 'analyzer' is callable'") if self.ngram_range != (1, 1) and self.ngram_range is not None and callable(self.analyzer): warnings.warn("The parameter 'ngram_range' will not be used since 'analyzer' is callable'") if self.analyzer != 'word' or callable(self.analyzer): if self.stop_words is not None: warnings.warn("The parameter 'stop_words' will not be used since 'analyzer' != 'word'") if self.token_pattern is not None and self.token_pattern != '(?u)\\b\\w\\w+\\b': warnings.warn("The parameter 'token_pattern' will not be used since 'analyzer' != 'word'") if self.tokenizer is not None: warnings.warn("The parameter 'tokenizer' will not be used since 'analyzer' != 'word'") </DeepExtract> <DeepExtract> vocabulary = self.vocabulary if vocabulary is not None: if isinstance(vocabulary, set): vocabulary = sorted(vocabulary) if not isinstance(vocabulary, Mapping): vocab = {} for (i, t) in enumerate(vocabulary): if vocab.setdefault(t, i) != i: msg = 'Duplicate term in vocabulary: %r' % t raise ValueError(msg) vocabulary = vocab else: indices = set(vocabulary.values()) if len(indices) != len(vocabulary): raise ValueError('Vocabulary contains repeated indices.') for i in range(len(vocabulary)): if i not in indices: msg = "Vocabulary of size %d doesn't contain index %d." % (len(vocabulary), i) raise ValueError(msg) if not vocabulary: raise ValueError('empty vocabulary passed to fit') self.fixed_vocabulary_ = True self.vocabulary_ = dict(vocabulary) else: self.fixed_vocabulary_ = False </DeepExtract> max_df = self.max_df min_df = self.min_df max_features = self.max_features if self.fixed_vocabulary_ and self.lowercase: for term in self.vocabulary: if any(map(str.isupper, term)): warnings.warn("Upper case characters found in vocabulary while 'lowercase' is True. These entries will not be matched with any documents") break <DeepExtract> if self.fixed_vocabulary_: vocabulary = self.vocabulary_ else: vocabulary = defaultdict() vocabulary.default_factory = vocabulary.__len__ analyze = self.build_analyzer() j_indices = [] indptr = [] values = _make_int_array() indptr.append(0) for doc in raw_documents: feature_counter = {} for feature in analyze(doc): try: feature_idx = vocabulary[feature] if feature_idx not in feature_counter: feature_counter[feature_idx] = 1 else: feature_counter[feature_idx] += 1 except KeyError: continue j_indices.extend(feature_counter.keys()) values.extend(feature_counter.values()) indptr.append(len(j_indices)) if not self.fixed_vocabulary_: vocabulary = dict(vocabulary) if not vocabulary: raise ValueError('empty vocabulary; perhaps the documents only contain stop words') if indptr[-1] > np.iinfo(np.int32).max: if _IS_32BIT: raise ValueError('sparse CSR array has {} non-zero elements and requires 64 bit indexing, which is unsupported with 32 bit Python.'.format(indptr[-1])) indices_dtype = np.int64 else: indices_dtype = np.int32 j_indices = np.asarray(j_indices, dtype=indices_dtype) indptr = np.asarray(indptr, dtype=indices_dtype) values = np.frombuffer(values, dtype=np.intc) X = sp.csr_matrix((values, j_indices, indptr), shape=(len(indptr) - 1, len(vocabulary)), dtype=self.dtype) X.sort_indices() (vocabulary, X) = (vocabulary, X) </DeepExtract> if self.binary: X.data.fill(1) if not self.fixed_vocabulary_: n_doc = X.shape[0] max_doc_count = max_df if isinstance(max_df, Integral) else max_df * n_doc min_doc_count = min_df if isinstance(min_df, Integral) else min_df * n_doc if max_doc_count < min_doc_count: raise ValueError('max_df corresponds to < documents than min_df') if max_features is not None: <DeepExtract> sorted_features = sorted(vocabulary.items()) map_index = np.empty(len(sorted_features), dtype=X.indices.dtype) for (new_val, (term, old_val)) in enumerate(sorted_features): vocabulary[term] = new_val map_index[old_val] = new_val X.indices = map_index.take(X.indices, mode='clip') X = X </DeepExtract> <DeepExtract> if max_doc_count is None and min_doc_count is None and (max_features is None): (X, self.stop_words_) = (X, set()) dfs = _document_frequency(X) mask = np.ones(len(dfs), dtype=bool) if max_doc_count is not None: mask &= dfs <= max_doc_count if min_doc_count is not None: mask &= dfs >= min_doc_count if max_features is not None and mask.sum() > max_features: tfs = np.asarray(X.sum(axis=0)).ravel() mask_inds = (-tfs[mask]).argsort()[:max_features] new_mask = np.zeros(len(dfs), dtype=bool) new_mask[np.where(mask)[0][mask_inds]] = True mask = new_mask new_indices = np.cumsum(mask) - 1 removed_terms = set() for (term, old_index) in list(vocabulary.items()): if mask[old_index]: vocabulary[term] = new_indices[old_index] else: del vocabulary[term] removed_terms.add(term) kept_indices = np.where(mask)[0] if len(kept_indices) == 0: raise ValueError('After pruning, no terms remain. Try a lower min_df or a higher max_df.') (X, self.stop_words_) = (X[:, kept_indices], removed_terms) </DeepExtract> if max_features is None: <DeepExtract> sorted_features = sorted(vocabulary.items()) map_index = np.empty(len(sorted_features), dtype=X.indices.dtype) for (new_val, (term, old_val)) in enumerate(sorted_features): vocabulary[term] = new_val map_index[old_val] = new_val X.indices = map_index.take(X.indices, mode='clip') X = X </DeepExtract> self.vocabulary_ = vocabulary return X
def test_no_validation(): """Check that validation can be skipped for a parameter.""" @validate_params({'param1': [int, None], 'param2': 'no_validation'}) def f(param1=None, param2=None): pass with pytest.raises(InvalidParameterError, match="The 'param1' parameter"): pass class SomeType: pass pass pass </DeepExtract>
def test_no_validation(): """Check that validation can be skipped for a parameter.""" @validate_params({'param1': [int, None], 'param2': 'no_validation'}) def f(param1=None, param2=None): pass with pytest.raises(InvalidParameterError, match="The 'param1' parameter"): <DeepExtract> pass </DeepExtract> class SomeType: pass <DeepExtract> pass </DeepExtract> <DeepExtract> pass </DeepExtract>
def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10): TreeEstimator = ALL_TREES[tree] n_samples = n_features samples = np.arange(n_samples) random_state = check_random_state(0) indices = [] data = [] offset = 0 indptr = [offset] for i in range(n_features): n_nonzero_i = random_state.binomial(n_samples, 0.5) indices_i = random_state.permutation(samples)[:n_nonzero_i] indices.append(indices_i) data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i,)) - 1 data.append(data_i) offset += n_nonzero_i indptr.append(offset) indices = np.concatenate(indices) data = np.array(np.concatenate(data), dtype=np.float32) X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features)) X = X_sparse.toarray() X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features)) X_test = X_sparse_test.toarray() y = random_state.randint(0, 3, size=(n_samples,)) X_sparse_test = X_sparse_test.copy() assert (X_sparse.data == 0.0).sum() > 0 assert (X_sparse_test.data == 0.0).sum() > 0 d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) assert s.tree_.node_count == d.tree_.node_count, '{0}: inequal number of node ({1} != {2})'.format('{0} with dense and sparse format gave different trees'.format(tree), s.tree_.node_count, d.tree_.node_count) assert_array_equal(d.tree_.children_right, s.tree_.children_right, '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal children_right') assert_array_equal(d.tree_.children_left, s.tree_.children_left, '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal children_left') external = d.tree_.children_right == TREE_LEAF internal = np.logical_not(external) assert_array_equal(d.tree_.feature[internal], s.tree_.feature[internal], '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal features') assert_array_equal(d.tree_.threshold[internal], s.tree_.threshold[internal], '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal threshold') assert_array_equal(d.tree_.n_node_samples.sum(), s.tree_.n_node_samples.sum(), '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal sum(n_node_samples)') assert_array_equal(d.tree_.n_node_samples, s.tree_.n_node_samples, '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal n_node_samples') assert_almost_equal(d.tree_.impurity, s.tree_.impurity, err_msg='{0} with dense and sparse format gave different trees'.format(tree) + ': inequal impurity') assert_array_almost_equal(d.tree_.value[external], s.tree_.value[external], err_msg='{0} with dense and sparse format gave different trees'.format(tree) + ': inequal value') Xs = (X_test, X_sparse_test) for (X1, X2) in product(Xs, Xs): assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) assert_array_almost_equal(s.apply(X1), d.apply(X2)) assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1)) assert_array_almost_equal(s.tree_.decision_path(X1).toarray(), d.tree_.decision_path(X2).toarray()) assert_array_almost_equal(s.decision_path(X1).toarray(), d.decision_path(X2).toarray()) assert_array_almost_equal(s.decision_path(X1).toarray(), s.tree_.decision_path(X1).toarray()) assert_array_almost_equal(s.predict(X1), d.predict(X2)) if tree in CLF_TREES: assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2))
def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10): TreeEstimator = ALL_TREES[tree] n_samples = n_features samples = np.arange(n_samples) random_state = check_random_state(0) indices = [] data = [] offset = 0 indptr = [offset] for i in range(n_features): n_nonzero_i = random_state.binomial(n_samples, 0.5) indices_i = random_state.permutation(samples)[:n_nonzero_i] indices.append(indices_i) data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i,)) - 1 data.append(data_i) offset += n_nonzero_i indptr.append(offset) indices = np.concatenate(indices) data = np.array(np.concatenate(data), dtype=np.float32) X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features)) X = X_sparse.toarray() X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features)) X_test = X_sparse_test.toarray() y = random_state.randint(0, 3, size=(n_samples,)) X_sparse_test = X_sparse_test.copy() assert (X_sparse.data == 0.0).sum() > 0 assert (X_sparse_test.data == 0.0).sum() > 0 d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) <DeepExtract> assert s.tree_.node_count == d.tree_.node_count, '{0}: inequal number of node ({1} != {2})'.format('{0} with dense and sparse format gave different trees'.format(tree), s.tree_.node_count, d.tree_.node_count) assert_array_equal(d.tree_.children_right, s.tree_.children_right, '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal children_right') assert_array_equal(d.tree_.children_left, s.tree_.children_left, '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal children_left') external = d.tree_.children_right == TREE_LEAF internal = np.logical_not(external) assert_array_equal(d.tree_.feature[internal], s.tree_.feature[internal], '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal features') assert_array_equal(d.tree_.threshold[internal], s.tree_.threshold[internal], '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal threshold') assert_array_equal(d.tree_.n_node_samples.sum(), s.tree_.n_node_samples.sum(), '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal sum(n_node_samples)') assert_array_equal(d.tree_.n_node_samples, s.tree_.n_node_samples, '{0} with dense and sparse format gave different trees'.format(tree) + ': inequal n_node_samples') assert_almost_equal(d.tree_.impurity, s.tree_.impurity, err_msg='{0} with dense and sparse format gave different trees'.format(tree) + ': inequal impurity') assert_array_almost_equal(d.tree_.value[external], s.tree_.value[external], err_msg='{0} with dense and sparse format gave different trees'.format(tree) + ': inequal value') </DeepExtract> Xs = (X_test, X_sparse_test) for (X1, X2) in product(Xs, Xs): assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) assert_array_almost_equal(s.apply(X1), d.apply(X2)) assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1)) assert_array_almost_equal(s.tree_.decision_path(X1).toarray(), d.tree_.decision_path(X2).toarray()) assert_array_almost_equal(s.decision_path(X1).toarray(), d.decision_path(X2).toarray()) assert_array_almost_equal(s.decision_path(X1).toarray(), s.tree_.decision_path(X1).toarray()) assert_array_almost_equal(s.predict(X1), d.predict(X2)) if tree in CLF_TREES: assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2))
def _fetch_remote(remote, dirname=None): """Helper function to download a remote dataset into path Fetch a dataset pointed by remote's url, save into path using remote's filename and ensure its integrity based on the SHA256 Checksum of the downloaded file. Parameters ---------- remote : RemoteFileMetadata Named tuple containing remote dataset meta information: url, filename and checksum dirname : str Directory to save the file to. Returns ------- file_path: str Full path of the created file. """ file_path = remote.filename if dirname is None else join(dirname, remote.filename) urlretrieve(remote.url, file_path) sha256hash = hashlib.sha256() chunk_size = 8192 with open(file_path, 'rb') as f: while True: buffer = f.read(chunk_size) if not buffer: break sha256hash.update(buffer) checksum = sha256hash.hexdigest() if remote.checksum != checksum: raise IOError('{} has an SHA256 checksum ({}) differing from expected ({}), file may be corrupted.'.format(file_path, checksum, remote.checksum)) return file_path
def _fetch_remote(remote, dirname=None): """Helper function to download a remote dataset into path Fetch a dataset pointed by remote's url, save into path using remote's filename and ensure its integrity based on the SHA256 Checksum of the downloaded file. Parameters ---------- remote : RemoteFileMetadata Named tuple containing remote dataset meta information: url, filename and checksum dirname : str Directory to save the file to. Returns ------- file_path: str Full path of the created file. """ file_path = remote.filename if dirname is None else join(dirname, remote.filename) urlretrieve(remote.url, file_path) <DeepExtract> sha256hash = hashlib.sha256() chunk_size = 8192 with open(file_path, 'rb') as f: while True: buffer = f.read(chunk_size) if not buffer: break sha256hash.update(buffer) checksum = sha256hash.hexdigest() </DeepExtract> if remote.checksum != checksum: raise IOError('{} has an SHA256 checksum ({}) differing from expected ({}), file may be corrupted.'.format(file_path, checksum, remote.checksum)) return file_path
@classmethod def from_predictions(cls, y_true, y_prob, *, n_bins=5, strategy='uniform', pos_label=None, name=None, ref_line=True, ax=None, **kwargs): """Plot calibration curve using true labels and predicted probabilities. Calibration curve, also known as reliability diagram, uses inputs from a binary classifier and plots the average predicted probability for each bin against the fraction of positive classes, on the y-axis. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Read more about calibration in the :ref:`User Guide <calibration>` and more about the scikit-learn visualization API in :ref:`visualizations`. .. versionadded:: 1.0 Parameters ---------- y_true : array-like of shape (n_samples,) True labels. y_prob : array-like of shape (n_samples,) The predicted probabilities of the positive class. n_bins : int, default=5 Number of bins to discretize the [0, 1] interval into when calculating the calibration curve. A bigger number requires more data. strategy : {'uniform', 'quantile'}, default='uniform' Strategy used to define the widths of the bins. - `'uniform'`: The bins have identical widths. - `'quantile'`: The bins have the same number of samples and depend on predicted probabilities. pos_label : str or int, default=None The positive class when computing the calibration curve. By default, `estimators.classes_[1]` is considered as the positive class. .. versionadded:: 1.1 name : str, default=None Name for labeling curve. ref_line : bool, default=True If `True`, plots a reference line representing a perfectly calibrated classifier. ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. **kwargs : dict Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. Returns ------- display : :class:`~sklearn.calibration.CalibrationDisplay`. Object that stores computed values. See Also -------- CalibrationDisplay.from_estimator : Plot calibration curve using an estimator and data. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.calibration import CalibrationDisplay >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression(random_state=0) >>> clf.fit(X_train, y_train) LogisticRegression(random_state=0) >>> y_prob = clf.predict_proba(X_test)[:, 1] >>> disp = CalibrationDisplay.from_predictions(y_test, y_prob) >>> plt.show() """ method_name = f'{cls.__name__}.from_predictions' check_matplotlib_support(method_name) target_type = type_of_target(y_true) if target_type != 'binary': raise ValueError(f'The target y is not binary. Got {target_type} type of target.') y_true = column_or_1d(y_true) y_prob = column_or_1d(y_prob) check_consistent_length(y_true, y_prob) pos_label = _check_pos_label_consistency(pos_label, y_true) if y_prob.min() < 0 or y_prob.max() > 1: raise ValueError('y_prob has values outside [0, 1].') labels = np.unique(y_true) if len(labels) > 2: raise ValueError(f'Only binary classification is supported. Provided labels {labels}.') y_true = y_true == pos_label if strategy == 'quantile': quantiles = np.linspace(0, 1, n_bins + 1) bins = np.percentile(y_prob, quantiles * 100) elif strategy == 'uniform': bins = np.linspace(0.0, 1.0, n_bins + 1) else: raise ValueError("Invalid entry to 'strategy' input. Strategy must be either 'quantile' or 'uniform'.") binids = np.searchsorted(bins[1:-1], y_prob) bin_sums = np.bincount(binids, weights=y_prob, minlength=len(bins)) bin_true = np.bincount(binids, weights=y_true, minlength=len(bins)) bin_total = np.bincount(binids, minlength=len(bins)) nonzero = bin_total != 0 prob_true = bin_true[nonzero] / bin_total[nonzero] prob_pred = bin_sums[nonzero] / bin_total[nonzero] (prob_true, prob_pred) = (prob_true, prob_pred) name = 'Classifier' if name is None else name pos_label = _check_pos_label_consistency(pos_label, y_true) disp = cls(prob_true=prob_true, prob_pred=prob_pred, y_prob=y_prob, estimator_name=name, pos_label=pos_label) return disp.plot(ax=ax, ref_line=ref_line, **kwargs)
@classmethod def from_predictions(cls, y_true, y_prob, *, n_bins=5, strategy='uniform', pos_label=None, name=None, ref_line=True, ax=None, **kwargs): """Plot calibration curve using true labels and predicted probabilities. Calibration curve, also known as reliability diagram, uses inputs from a binary classifier and plots the average predicted probability for each bin against the fraction of positive classes, on the y-axis. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Read more about calibration in the :ref:`User Guide <calibration>` and more about the scikit-learn visualization API in :ref:`visualizations`. .. versionadded:: 1.0 Parameters ---------- y_true : array-like of shape (n_samples,) True labels. y_prob : array-like of shape (n_samples,) The predicted probabilities of the positive class. n_bins : int, default=5 Number of bins to discretize the [0, 1] interval into when calculating the calibration curve. A bigger number requires more data. strategy : {'uniform', 'quantile'}, default='uniform' Strategy used to define the widths of the bins. - `'uniform'`: The bins have identical widths. - `'quantile'`: The bins have the same number of samples and depend on predicted probabilities. pos_label : str or int, default=None The positive class when computing the calibration curve. By default, `estimators.classes_[1]` is considered as the positive class. .. versionadded:: 1.1 name : str, default=None Name for labeling curve. ref_line : bool, default=True If `True`, plots a reference line representing a perfectly calibrated classifier. ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. **kwargs : dict Keyword arguments to be passed to :func:`matplotlib.pyplot.plot`. Returns ------- display : :class:`~sklearn.calibration.CalibrationDisplay`. Object that stores computed values. See Also -------- CalibrationDisplay.from_estimator : Plot calibration curve using an estimator and data. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.calibration import CalibrationDisplay >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression(random_state=0) >>> clf.fit(X_train, y_train) LogisticRegression(random_state=0) >>> y_prob = clf.predict_proba(X_test)[:, 1] >>> disp = CalibrationDisplay.from_predictions(y_test, y_prob) >>> plt.show() """ method_name = f'{cls.__name__}.from_predictions' check_matplotlib_support(method_name) target_type = type_of_target(y_true) if target_type != 'binary': raise ValueError(f'The target y is not binary. Got {target_type} type of target.') <DeepExtract> y_true = column_or_1d(y_true) y_prob = column_or_1d(y_prob) check_consistent_length(y_true, y_prob) pos_label = _check_pos_label_consistency(pos_label, y_true) if y_prob.min() < 0 or y_prob.max() > 1: raise ValueError('y_prob has values outside [0, 1].') labels = np.unique(y_true) if len(labels) > 2: raise ValueError(f'Only binary classification is supported. Provided labels {labels}.') y_true = y_true == pos_label if strategy == 'quantile': quantiles = np.linspace(0, 1, n_bins + 1) bins = np.percentile(y_prob, quantiles * 100) elif strategy == 'uniform': bins = np.linspace(0.0, 1.0, n_bins + 1) else: raise ValueError("Invalid entry to 'strategy' input. Strategy must be either 'quantile' or 'uniform'.") binids = np.searchsorted(bins[1:-1], y_prob) bin_sums = np.bincount(binids, weights=y_prob, minlength=len(bins)) bin_true = np.bincount(binids, weights=y_true, minlength=len(bins)) bin_total = np.bincount(binids, minlength=len(bins)) nonzero = bin_total != 0 prob_true = bin_true[nonzero] / bin_total[nonzero] prob_pred = bin_sums[nonzero] / bin_total[nonzero] (prob_true, prob_pred) = (prob_true, prob_pred) </DeepExtract> name = 'Classifier' if name is None else name pos_label = _check_pos_label_consistency(pos_label, y_true) disp = cls(prob_true=prob_true, prob_pred=prob_pred, y_prob=y_prob, estimator_name=name, pos_label=pos_label) return disp.plot(ax=ax, ref_line=ref_line, **kwargs)
def test_underflow_or_overlow(): with np.errstate(all='raise'): rng = np.random.RandomState(0) n_samples = 100 n_features = 10 X = rng.normal(size=(n_samples, n_features)) X[:, :2] *= 1e+300 assert np.isfinite(X).all() X_scaled = MinMaxScaler().fit_transform(X) assert np.isfinite(X_scaled).all() ground_truth = rng.normal(size=n_features) y = (np.dot(X_scaled, ground_truth) > 0.0).astype(np.int32) assert_array_equal(np.unique(y), [0, 1]) _update_kwargs(kwargs) model = linear_model.SGDClassifier(**kwargs) model.fit(X_scaled, y) assert np.isfinite(model.coef_).all() msg_regxp = 'Floating-point under-/overflow occurred at epoch #.* Scaling input data with StandardScaler or MinMaxScaler might help.' with pytest.raises(ValueError, match=msg_regxp): model.fit(X, y)
def test_underflow_or_overlow(): with np.errstate(all='raise'): rng = np.random.RandomState(0) n_samples = 100 n_features = 10 X = rng.normal(size=(n_samples, n_features)) X[:, :2] *= 1e+300 assert np.isfinite(X).all() X_scaled = MinMaxScaler().fit_transform(X) assert np.isfinite(X_scaled).all() ground_truth = rng.normal(size=n_features) y = (np.dot(X_scaled, ground_truth) > 0.0).astype(np.int32) assert_array_equal(np.unique(y), [0, 1]) <DeepExtract> _update_kwargs(kwargs) model = linear_model.SGDClassifier(**kwargs) </DeepExtract> model.fit(X_scaled, y) assert np.isfinite(model.coef_).all() msg_regxp = 'Floating-point under-/overflow occurred at epoch #.* Scaling input data with StandardScaler or MinMaxScaler might help.' with pytest.raises(ValueError, match=msg_regxp): model.fit(X, y)
def test_classification_report_multiclass(): iris = datasets.load_iris() if iris is None: iris = datasets.load_iris() X = iris.data y = iris.target if False: (X, y) = (X[y < 2], y[y < 2]) (n_samples, n_features) = X.shape p = np.arange(n_samples) rng = check_random_state(37) rng.shuffle(p) (X, y) = (X[p], y[p]) half = int(n_samples / 2) rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)] clf = svm.SVC(kernel='linear', probability=True, random_state=0) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if False: probas_pred = probas_pred[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] (y_true, y_pred, _) = (y_true, y_pred, probas_pred) expected_report = ' precision recall f1-score support\n\n setosa 0.83 0.79 0.81 24\n versicolor 0.33 0.10 0.15 31\n virginica 0.42 0.90 0.57 20\n\n accuracy 0.53 75\n macro avg 0.53 0.60 0.51 75\nweighted avg 0.51 0.53 0.47 75\n' report = classification_report(y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names) assert report == expected_report
def test_classification_report_multiclass(): iris = datasets.load_iris() <DeepExtract> if iris is None: iris = datasets.load_iris() X = iris.data y = iris.target if False: (X, y) = (X[y < 2], y[y < 2]) (n_samples, n_features) = X.shape p = np.arange(n_samples) rng = check_random_state(37) rng.shuffle(p) (X, y) = (X[p], y[p]) half = int(n_samples / 2) rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)] clf = svm.SVC(kernel='linear', probability=True, random_state=0) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if False: probas_pred = probas_pred[:, 1] y_pred = clf.predict(X[half:]) y_true = y[half:] (y_true, y_pred, _) = (y_true, y_pred, probas_pred) </DeepExtract> expected_report = ' precision recall f1-score support\n\n setosa 0.83 0.79 0.81 24\n versicolor 0.33 0.10 0.15 31\n virginica 0.42 0.90 0.57 20\n\n accuracy 0.53 75\n macro avg 0.53 0.60 0.51 75\nweighted avg 0.51 0.53 0.47 75\n' report = classification_report(y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names) assert report == expected_report
@pytest.mark.parametrize('name', sorted((MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT)) def test_multilabel_sample_weight_invariance(name): random_state = check_random_state(0) (_, ya) = make_multilabel_classification(n_features=1, n_classes=10, random_state=0, n_samples=50, allow_unlabeled=False) (_, yb) = make_multilabel_classification(n_features=1, n_classes=10, random_state=1, n_samples=50, allow_unlabeled=False) y_true = np.vstack([ya, yb]) y_pred = np.vstack([ya, ya]) y_score = random_state.randint(1, 4, size=y_true.shape) metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y_true)) metric = partial(metric, k=1) if name == 'top_k_accuracy_score' else metric unweighted_score = metric(y_true, y_score, sample_weight=None) assert_allclose(unweighted_score, metric(y_true, y_score, sample_weight=np.ones(shape=len(y_true))), err_msg='For %s sample_weight=None is not equivalent to sample_weight=ones' % name) weighted_score = metric(y_true, y_score, sample_weight=sample_weight) with pytest.raises(AssertionError): assert_allclose(unweighted_score, weighted_score) raise ValueError('Unweighted and weighted scores are unexpectedly almost equal (%s) and (%s) for %s' % (unweighted_score, weighted_score, name)) weighted_score_list = metric(y_true, y_score, sample_weight=sample_weight.tolist()) assert_allclose(weighted_score, weighted_score_list, err_msg='Weighted scores for array and list sample_weight input are not equal (%s != %s) for %s' % (weighted_score, weighted_score_list, name)) repeat_weighted_score = metric(np.repeat(y_true, sample_weight, axis=0), np.repeat(y_score, sample_weight, axis=0), sample_weight=None) assert_allclose(weighted_score, repeat_weighted_score, err_msg='Weighting %s is not equal to repeating samples' % name) sample_weight_subset = sample_weight[1::2] sample_weight_zeroed = np.copy(sample_weight) sample_weight_zeroed[::2] = 0 y1_subset = y_true[1::2] y2_subset = y_score[1::2] weighted_score_subset = metric(y1_subset, y2_subset, sample_weight=sample_weight_subset) weighted_score_zeroed = metric(y_true, y_score, sample_weight=sample_weight_zeroed) assert_allclose(weighted_score_subset, weighted_score_zeroed, err_msg='Zeroing weights does not give the same result as removing the corresponding samples (%s != %s) for %s' % (weighted_score_zeroed, weighted_score_subset, name)) if not name.startswith('unnormalized'): for scaling in [2, 0.3]: assert_allclose(weighted_score, metric(y_true, y_score, sample_weight=sample_weight * scaling), err_msg='%s sample_weight is not invariant under scaling' % name) error_message = 'Found input variables with inconsistent numbers of samples: \\[{}, {}, {}\\]'.format(_num_samples(y_true), _num_samples(y_score), _num_samples(sample_weight) * 2) with pytest.raises(ValueError, match=error_message): metric(y_true, y_score, sample_weight=np.hstack([sample_weight, sample_weight])) else: rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y_true)) metric = partial(metric, k=1) if name == 'top_k_accuracy_score' else metric unweighted_score = metric(y_true, y_pred, sample_weight=None) assert_allclose(unweighted_score, metric(y_true, y_pred, sample_weight=np.ones(shape=len(y_true))), err_msg='For %s sample_weight=None is not equivalent to sample_weight=ones' % name) weighted_score = metric(y_true, y_pred, sample_weight=sample_weight) with pytest.raises(AssertionError): assert_allclose(unweighted_score, weighted_score) raise ValueError('Unweighted and weighted scores are unexpectedly almost equal (%s) and (%s) for %s' % (unweighted_score, weighted_score, name)) weighted_score_list = metric(y_true, y_pred, sample_weight=sample_weight.tolist()) assert_allclose(weighted_score, weighted_score_list, err_msg='Weighted scores for array and list sample_weight input are not equal (%s != %s) for %s' % (weighted_score, weighted_score_list, name)) repeat_weighted_score = metric(np.repeat(y_true, sample_weight, axis=0), np.repeat(y_pred, sample_weight, axis=0), sample_weight=None) assert_allclose(weighted_score, repeat_weighted_score, err_msg='Weighting %s is not equal to repeating samples' % name) sample_weight_subset = sample_weight[1::2] sample_weight_zeroed = np.copy(sample_weight) sample_weight_zeroed[::2] = 0 y1_subset = y_true[1::2] y2_subset = y_pred[1::2] weighted_score_subset = metric(y1_subset, y2_subset, sample_weight=sample_weight_subset) weighted_score_zeroed = metric(y_true, y_pred, sample_weight=sample_weight_zeroed) assert_allclose(weighted_score_subset, weighted_score_zeroed, err_msg='Zeroing weights does not give the same result as removing the corresponding samples (%s != %s) for %s' % (weighted_score_zeroed, weighted_score_subset, name)) if not name.startswith('unnormalized'): for scaling in [2, 0.3]: assert_allclose(weighted_score, metric(y_true, y_pred, sample_weight=sample_weight * scaling), err_msg='%s sample_weight is not invariant under scaling' % name) error_message = 'Found input variables with inconsistent numbers of samples: \\[{}, {}, {}\\]'.format(_num_samples(y_true), _num_samples(y_pred), _num_samples(sample_weight) * 2) with pytest.raises(ValueError, match=error_message): metric(y_true, y_pred, sample_weight=np.hstack([sample_weight, sample_weight])) </DeepExtract>
@pytest.mark.parametrize('name', sorted((MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT)) def test_multilabel_sample_weight_invariance(name): random_state = check_random_state(0) (_, ya) = make_multilabel_classification(n_features=1, n_classes=10, random_state=0, n_samples=50, allow_unlabeled=False) (_, yb) = make_multilabel_classification(n_features=1, n_classes=10, random_state=1, n_samples=50, allow_unlabeled=False) y_true = np.vstack([ya, yb]) y_pred = np.vstack([ya, ya]) y_score = random_state.randint(1, 4, size=y_true.shape) metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: <DeepExtract> rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y_true)) metric = partial(metric, k=1) if name == 'top_k_accuracy_score' else metric unweighted_score = metric(y_true, y_score, sample_weight=None) assert_allclose(unweighted_score, metric(y_true, y_score, sample_weight=np.ones(shape=len(y_true))), err_msg='For %s sample_weight=None is not equivalent to sample_weight=ones' % name) weighted_score = metric(y_true, y_score, sample_weight=sample_weight) with pytest.raises(AssertionError): assert_allclose(unweighted_score, weighted_score) raise ValueError('Unweighted and weighted scores are unexpectedly almost equal (%s) and (%s) for %s' % (unweighted_score, weighted_score, name)) weighted_score_list = metric(y_true, y_score, sample_weight=sample_weight.tolist()) assert_allclose(weighted_score, weighted_score_list, err_msg='Weighted scores for array and list sample_weight input are not equal (%s != %s) for %s' % (weighted_score, weighted_score_list, name)) repeat_weighted_score = metric(np.repeat(y_true, sample_weight, axis=0), np.repeat(y_score, sample_weight, axis=0), sample_weight=None) assert_allclose(weighted_score, repeat_weighted_score, err_msg='Weighting %s is not equal to repeating samples' % name) sample_weight_subset = sample_weight[1::2] sample_weight_zeroed = np.copy(sample_weight) sample_weight_zeroed[::2] = 0 y1_subset = y_true[1::2] y2_subset = y_score[1::2] weighted_score_subset = metric(y1_subset, y2_subset, sample_weight=sample_weight_subset) weighted_score_zeroed = metric(y_true, y_score, sample_weight=sample_weight_zeroed) assert_allclose(weighted_score_subset, weighted_score_zeroed, err_msg='Zeroing weights does not give the same result as removing the corresponding samples (%s != %s) for %s' % (weighted_score_zeroed, weighted_score_subset, name)) if not name.startswith('unnormalized'): for scaling in [2, 0.3]: assert_allclose(weighted_score, metric(y_true, y_score, sample_weight=sample_weight * scaling), err_msg='%s sample_weight is not invariant under scaling' % name) error_message = 'Found input variables with inconsistent numbers of samples: \\[{}, {}, {}\\]'.format(_num_samples(y_true), _num_samples(y_score), _num_samples(sample_weight) * 2) with pytest.raises(ValueError, match=error_message): metric(y_true, y_score, sample_weight=np.hstack([sample_weight, sample_weight])) </DeepExtract> else: <DeepExtract> rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y_true)) metric = partial(metric, k=1) if name == 'top_k_accuracy_score' else metric unweighted_score = metric(y_true, y_pred, sample_weight=None) assert_allclose(unweighted_score, metric(y_true, y_pred, sample_weight=np.ones(shape=len(y_true))), err_msg='For %s sample_weight=None is not equivalent to sample_weight=ones' % name) weighted_score = metric(y_true, y_pred, sample_weight=sample_weight) with pytest.raises(AssertionError): assert_allclose(unweighted_score, weighted_score) raise ValueError('Unweighted and weighted scores are unexpectedly almost equal (%s) and (%s) for %s' % (unweighted_score, weighted_score, name)) weighted_score_list = metric(y_true, y_pred, sample_weight=sample_weight.tolist()) assert_allclose(weighted_score, weighted_score_list, err_msg='Weighted scores for array and list sample_weight input are not equal (%s != %s) for %s' % (weighted_score, weighted_score_list, name)) repeat_weighted_score = metric(np.repeat(y_true, sample_weight, axis=0), np.repeat(y_pred, sample_weight, axis=0), sample_weight=None) assert_allclose(weighted_score, repeat_weighted_score, err_msg='Weighting %s is not equal to repeating samples' % name) sample_weight_subset = sample_weight[1::2] sample_weight_zeroed = np.copy(sample_weight) sample_weight_zeroed[::2] = 0 y1_subset = y_true[1::2] y2_subset = y_pred[1::2] weighted_score_subset = metric(y1_subset, y2_subset, sample_weight=sample_weight_subset) weighted_score_zeroed = metric(y_true, y_pred, sample_weight=sample_weight_zeroed) assert_allclose(weighted_score_subset, weighted_score_zeroed, err_msg='Zeroing weights does not give the same result as removing the corresponding samples (%s != %s) for %s' % (weighted_score_zeroed, weighted_score_subset, name)) if not name.startswith('unnormalized'): for scaling in [2, 0.3]: assert_allclose(weighted_score, metric(y_true, y_pred, sample_weight=sample_weight * scaling), err_msg='%s sample_weight is not invariant under scaling' % name) error_message = 'Found input variables with inconsistent numbers of samples: \\[{}, {}, {}\\]'.format(_num_samples(y_true), _num_samples(y_pred), _num_samples(sample_weight) * 2) with pytest.raises(ValueError, match=error_message): metric(y_true, y_pred, sample_weight=np.hstack([sample_weight, sample_weight])) </DeepExtract>
def pairwise_distances_argmin(X, Y, *, axis=1, metric='euclidean', metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equivalent to calling: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Array containing points. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Arrays containing points. axis : int, default=1 Axis along which the argmin and distances are to be computed. metric : str or callable, default="euclidean" Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. .. note:: `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. metric_kwargs : dict, default=None Keyword arguments to pass to specified metric function. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See Also -------- pairwise_distances : Distances between every pair of samples of X and Y. pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also returns the distances. """ if metric_kwargs is None: metric_kwargs = {} (X, Y, dtype_float) = _return_float_dtype(X, Y) estimator = 'check_pairwise_arrays' if dtype is None: dtype = dtype_float if Y is X or Y is None: X = Y = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) else: X = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) Y = check_array(Y, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) if precomputed: if X.shape[1] != Y.shape[0]: raise ValueError('Precomputed metric requires shape (n_queries, n_indexed). Got (%d, %d) for %d indexed.' % (X.shape[0], X.shape[1], Y.shape[0])) elif X.shape[1] != Y.shape[1]: raise ValueError('Incompatible dimension for X and Y matrices: X.shape[1] == %d while Y.shape[1] == %d' % (X.shape[1], Y.shape[1])) (X, Y) = (X, Y) if axis == 0: (X, Y) = (Y, X) if metric_kwargs is None: metric_kwargs = {} if ArgKmin.is_usable_for(X, Y, metric): if metric_kwargs.get('squared', False) and metric == 'euclidean': metric = 'sqeuclidean' metric_kwargs = {} indices = ArgKmin.compute(X=X, Y=Y, k=1, metric=metric, metric_kwargs=metric_kwargs, strategy='auto', return_distance=False) indices = indices.flatten() else: with config_context(assume_finite=True): indices = np.concatenate(list(pairwise_distances_chunked(X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs))) return indices
def pairwise_distances_argmin(X, Y, *, axis=1, metric='euclidean', metric_kwargs=None): """Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). This is mostly equivalent to calling: pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) but uses much less memory, and is faster for large arrays. This function works with dense 2D arrays only. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples_X, n_features) Array containing points. Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) Arrays containing points. axis : int, default=1 Axis along which the argmin and distances are to be computed. metric : str or callable, default="euclidean" Metric to use for distance computation. Any metric from scikit-learn or scipy.spatial.distance can be used. If metric is a callable function, it is called on each pair of instances (rows) and the resulting value recorded. The callable should take two arrays as input and return one value indicating the distance between them. This works for Scipy's metrics, but is less efficient than passing the metric name as a string. Distance matrices are not supported. Valid values for metric are: - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan'] - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] See the documentation for scipy.spatial.distance for details on these metrics. .. note:: `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. metric_kwargs : dict, default=None Keyword arguments to pass to specified metric function. Returns ------- argmin : numpy.ndarray Y[argmin[i], :] is the row in Y that is closest to X[i, :]. See Also -------- pairwise_distances : Distances between every pair of samples of X and Y. pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also returns the distances. """ if metric_kwargs is None: metric_kwargs = {} <DeepExtract> (X, Y, dtype_float) = _return_float_dtype(X, Y) estimator = 'check_pairwise_arrays' if dtype is None: dtype = dtype_float if Y is X or Y is None: X = Y = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) else: X = check_array(X, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) Y = check_array(Y, accept_sparse=accept_sparse, dtype=dtype, copy=copy, force_all_finite=force_all_finite, estimator=estimator) if precomputed: if X.shape[1] != Y.shape[0]: raise ValueError('Precomputed metric requires shape (n_queries, n_indexed). Got (%d, %d) for %d indexed.' % (X.shape[0], X.shape[1], Y.shape[0])) elif X.shape[1] != Y.shape[1]: raise ValueError('Incompatible dimension for X and Y matrices: X.shape[1] == %d while Y.shape[1] == %d' % (X.shape[1], Y.shape[1])) (X, Y) = (X, Y) </DeepExtract> if axis == 0: (X, Y) = (Y, X) if metric_kwargs is None: metric_kwargs = {} if ArgKmin.is_usable_for(X, Y, metric): if metric_kwargs.get('squared', False) and metric == 'euclidean': metric = 'sqeuclidean' metric_kwargs = {} indices = ArgKmin.compute(X=X, Y=Y, k=1, metric=metric, metric_kwargs=metric_kwargs, strategy='auto', return_distance=False) indices = indices.flatten() else: with config_context(assume_finite=True): indices = np.concatenate(list(pairwise_distances_chunked(X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs))) return indices