before
stringlengths
87
36.6k
after
stringlengths
116
37.2k
def _fit_full(self, X, n_components): """Fit the model by computing full SVD on X.""" (n_samples, n_features) = X.shape if n_components == 'mle': if n_samples < n_features: raise ValueError("n_components='mle' is only supported if n_samples >= n_features") elif not 0 <= n_components <= min(n_samples, n_features): raise ValueError("n_components=%r must be between 0 and min(n_samples, n_features)=%r with svd_solver='full'" % (n_components, min(n_samples, n_features))) self.mean_ = np.mean(X, axis=0) X -= self.mean_ (U, S, Vt) = linalg.svd(X, full_matrices=False) (U, Vt) = svd_flip(U, Vt) components_ = Vt explained_variance_ = S ** 2 / (n_samples - 1) total_var = explained_variance_.sum() explained_variance_ratio_ = explained_variance_ / total_var singular_values_ = S.copy() if n_components == 'mle': ll = np.empty_like(explained_variance_) ll[0] = -np.inf for rank in range(1, explained_variance_.shape[0]): ll[rank] = _assess_dimension(explained_variance_, rank, n_samples) n_components = ll.argmax() elif 0 < n_components < 1.0: ratio_cumsum = stable_cumsum(explained_variance_ratio_) n_components = np.searchsorted(ratio_cumsum, n_components, side='right') + 1 if n_components < min(n_features, n_samples): self.noise_variance_ = explained_variance_[n_components:].mean() else: self.noise_variance_ = 0.0 self.n_samples_ = n_samples self.components_ = components_[:n_components] self.n_components_ = n_components self.explained_variance_ = explained_variance_[:n_components] self.explained_variance_ratio_ = explained_variance_ratio_[:n_components] self.singular_values_ = singular_values_[:n_components] return (U, S, Vt)
def _fit_full(self, X, n_components): """Fit the model by computing full SVD on X.""" (n_samples, n_features) = X.shape if n_components == 'mle': if n_samples < n_features: raise ValueError("n_components='mle' is only supported if n_samples >= n_features") elif not 0 <= n_components <= min(n_samples, n_features): raise ValueError("n_components=%r must be between 0 and min(n_samples, n_features)=%r with svd_solver='full'" % (n_components, min(n_samples, n_features))) self.mean_ = np.mean(X, axis=0) X -= self.mean_ (U, S, Vt) = linalg.svd(X, full_matrices=False) (U, Vt) = svd_flip(U, Vt) components_ = Vt explained_variance_ = S ** 2 / (n_samples - 1) total_var = explained_variance_.sum() explained_variance_ratio_ = explained_variance_ / total_var singular_values_ = S.copy() if n_components == 'mle': <DeepExtract> ll = np.empty_like(explained_variance_) ll[0] = -np.inf for rank in range(1, explained_variance_.shape[0]): ll[rank] = _assess_dimension(explained_variance_, rank, n_samples) n_components = ll.argmax() </DeepExtract> elif 0 < n_components < 1.0: ratio_cumsum = stable_cumsum(explained_variance_ratio_) n_components = np.searchsorted(ratio_cumsum, n_components, side='right') + 1 if n_components < min(n_features, n_samples): self.noise_variance_ = explained_variance_[n_components:].mean() else: self.noise_variance_ = 0.0 self.n_samples_ = n_samples self.components_ = components_[:n_components] self.n_components_ = n_components self.explained_variance_ = explained_variance_[:n_components] self.explained_variance_ratio_ = explained_variance_ratio_[:n_components] self.singular_values_ = singular_values_[:n_components] return (U, S, Vt)
def test_roc_returns_consistency(): 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) (fpr, tpr, thresholds) = roc_curve(y_true, y_score) tpr_correct = [] for t in thresholds: tp = np.sum((y_score >= t) & y_true) p = np.sum(y_true) tpr_correct.append(1.0 * tp / p) assert_array_almost_equal(tpr, tpr_correct, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def test_roc_returns_consistency(): <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> (fpr, tpr, thresholds) = roc_curve(y_true, y_score) tpr_correct = [] for t in thresholds: tp = np.sum((y_score >= t) & y_true) p = np.sum(y_true) tpr_correct.append(1.0 * tp / p) assert_array_almost_equal(tpr, tpr_correct, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def fetch_rcv1(*, data_home=None, subset='all', download_if_missing=True, random_state=None, shuffle=False, return_X_y=False): """Load the RCV1 multilabel dataset (classification). Download it if necessary. Version: RCV1-v2, vectors, full sets, topics multilabels. ================= ===================== Classes 103 Samples total 804414 Dimensionality 47236 Features real, between 0 and 1 ================= ===================== Read more in the :ref:`User Guide <rcv1_dataset>`. .. versionadded:: 0.17 Parameters ---------- data_home : str, default=None Specify another download and cache folder for the datasets. By default all scikit-learn data is stored in '~/scikit_learn_data' subfolders. subset : {'train', 'test', 'all'}, default='all' Select the dataset to load: 'train' for the training set (23149 samples), 'test' for the test set (781265 samples), 'all' for both, with the training samples first if shuffle is False. This follows the official LYRL2004 chronological split. download_if_missing : bool, default=True If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. random_state : int, RandomState instance or None, default=None Determines random number generation for dataset shuffling. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. shuffle : bool, default=False Whether to shuffle dataset. return_X_y : bool, default=False If True, returns ``(dataset.data, dataset.target)`` instead of a Bunch object. See below for more information about the `dataset.data` and `dataset.target` object. .. versionadded:: 0.20 Returns ------- dataset : :class:`~sklearn.utils.Bunch` Dictionary-like object. Returned only if `return_X_y` is False. `dataset` has the following attributes: - data : sparse matrix of shape (804414, 47236), dtype=np.float64 The array has 0.16% of non zero values. Will be of CSR format. - target : sparse matrix of shape (804414, 103), dtype=np.uint8 Each sample has a value of 1 in its categories, and 0 in others. The array has 3.15% of non zero values. Will be of CSR format. - sample_id : ndarray of shape (804414,), dtype=np.uint32, Identification number of each sample, as ordered in dataset.data. - target_names : ndarray of shape (103,), dtype=object Names of each target (RCV1 topics), as ordered in dataset.target. - DESCR : str Description of the RCV1 dataset. (data, target) : tuple A tuple consisting of `dataset.data` and `dataset.target`, as described above. Returned only if `return_X_y` is True. .. versionadded:: 0.20 """ N_SAMPLES = 804414 N_FEATURES = 47236 N_CATEGORIES = 103 N_TRAIN = 23149 data_home = get_data_home(data_home=data_home) rcv1_dir = join(data_home, 'RCV1') if download_if_missing: if not exists(rcv1_dir): makedirs(rcv1_dir) samples_path = _pkl_filepath(rcv1_dir, 'samples.pkl') sample_id_path = _pkl_filepath(rcv1_dir, 'sample_id.pkl') sample_topics_path = _pkl_filepath(rcv1_dir, 'sample_topics.pkl') topics_path = _pkl_filepath(rcv1_dir, 'topics_names.pkl') if download_if_missing and (not exists(samples_path) or not exists(sample_id_path)): files = [] for each in XY_METADATA: logger.info('Downloading %s' % each.url) file_path = _fetch_remote(each, dirname=rcv1_dir) files.append(GzipFile(filename=file_path)) Xy = load_svmlight_files(files, n_features=N_FEATURES) X = sp.vstack([Xy[8], Xy[0], Xy[2], Xy[4], Xy[6]]).tocsr() sample_id = np.hstack((Xy[9], Xy[1], Xy[3], Xy[5], Xy[7])) sample_id = sample_id.astype(np.uint32, copy=False) joblib.dump(X, samples_path, compress=9) joblib.dump(sample_id, sample_id_path, compress=9) for f in files: f.close() remove(f.name) else: X = joblib.load(samples_path) sample_id = joblib.load(sample_id_path) if download_if_missing and (not exists(sample_topics_path) or not exists(topics_path)): logger.info('Downloading %s' % TOPICS_METADATA.url) topics_archive_path = _fetch_remote(TOPICS_METADATA, dirname=rcv1_dir) n_cat = -1 n_doc = -1 doc_previous = -1 y = np.zeros((N_SAMPLES, N_CATEGORIES), dtype=np.uint8) sample_id_bis = np.zeros(N_SAMPLES, dtype=np.int32) category_names = {} with GzipFile(filename=topics_archive_path, mode='rb') as f: for line in f: line_components = line.decode('ascii').split(' ') if len(line_components) == 3: (cat, doc, _) = line_components if cat not in category_names: n_cat += 1 category_names[cat] = n_cat doc = int(doc) if doc != doc_previous: doc_previous = doc n_doc += 1 sample_id_bis[n_doc] = doc y[n_doc, category_names[cat]] = 1 remove(topics_archive_path) t = np.argsort(sample_id_bis) u = np.argsort(sample_id) u_ = _inverse_permutation(u) permutation = t[u_] y = y[permutation, :] categories = np.empty(N_CATEGORIES, dtype=object) for k in category_names.keys(): categories[category_names[k]] = k order = np.argsort(categories) categories = categories[order] y = sp.csr_matrix(y[:, order]) joblib.dump(y, sample_topics_path, compress=9) joblib.dump(categories, topics_path, compress=9) else: y = joblib.load(sample_topics_path) categories = joblib.load(topics_path) if subset == 'all': pass elif subset == 'train': X = X[:N_TRAIN, :] y = y[:N_TRAIN, :] sample_id = sample_id[:N_TRAIN] elif subset == 'test': X = X[N_TRAIN:, :] y = y[N_TRAIN:, :] sample_id = sample_id[N_TRAIN:] else: raise ValueError("Unknown subset parameter. Got '%s' instead of one of ('all', 'train', test')" % subset) if shuffle: (X, y, sample_id) = shuffle_(X, y, sample_id, random_state=random_state) fdescr = load_descr('rcv1.rst') if return_X_y: return (X, y) return Bunch(data=X, target=y, sample_id=sample_id, target_names=categories, DESCR=fdescr)
def fetch_rcv1(*, data_home=None, subset='all', download_if_missing=True, random_state=None, shuffle=False, return_X_y=False): """Load the RCV1 multilabel dataset (classification). Download it if necessary. Version: RCV1-v2, vectors, full sets, topics multilabels. ================= ===================== Classes 103 Samples total 804414 Dimensionality 47236 Features real, between 0 and 1 ================= ===================== Read more in the :ref:`User Guide <rcv1_dataset>`. .. versionadded:: 0.17 Parameters ---------- data_home : str, default=None Specify another download and cache folder for the datasets. By default all scikit-learn data is stored in '~/scikit_learn_data' subfolders. subset : {'train', 'test', 'all'}, default='all' Select the dataset to load: 'train' for the training set (23149 samples), 'test' for the test set (781265 samples), 'all' for both, with the training samples first if shuffle is False. This follows the official LYRL2004 chronological split. download_if_missing : bool, default=True If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. random_state : int, RandomState instance or None, default=None Determines random number generation for dataset shuffling. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. shuffle : bool, default=False Whether to shuffle dataset. return_X_y : bool, default=False If True, returns ``(dataset.data, dataset.target)`` instead of a Bunch object. See below for more information about the `dataset.data` and `dataset.target` object. .. versionadded:: 0.20 Returns ------- dataset : :class:`~sklearn.utils.Bunch` Dictionary-like object. Returned only if `return_X_y` is False. `dataset` has the following attributes: - data : sparse matrix of shape (804414, 47236), dtype=np.float64 The array has 0.16% of non zero values. Will be of CSR format. - target : sparse matrix of shape (804414, 103), dtype=np.uint8 Each sample has a value of 1 in its categories, and 0 in others. The array has 3.15% of non zero values. Will be of CSR format. - sample_id : ndarray of shape (804414,), dtype=np.uint32, Identification number of each sample, as ordered in dataset.data. - target_names : ndarray of shape (103,), dtype=object Names of each target (RCV1 topics), as ordered in dataset.target. - DESCR : str Description of the RCV1 dataset. (data, target) : tuple A tuple consisting of `dataset.data` and `dataset.target`, as described above. Returned only if `return_X_y` is True. .. versionadded:: 0.20 """ N_SAMPLES = 804414 N_FEATURES = 47236 N_CATEGORIES = 103 N_TRAIN = 23149 data_home = get_data_home(data_home=data_home) rcv1_dir = join(data_home, 'RCV1') if download_if_missing: if not exists(rcv1_dir): makedirs(rcv1_dir) samples_path = _pkl_filepath(rcv1_dir, 'samples.pkl') sample_id_path = _pkl_filepath(rcv1_dir, 'sample_id.pkl') sample_topics_path = _pkl_filepath(rcv1_dir, 'sample_topics.pkl') topics_path = _pkl_filepath(rcv1_dir, 'topics_names.pkl') if download_if_missing and (not exists(samples_path) or not exists(sample_id_path)): files = [] for each in XY_METADATA: logger.info('Downloading %s' % each.url) file_path = _fetch_remote(each, dirname=rcv1_dir) files.append(GzipFile(filename=file_path)) Xy = load_svmlight_files(files, n_features=N_FEATURES) X = sp.vstack([Xy[8], Xy[0], Xy[2], Xy[4], Xy[6]]).tocsr() sample_id = np.hstack((Xy[9], Xy[1], Xy[3], Xy[5], Xy[7])) sample_id = sample_id.astype(np.uint32, copy=False) joblib.dump(X, samples_path, compress=9) joblib.dump(sample_id, sample_id_path, compress=9) for f in files: f.close() remove(f.name) else: X = joblib.load(samples_path) sample_id = joblib.load(sample_id_path) if download_if_missing and (not exists(sample_topics_path) or not exists(topics_path)): logger.info('Downloading %s' % TOPICS_METADATA.url) topics_archive_path = _fetch_remote(TOPICS_METADATA, dirname=rcv1_dir) n_cat = -1 n_doc = -1 doc_previous = -1 y = np.zeros((N_SAMPLES, N_CATEGORIES), dtype=np.uint8) sample_id_bis = np.zeros(N_SAMPLES, dtype=np.int32) category_names = {} with GzipFile(filename=topics_archive_path, mode='rb') as f: for line in f: line_components = line.decode('ascii').split(' ') if len(line_components) == 3: (cat, doc, _) = line_components if cat not in category_names: n_cat += 1 category_names[cat] = n_cat doc = int(doc) if doc != doc_previous: doc_previous = doc n_doc += 1 sample_id_bis[n_doc] = doc y[n_doc, category_names[cat]] = 1 remove(topics_archive_path) <DeepExtract> t = np.argsort(sample_id_bis) u = np.argsort(sample_id) u_ = _inverse_permutation(u) permutation = t[u_] </DeepExtract> y = y[permutation, :] categories = np.empty(N_CATEGORIES, dtype=object) for k in category_names.keys(): categories[category_names[k]] = k order = np.argsort(categories) categories = categories[order] y = sp.csr_matrix(y[:, order]) joblib.dump(y, sample_topics_path, compress=9) joblib.dump(categories, topics_path, compress=9) else: y = joblib.load(sample_topics_path) categories = joblib.load(topics_path) if subset == 'all': pass elif subset == 'train': X = X[:N_TRAIN, :] y = y[:N_TRAIN, :] sample_id = sample_id[:N_TRAIN] elif subset == 'test': X = X[N_TRAIN:, :] y = y[N_TRAIN:, :] sample_id = sample_id[N_TRAIN:] else: raise ValueError("Unknown subset parameter. Got '%s' instead of one of ('all', 'train', test')" % subset) if shuffle: (X, y, sample_id) = shuffle_(X, y, sample_id, random_state=random_state) fdescr = load_descr('rcv1.rst') if return_X_y: return (X, y) return Bunch(data=X, target=y, sample_id=sample_id, target_names=categories, DESCR=fdescr)
def _multiplicative_update_w(X, W, H, beta_loss, l1_reg_W, l2_reg_W, gamma, H_sum=None, HHt=None, XHt=None, update_H=True): """Update W in Multiplicative Update NMF.""" if beta_loss == 2: if XHt is None: XHt = safe_sparse_dot(X, H.T) if update_H: numerator = XHt else: numerator = XHt.copy() if HHt is None: HHt = np.dot(H, H.T) denominator = np.dot(W, HHt) else: if sp.issparse(X): (ii, jj) = X.nonzero() n_vals = ii.shape[0] dot_vals = np.empty(n_vals) n_components = W.shape[1] batch_size = max(n_components, n_vals // n_components) for start in range(0, n_vals, batch_size): batch = slice(start, start + batch_size) dot_vals[batch] = np.multiply(W[ii[batch], :], H.T[jj[batch], :]).sum(axis=1) WH = sp.coo_matrix((dot_vals, (ii, jj)), shape=X.shape) WH_safe_X = WH.tocsr() else: WH_safe_X = np.dot(W, H) if sp.issparse(X): WH_safe_X_data = WH_safe_X.data X_data = X.data else: WH_safe_X_data = WH_safe_X X_data = X WH = WH_safe_X.copy() if beta_loss - 1.0 < 0: WH[WH < EPSILON] = EPSILON if beta_loss - 2.0 < 0: WH_safe_X_data[WH_safe_X_data < EPSILON] = EPSILON if beta_loss == 1: np.divide(X_data, WH_safe_X_data, out=WH_safe_X_data) elif beta_loss == 0: WH_safe_X_data **= -1 WH_safe_X_data **= 2 WH_safe_X_data *= X_data else: WH_safe_X_data **= beta_loss - 2 WH_safe_X_data *= X_data numerator = safe_sparse_dot(WH_safe_X, H.T) if beta_loss == 1: if H_sum is None: H_sum = np.sum(H, axis=1) denominator = H_sum[np.newaxis, :] else: if sp.issparse(X): WHHt = np.empty(W.shape) for i in range(X.shape[0]): WHi = np.dot(W[i, :], H) if beta_loss - 1 < 0: WHi[WHi < EPSILON] = EPSILON WHi **= beta_loss - 1 WHHt[i, :] = np.dot(WHi, H.T) else: WH **= beta_loss - 1 WHHt = np.dot(WH, H.T) denominator = WHHt if l1_reg_W > 0: denominator += l1_reg_W if l2_reg_W > 0: denominator = denominator + l2_reg_W * W denominator[denominator == 0] = EPSILON numerator /= denominator delta_W = numerator if gamma != 1: delta_W **= gamma W *= delta_W return (W, H_sum, HHt, XHt)
def _multiplicative_update_w(X, W, H, beta_loss, l1_reg_W, l2_reg_W, gamma, H_sum=None, HHt=None, XHt=None, update_H=True): """Update W in Multiplicative Update NMF.""" if beta_loss == 2: if XHt is None: XHt = safe_sparse_dot(X, H.T) if update_H: numerator = XHt else: numerator = XHt.copy() if HHt is None: HHt = np.dot(H, H.T) denominator = np.dot(W, HHt) else: <DeepExtract> if sp.issparse(X): (ii, jj) = X.nonzero() n_vals = ii.shape[0] dot_vals = np.empty(n_vals) n_components = W.shape[1] batch_size = max(n_components, n_vals // n_components) for start in range(0, n_vals, batch_size): batch = slice(start, start + batch_size) dot_vals[batch] = np.multiply(W[ii[batch], :], H.T[jj[batch], :]).sum(axis=1) WH = sp.coo_matrix((dot_vals, (ii, jj)), shape=X.shape) WH_safe_X = WH.tocsr() else: WH_safe_X = np.dot(W, H) </DeepExtract> if sp.issparse(X): WH_safe_X_data = WH_safe_X.data X_data = X.data else: WH_safe_X_data = WH_safe_X X_data = X WH = WH_safe_X.copy() if beta_loss - 1.0 < 0: WH[WH < EPSILON] = EPSILON if beta_loss - 2.0 < 0: WH_safe_X_data[WH_safe_X_data < EPSILON] = EPSILON if beta_loss == 1: np.divide(X_data, WH_safe_X_data, out=WH_safe_X_data) elif beta_loss == 0: WH_safe_X_data **= -1 WH_safe_X_data **= 2 WH_safe_X_data *= X_data else: WH_safe_X_data **= beta_loss - 2 WH_safe_X_data *= X_data numerator = safe_sparse_dot(WH_safe_X, H.T) if beta_loss == 1: if H_sum is None: H_sum = np.sum(H, axis=1) denominator = H_sum[np.newaxis, :] else: if sp.issparse(X): WHHt = np.empty(W.shape) for i in range(X.shape[0]): WHi = np.dot(W[i, :], H) if beta_loss - 1 < 0: WHi[WHi < EPSILON] = EPSILON WHi **= beta_loss - 1 WHHt[i, :] = np.dot(WHi, H.T) else: WH **= beta_loss - 1 WHHt = np.dot(WH, H.T) denominator = WHHt if l1_reg_W > 0: denominator += l1_reg_W if l2_reg_W > 0: denominator = denominator + l2_reg_W * W denominator[denominator == 0] = EPSILON numerator /= denominator delta_W = numerator if gamma != 1: delta_W **= gamma W *= delta_W return (W, H_sum, HHt, XHt)
def test_sparse_random_matrix(): n_components = 100 n_features = 500 for density in [0.3, 1.0]: s = 1 / density A = _sparse_random_matrix(n_components, n_features, density=density, random_state=0) if not sp.issparse(A): A = A else: A = A.toarray() values = np.unique(A) assert np.sqrt(s) / np.sqrt(n_components) in values assert -np.sqrt(s) / np.sqrt(n_components) in values if density == 1.0: assert np.size(values) == 2 else: assert 0.0 in values assert np.size(values) == 3 assert_almost_equal(np.mean(A == 0.0), 1 - 1 / s, decimal=2) assert_almost_equal(np.mean(A == np.sqrt(s) / np.sqrt(n_components)), 1 / (2 * s), decimal=2) assert_almost_equal(np.mean(A == -np.sqrt(s) / np.sqrt(n_components)), 1 / (2 * s), decimal=2) assert_almost_equal(np.var(A == 0.0, ddof=1), (1 - 1 / s) * 1 / s, decimal=2) assert_almost_equal(np.var(A == np.sqrt(s) / np.sqrt(n_components), ddof=1), (1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2) assert_almost_equal(np.var(A == -np.sqrt(s) / np.sqrt(n_components), ddof=1), (1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2)
def test_sparse_random_matrix(): n_components = 100 n_features = 500 for density in [0.3, 1.0]: s = 1 / density A = _sparse_random_matrix(n_components, n_features, density=density, random_state=0) <DeepExtract> if not sp.issparse(A): A = A else: A = A.toarray() </DeepExtract> values = np.unique(A) assert np.sqrt(s) / np.sqrt(n_components) in values assert -np.sqrt(s) / np.sqrt(n_components) in values if density == 1.0: assert np.size(values) == 2 else: assert 0.0 in values assert np.size(values) == 3 assert_almost_equal(np.mean(A == 0.0), 1 - 1 / s, decimal=2) assert_almost_equal(np.mean(A == np.sqrt(s) / np.sqrt(n_components)), 1 / (2 * s), decimal=2) assert_almost_equal(np.mean(A == -np.sqrt(s) / np.sqrt(n_components)), 1 / (2 * s), decimal=2) assert_almost_equal(np.var(A == 0.0, ddof=1), (1 - 1 / s) * 1 / s, decimal=2) assert_almost_equal(np.var(A == np.sqrt(s) / np.sqrt(n_components), ddof=1), (1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2) assert_almost_equal(np.var(A == -np.sqrt(s) / np.sqrt(n_components), ddof=1), (1 - 1 / (2 * s)) * 1 / (2 * s), decimal=2)
@pytest.mark.parametrize(['est', 'pattern'], [(ColumnTransformer([('trans1', Trans(), [0]), ('trans2', Trans(), [1])], remainder=DoubleTrans()), '\\[ColumnTransformer\\].*\\(1 of 3\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 3\\) Processing trans2.* total=.*\\n\\[ColumnTransformer\\].*\\(3 of 3\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', Trans(), [1])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 3\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 3\\) Processing trans2.* total=.*\\n\\[ColumnTransformer\\].*\\(3 of 3\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', 'drop', [1])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 2\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 2\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', 'passthrough', [1])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 3\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 3\\) Processing trans2.* total=.*\\n\\[ColumnTransformer\\].*\\(3 of 3\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 2\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 2\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', Trans(), [1])], remainder='drop'), '\\[ColumnTransformer\\].*\\(1 of 2\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 2\\) Processing trans2.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0])], remainder='drop'), '\\[ColumnTransformer\\].*\\(1 of 1\\) Processing trans1.* total=.*\\n$')]) @pytest.mark.parametrize('method', ['fit', 'fit_transform']) def test_column_transformer_verbose(est, pattern, method, capsys): X_array = np.array([[0, 1, 2], [2, 4, 6], [8, 6, 4]]).T func = getattr(est, method) est.set_params(verbose=False) assert_array_equal(X_array, X_array) return [0] assert not capsys.readouterr().out, 'Got output for verbose=False' est.set_params(verbose=True) assert_array_equal(X_array, X_array) return [0] assert re.match(pattern, capsys.readouterr()[0])
@pytest.mark.parametrize(['est', 'pattern'], [(ColumnTransformer([('trans1', Trans(), [0]), ('trans2', Trans(), [1])], remainder=DoubleTrans()), '\\[ColumnTransformer\\].*\\(1 of 3\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 3\\) Processing trans2.* total=.*\\n\\[ColumnTransformer\\].*\\(3 of 3\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', Trans(), [1])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 3\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 3\\) Processing trans2.* total=.*\\n\\[ColumnTransformer\\].*\\(3 of 3\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', 'drop', [1])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 2\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 2\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', 'passthrough', [1])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 3\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 3\\) Processing trans2.* total=.*\\n\\[ColumnTransformer\\].*\\(3 of 3\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0])], remainder='passthrough'), '\\[ColumnTransformer\\].*\\(1 of 2\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 2\\) Processing remainder.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0]), ('trans2', Trans(), [1])], remainder='drop'), '\\[ColumnTransformer\\].*\\(1 of 2\\) Processing trans1.* total=.*\\n\\[ColumnTransformer\\].*\\(2 of 2\\) Processing trans2.* total=.*\\n$'), (ColumnTransformer([('trans1', Trans(), [0])], remainder='drop'), '\\[ColumnTransformer\\].*\\(1 of 1\\) Processing trans1.* total=.*\\n$')]) @pytest.mark.parametrize('method', ['fit', 'fit_transform']) def test_column_transformer_verbose(est, pattern, method, capsys): X_array = np.array([[0, 1, 2], [2, 4, 6], [8, 6, 4]]).T func = getattr(est, method) est.set_params(verbose=False) <DeepExtract> assert_array_equal(X_array, X_array) return [0] </DeepExtract> assert not capsys.readouterr().out, 'Got output for verbose=False' est.set_params(verbose=True) <DeepExtract> assert_array_equal(X_array, X_array) return [0] </DeepExtract> assert re.match(pattern, capsys.readouterr()[0])
def test_randomized_svd_sign_flip_with_transpose(): def max_loading_is_positive(u, v): """ returns bool tuple indicating if the values maximising np.abs are positive across all rows for u and across all columns for v. """ u_based = (np.abs(u).max(axis=0) == u.max(axis=0)).all() v_based = (np.abs(v).max(axis=1) == v.max(axis=1)).all() return (u_based, v_based) mat = np.arange(10 * 8).reshape(10, -1) (u_flipped, _, v_flipped) = randomized_svd(mat, 3, flip_sign=True, random_state=0) u_based = (np.abs(u_flipped).max(axis=0) == u_flipped.max(axis=0)).all() v_based = (np.abs(v_flipped).max(axis=1) == v_flipped.max(axis=1)).all() (u_based, v_based) = (u_based, v_based) assert u_based assert not v_based (u_flipped_with_transpose, _, v_flipped_with_transpose) = randomized_svd(mat, 3, flip_sign=True, transpose=True, random_state=0) u_based = (np.abs(u_flipped_with_transpose).max(axis=0) == u_flipped_with_transpose.max(axis=0)).all() v_based = (np.abs(v_flipped_with_transpose).max(axis=1) == v_flipped_with_transpose.max(axis=1)).all() (u_based, v_based) = (u_based, v_based) assert u_based assert not v_based
def test_randomized_svd_sign_flip_with_transpose(): def max_loading_is_positive(u, v): """ returns bool tuple indicating if the values maximising np.abs are positive across all rows for u and across all columns for v. """ u_based = (np.abs(u).max(axis=0) == u.max(axis=0)).all() v_based = (np.abs(v).max(axis=1) == v.max(axis=1)).all() return (u_based, v_based) mat = np.arange(10 * 8).reshape(10, -1) (u_flipped, _, v_flipped) = randomized_svd(mat, 3, flip_sign=True, random_state=0) <DeepExtract> u_based = (np.abs(u_flipped).max(axis=0) == u_flipped.max(axis=0)).all() v_based = (np.abs(v_flipped).max(axis=1) == v_flipped.max(axis=1)).all() (u_based, v_based) = (u_based, v_based) </DeepExtract> assert u_based assert not v_based (u_flipped_with_transpose, _, v_flipped_with_transpose) = randomized_svd(mat, 3, flip_sign=True, transpose=True, random_state=0) <DeepExtract> u_based = (np.abs(u_flipped_with_transpose).max(axis=0) == u_flipped_with_transpose.max(axis=0)).all() v_based = (np.abs(v_flipped_with_transpose).max(axis=1) == v_flipped_with_transpose.max(axis=1)).all() (u_based, v_based) = (u_based, v_based) </DeepExtract> assert u_based assert not v_based
@ignore_warnings(category=FutureWarning) def check_classifiers_regression_target(name, estimator_orig): global REGRESSION_DATASET if REGRESSION_DATASET is None: (X, y) = make_regression(n_samples=200, n_features=10, n_informative=1, bias=5.0, noise=20, random_state=42) X = StandardScaler().fit_transform(X) REGRESSION_DATASET = (X, y) (X, y) = REGRESSION_DATASET 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 e = clone(estimator_orig) msg = 'Unknown label type: ' if not _safe_tags(e, key='no_validation'): with raises(ValueError, match=msg): e.fit(X, y)
@ignore_warnings(category=FutureWarning) def check_classifiers_regression_target(name, estimator_orig): <DeepExtract> global REGRESSION_DATASET if REGRESSION_DATASET is None: (X, y) = make_regression(n_samples=200, n_features=10, n_informative=1, bias=5.0, noise=20, random_state=42) X = StandardScaler().fit_transform(X) REGRESSION_DATASET = (X, y) (X, y) = REGRESSION_DATASET </DeepExtract> <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> e = clone(estimator_orig) msg = 'Unknown label type: ' if not _safe_tags(e, key='no_validation'): with raises(ValueError, match=msg): e.fit(X, y)
def setup_package(): python_requires = '>=3.8' required_python_version = (3, 8) metadata = dict(name=DISTNAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, license=LICENSE, url=URL, download_url=DOWNLOAD_URL, project_urls=PROJECT_URLS, version=VERSION, long_description=LONG_DESCRIPTION, classifiers=['Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: C', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', 'Development Status :: 5 - Production/Stable', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy'], cmdclass=cmdclass, python_requires=python_requires, install_requires=min_deps.tag_to_packages['install'], package_data={'': ['*.csv', '*.gz', '*.txt', '*.pxd', '*.rst', '*.jpg']}, zip_safe=False, extras_require={key: min_deps.tag_to_packages[key] for key in ['examples', 'docs', 'tests', 'benchmark']}) commands = [arg for arg in sys.argv[1:] if not arg.startswith('-')] if not all((command in ('egg_info', 'dist_info', 'clean', 'check') for command in commands)): if sys.version_info < required_python_version: required_version = '%d.%d' % required_python_version raise RuntimeError('Scikit-learn requires Python %s or later. The current Python version is %s installed in %s.' % (required_version, platform.python_version(), sys.executable)) package_status = {} try: module = importlib.import_module('numpy') package_version = module.__version__ package_status['up_to_date'] = parse_version(package_version) >= parse_version(min_deps.NUMPY_MIN_VERSION) package_status['version'] = package_version except ImportError: traceback.print_exc() package_status['up_to_date'] = False package_status['version'] = '' req_str = 'scikit-learn requires {} >= {}.\n'.format('numpy', min_deps.NUMPY_MIN_VERSION) instructions = 'Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html\n' if package_status['up_to_date'] is False: if package_status['version']: raise ImportError('Your installation of {} {} is out-of-date.\n{}{}'.format('numpy', package_status['version'], req_str, instructions)) else: raise ImportError('{} is not installed.\n{}{}'.format('numpy', req_str, instructions)) package_status = {} try: module = importlib.import_module('scipy') package_version = module.__version__ package_status['up_to_date'] = parse_version(package_version) >= parse_version(min_deps.SCIPY_MIN_VERSION) package_status['version'] = package_version except ImportError: traceback.print_exc() package_status['up_to_date'] = False package_status['version'] = '' req_str = 'scikit-learn requires {} >= {}.\n'.format('scipy', min_deps.SCIPY_MIN_VERSION) instructions = 'Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html\n' if package_status['up_to_date'] is False: if package_status['version']: raise ImportError('Your installation of {} {} is out-of-date.\n{}{}'.format('scipy', package_status['version'], req_str, instructions)) else: raise ImportError('{} is not installed.\n{}{}'.format('scipy', req_str, instructions)) _check_cython_version() if 'sdist' in sys.argv or '--help' in sys.argv: metadata['ext_modules'] = [] from sklearn._build_utils import cythonize_extensions from sklearn._build_utils import gen_from_templates import numpy is_pypy = platform.python_implementation() == 'PyPy' np_include = numpy.get_include() default_optimization_level = 'O2' if os.name == 'posix': default_libraries = ['m'] else: default_libraries = [] default_extra_compile_args = [] build_with_debug_symbols = os.environ.get('SKLEARN_BUILD_ENABLE_DEBUG_SYMBOLS', '0') != '0' if os.name == 'posix': if build_with_debug_symbols: default_extra_compile_args.append('-g') else: default_extra_compile_args.append('-g0') cython_exts = [] for (submodule, extensions) in extension_config.items(): submodule_parts = submodule.split('.') parent_dir = join('sklearn', *submodule_parts) for extension in extensions: if is_pypy and (not extension.get('compile_for_pypy', True)): continue tempita_sources = [] sources = [] for source in extension['sources']: source = join(parent_dir, source) (new_source_path, path_ext) = os.path.splitext(source) if path_ext != '.tp': sources.append(source) continue tempita_sources.append(source) if os.path.splitext(new_source_path)[-1] == '.pxd': continue sources.append(new_source_path) gen_from_templates(tempita_sources) source_name = os.path.splitext(os.path.basename(sources[0]))[0] if submodule: name_parts = ['sklearn', submodule, source_name] else: name_parts = ['sklearn', source_name] name = '.'.join(name_parts) include_dirs = [join(parent_dir, include_dir) for include_dir in extension.get('include_dirs', [])] if extension.get('include_np', False): include_dirs.append(np_include) depends = [join(parent_dir, depend) for depend in extension.get('depends', [])] extra_compile_args = extension.get('extra_compile_args', []) + default_extra_compile_args optimization_level = extension.get('optimization_level', default_optimization_level) if os.name == 'posix': extra_compile_args.append(f'-{optimization_level}') else: extra_compile_args.append(f'/{optimization_level}') libraries_ext = extension.get('libraries', []) + default_libraries new_ext = Extension(name=name, sources=sources, language=extension.get('language', None), include_dirs=include_dirs, libraries=libraries_ext, depends=depends, extra_link_args=extension.get('extra_link_args', None), extra_compile_args=extra_compile_args) cython_exts.append(new_ext) metadata['ext_modules'] = cythonize_extensions(cython_exts) metadata['libraries'] = libraries setup(**metadata)
def setup_package(): python_requires = '>=3.8' required_python_version = (3, 8) metadata = dict(name=DISTNAME, maintainer=MAINTAINER, maintainer_email=MAINTAINER_EMAIL, description=DESCRIPTION, license=LICENSE, url=URL, download_url=DOWNLOAD_URL, project_urls=PROJECT_URLS, version=VERSION, long_description=LONG_DESCRIPTION, classifiers=['Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: C', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Scientific/Engineering', 'Development Status :: 5 - Production/Stable', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy'], cmdclass=cmdclass, python_requires=python_requires, install_requires=min_deps.tag_to_packages['install'], package_data={'': ['*.csv', '*.gz', '*.txt', '*.pxd', '*.rst', '*.jpg']}, zip_safe=False, extras_require={key: min_deps.tag_to_packages[key] for key in ['examples', 'docs', 'tests', 'benchmark']}) commands = [arg for arg in sys.argv[1:] if not arg.startswith('-')] if not all((command in ('egg_info', 'dist_info', 'clean', 'check') for command in commands)): if sys.version_info < required_python_version: required_version = '%d.%d' % required_python_version raise RuntimeError('Scikit-learn requires Python %s or later. The current Python version is %s installed in %s.' % (required_version, platform.python_version(), sys.executable)) <DeepExtract> package_status = {} try: module = importlib.import_module('numpy') package_version = module.__version__ package_status['up_to_date'] = parse_version(package_version) >= parse_version(min_deps.NUMPY_MIN_VERSION) package_status['version'] = package_version except ImportError: traceback.print_exc() package_status['up_to_date'] = False package_status['version'] = '' req_str = 'scikit-learn requires {} >= {}.\n'.format('numpy', min_deps.NUMPY_MIN_VERSION) instructions = 'Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html\n' if package_status['up_to_date'] is False: if package_status['version']: raise ImportError('Your installation of {} {} is out-of-date.\n{}{}'.format('numpy', package_status['version'], req_str, instructions)) else: raise ImportError('{} is not installed.\n{}{}'.format('numpy', req_str, instructions)) </DeepExtract> <DeepExtract> package_status = {} try: module = importlib.import_module('scipy') package_version = module.__version__ package_status['up_to_date'] = parse_version(package_version) >= parse_version(min_deps.SCIPY_MIN_VERSION) package_status['version'] = package_version except ImportError: traceback.print_exc() package_status['up_to_date'] = False package_status['version'] = '' req_str = 'scikit-learn requires {} >= {}.\n'.format('scipy', min_deps.SCIPY_MIN_VERSION) instructions = 'Installation instructions are available on the scikit-learn website: http://scikit-learn.org/stable/install.html\n' if package_status['up_to_date'] is False: if package_status['version']: raise ImportError('Your installation of {} {} is out-of-date.\n{}{}'.format('scipy', package_status['version'], req_str, instructions)) else: raise ImportError('{} is not installed.\n{}{}'.format('scipy', req_str, instructions)) </DeepExtract> _check_cython_version() <DeepExtract> if 'sdist' in sys.argv or '--help' in sys.argv: metadata['ext_modules'] = [] from sklearn._build_utils import cythonize_extensions from sklearn._build_utils import gen_from_templates import numpy is_pypy = platform.python_implementation() == 'PyPy' np_include = numpy.get_include() default_optimization_level = 'O2' if os.name == 'posix': default_libraries = ['m'] else: default_libraries = [] default_extra_compile_args = [] build_with_debug_symbols = os.environ.get('SKLEARN_BUILD_ENABLE_DEBUG_SYMBOLS', '0') != '0' if os.name == 'posix': if build_with_debug_symbols: default_extra_compile_args.append('-g') else: default_extra_compile_args.append('-g0') cython_exts = [] for (submodule, extensions) in extension_config.items(): submodule_parts = submodule.split('.') parent_dir = join('sklearn', *submodule_parts) for extension in extensions: if is_pypy and (not extension.get('compile_for_pypy', True)): continue tempita_sources = [] sources = [] for source in extension['sources']: source = join(parent_dir, source) (new_source_path, path_ext) = os.path.splitext(source) if path_ext != '.tp': sources.append(source) continue tempita_sources.append(source) if os.path.splitext(new_source_path)[-1] == '.pxd': continue sources.append(new_source_path) gen_from_templates(tempita_sources) source_name = os.path.splitext(os.path.basename(sources[0]))[0] if submodule: name_parts = ['sklearn', submodule, source_name] else: name_parts = ['sklearn', source_name] name = '.'.join(name_parts) include_dirs = [join(parent_dir, include_dir) for include_dir in extension.get('include_dirs', [])] if extension.get('include_np', False): include_dirs.append(np_include) depends = [join(parent_dir, depend) for depend in extension.get('depends', [])] extra_compile_args = extension.get('extra_compile_args', []) + default_extra_compile_args optimization_level = extension.get('optimization_level', default_optimization_level) if os.name == 'posix': extra_compile_args.append(f'-{optimization_level}') else: extra_compile_args.append(f'/{optimization_level}') libraries_ext = extension.get('libraries', []) + default_libraries new_ext = Extension(name=name, sources=sources, language=extension.get('language', None), include_dirs=include_dirs, libraries=libraries_ext, depends=depends, extra_link_args=extension.get('extra_link_args', None), extra_compile_args=extra_compile_args) cython_exts.append(new_ext) metadata['ext_modules'] = cythonize_extensions(cython_exts) </DeepExtract> metadata['libraries'] = libraries setup(**metadata)
@fails_if_pypy @pytest.mark.parametrize('parser', ['liac-arff', 'pandas']) def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): """Check the equivalence of the dataset when using `as_frame=False` and `as_frame=True`. """ pytest.importorskip('pandas') data_id = 61 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 True: 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) bunch_as_frame_true = fetch_openml(data_id=data_id, as_frame=True, cache=False, parser=parser) bunch_as_frame_false = fetch_openml(data_id=data_id, as_frame=False, cache=False, parser=parser) assert_allclose(bunch_as_frame_false.data, bunch_as_frame_true.data) assert_array_equal(bunch_as_frame_false.target, bunch_as_frame_true.target)
@fails_if_pypy @pytest.mark.parametrize('parser', ['liac-arff', 'pandas']) def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser): """Check the equivalence of the dataset when using `as_frame=False` and `as_frame=True`. """ pytest.importorskip('pandas') data_id = 61 <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 True: 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> bunch_as_frame_true = fetch_openml(data_id=data_id, as_frame=True, cache=False, parser=parser) bunch_as_frame_false = fetch_openml(data_id=data_id, as_frame=False, cache=False, parser=parser) assert_allclose(bunch_as_frame_false.data, bunch_as_frame_true.data) assert_array_equal(bunch_as_frame_false.target, bunch_as_frame_true.target)
def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto', power_iteration_normalizer='auto', transpose='auto', flip_sign=True, random_state=None, svd_lapack_driver='gesdd'): """Compute a truncated randomized SVD. This method solves the fixed-rank approximation problem described in [1]_ (problem (1.5), p5). Parameters ---------- M : {ndarray, sparse matrix} Matrix to decompose. n_components : int Number of singular values and vectors to extract. n_oversamples : int, default=10 Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of singular vectors and singular values. Users might wish to increase this parameter up to `2*k - n_components` where k is the effective rank, for large matrices, noisy problems, matrices with slowly decaying spectrums, or to increase precision accuracy. See [1]_ (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) in which case `n_iter` is set to 7. This improves precision with few components. Note that in general users should rather increase `n_oversamples` before increasing `n_iter` as the principle of the randomized method is to avoid usage of these more costly power iterations steps. When `n_components` is equal or greater to the effective matrix rank and the spectrum does not present a slow decay, `n_iter=0` or `1` should even work fine in theory (see [1]_ page 9). .. versionchanged:: 0.18 power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. .. versionadded:: 0.18 transpose : bool or 'auto', default='auto' Whether the algorithm should be applied to M.T instead of M. The result should approximately be the same. The 'auto' mode will trigger the transposition if M.shape[1] > M.shape[0] since this implementation of randomized SVD tend to be a little faster in that case. .. versionchanged:: 0.18 flip_sign : bool, default=True The output of a singular value decomposition is only unique up to a permutation of the signs of the singular vectors. If `flip_sign` is set to `True`, the sign ambiguity is resolved by making the largest loadings for each component in the left singular vectors positive. random_state : int, RandomState instance or None, default='warn' The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. .. versionchanged:: 1.2 The default value changed from 0 to None. svd_lapack_driver : {"gesdd", "gesvd"}, default="gesdd" Whether to use the more efficient divide-and-conquer approach (`"gesdd"`) or more general rectangular approach (`"gesvd"`) to compute the SVD of the matrix B, which is the projection of M into a low dimensional subspace, as described in [1]_. .. versionadded:: 1.2 Returns ------- u : ndarray of shape (n_samples, n_components) Unitary matrix having left singular vectors with signs flipped as columns. s : ndarray of shape (n_components,) The singular values, sorted in non-increasing order. vh : ndarray of shape (n_components, n_features) Unitary matrix having right singular vectors with signs flipped as rows. Notes ----- This algorithm finds a (usually very good) approximate truncated singular value decomposition using randomization to speed up the computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). To increase the precision it is recommended to increase `n_oversamples`, up to `2*k-n_components` where k is the effective rank. Usually, `n_components` is chosen to be greater than k so increasing `n_oversamples` up to `n_components` should be enough. References ---------- .. [1] :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" <0909.4061>` Halko, et al. (2009) .. [2] A randomized algorithm for the decomposition of matrices Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert .. [3] An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014 Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import randomized_svd >>> a = np.array([[1, 2, 3, 5], ... [3, 4, 5, 6], ... [7, 8, 9, 10]]) >>> U, s, Vh = randomized_svd(a, n_components=2, random_state=0) >>> U.shape, s.shape, Vh.shape ((3, 2), (2,), (2, 4)) """ if isinstance(M, (sparse.lil_matrix, sparse.dok_matrix)): warnings.warn('Calculating SVD of a {} is expensive. csr_matrix is more efficient.'.format(type(M).__name__), sparse.SparseEfficiencyWarning) random_state = check_random_state(random_state) n_random = n_components + n_oversamples (n_samples, n_features) = M.shape if n_iter == 'auto': n_iter = 7 if n_components < 0.1 * min(M.shape) else 4 if transpose == 'auto': transpose = n_samples < n_features if transpose: M = M.T random_state = check_random_state(random_state) Q = random_state.normal(size=(M.shape[1], n_random)) if hasattr(M, 'dtype') and M.dtype.kind == 'f': Q = Q.astype(M.dtype, copy=False) if power_iteration_normalizer == 'auto': if n_iter <= 2: power_iteration_normalizer = 'none' else: power_iteration_normalizer = 'LU' for i in range(n_iter): if power_iteration_normalizer == 'none': Q = safe_sparse_dot(M, Q) Q = safe_sparse_dot(M.T, Q) elif power_iteration_normalizer == 'LU': (Q, _) = linalg.lu(safe_sparse_dot(M, Q), permute_l=True) (Q, _) = linalg.lu(safe_sparse_dot(M.T, Q), permute_l=True) elif power_iteration_normalizer == 'QR': (Q, _) = linalg.qr(safe_sparse_dot(M, Q), mode='economic') (Q, _) = linalg.qr(safe_sparse_dot(M.T, Q), mode='economic') (Q, _) = linalg.qr(safe_sparse_dot(M, Q), mode='economic') Q = Q if Q.T.ndim > 2 or M.ndim > 2: if sparse.issparse(Q.T): b_ = np.rollaxis(M, -2) b_2d = b_.reshape((M.shape[-2], -1)) ret = Q.T @ b_2d ret = ret.reshape(Q.T.shape[0], *b_.shape[1:]) elif sparse.issparse(M): a_2d = Q.T.reshape(-1, Q.T.shape[-1]) ret = a_2d @ M ret = ret.reshape(*Q.T.shape[:-1], M.shape[1]) else: ret = np.dot(Q.T, M) else: ret = Q.T @ M if sparse.issparse(Q.T) and sparse.issparse(M) and dense_output and hasattr(ret, 'toarray'): B = ret.toarray() B = ret (Uhat, s, Vt) = linalg.svd(B, full_matrices=False, lapack_driver=svd_lapack_driver) del B U = np.dot(Q, Uhat) if flip_sign: if not transpose: if u_based_decision: max_abs_cols = np.argmax(np.abs(U), axis=0) signs = np.sign(U[max_abs_cols, range(U.shape[1])]) U *= signs Vt *= signs[:, np.newaxis] else: max_abs_rows = np.argmax(np.abs(Vt), axis=1) signs = np.sign(Vt[range(Vt.shape[0]), max_abs_rows]) U *= signs Vt *= signs[:, np.newaxis] (U, Vt) = (U, Vt) else: if False: max_abs_cols = np.argmax(np.abs(U), axis=0) signs = np.sign(U[max_abs_cols, range(U.shape[1])]) U *= signs Vt *= signs[:, np.newaxis] else: max_abs_rows = np.argmax(np.abs(Vt), axis=1) signs = np.sign(Vt[range(Vt.shape[0]), max_abs_rows]) U *= signs Vt *= signs[:, np.newaxis] (U, Vt) = (U, Vt) if transpose: return (Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T) else: return (U[:, :n_components], s[:n_components], Vt[:n_components, :])
def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto', power_iteration_normalizer='auto', transpose='auto', flip_sign=True, random_state=None, svd_lapack_driver='gesdd'): """Compute a truncated randomized SVD. This method solves the fixed-rank approximation problem described in [1]_ (problem (1.5), p5). Parameters ---------- M : {ndarray, sparse matrix} Matrix to decompose. n_components : int Number of singular values and vectors to extract. n_oversamples : int, default=10 Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of singular vectors and singular values. Users might wish to increase this parameter up to `2*k - n_components` where k is the effective rank, for large matrices, noisy problems, matrices with slowly decaying spectrums, or to increase precision accuracy. See [1]_ (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) in which case `n_iter` is set to 7. This improves precision with few components. Note that in general users should rather increase `n_oversamples` before increasing `n_iter` as the principle of the randomized method is to avoid usage of these more costly power iterations steps. When `n_components` is equal or greater to the effective matrix rank and the spectrum does not present a slow decay, `n_iter=0` or `1` should even work fine in theory (see [1]_ page 9). .. versionchanged:: 0.18 power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. .. versionadded:: 0.18 transpose : bool or 'auto', default='auto' Whether the algorithm should be applied to M.T instead of M. The result should approximately be the same. The 'auto' mode will trigger the transposition if M.shape[1] > M.shape[0] since this implementation of randomized SVD tend to be a little faster in that case. .. versionchanged:: 0.18 flip_sign : bool, default=True The output of a singular value decomposition is only unique up to a permutation of the signs of the singular vectors. If `flip_sign` is set to `True`, the sign ambiguity is resolved by making the largest loadings for each component in the left singular vectors positive. random_state : int, RandomState instance or None, default='warn' The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. .. versionchanged:: 1.2 The default value changed from 0 to None. svd_lapack_driver : {"gesdd", "gesvd"}, default="gesdd" Whether to use the more efficient divide-and-conquer approach (`"gesdd"`) or more general rectangular approach (`"gesvd"`) to compute the SVD of the matrix B, which is the projection of M into a low dimensional subspace, as described in [1]_. .. versionadded:: 1.2 Returns ------- u : ndarray of shape (n_samples, n_components) Unitary matrix having left singular vectors with signs flipped as columns. s : ndarray of shape (n_components,) The singular values, sorted in non-increasing order. vh : ndarray of shape (n_components, n_features) Unitary matrix having right singular vectors with signs flipped as rows. Notes ----- This algorithm finds a (usually very good) approximate truncated singular value decomposition using randomization to speed up the computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). To increase the precision it is recommended to increase `n_oversamples`, up to `2*k-n_components` where k is the effective rank. Usually, `n_components` is chosen to be greater than k so increasing `n_oversamples` up to `n_components` should be enough. References ---------- .. [1] :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" <0909.4061>` Halko, et al. (2009) .. [2] A randomized algorithm for the decomposition of matrices Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert .. [3] An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014 Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import randomized_svd >>> a = np.array([[1, 2, 3, 5], ... [3, 4, 5, 6], ... [7, 8, 9, 10]]) >>> U, s, Vh = randomized_svd(a, n_components=2, random_state=0) >>> U.shape, s.shape, Vh.shape ((3, 2), (2,), (2, 4)) """ if isinstance(M, (sparse.lil_matrix, sparse.dok_matrix)): warnings.warn('Calculating SVD of a {} is expensive. csr_matrix is more efficient.'.format(type(M).__name__), sparse.SparseEfficiencyWarning) random_state = check_random_state(random_state) n_random = n_components + n_oversamples (n_samples, n_features) = M.shape if n_iter == 'auto': n_iter = 7 if n_components < 0.1 * min(M.shape) else 4 if transpose == 'auto': transpose = n_samples < n_features if transpose: M = M.T <DeepExtract> random_state = check_random_state(random_state) Q = random_state.normal(size=(M.shape[1], n_random)) if hasattr(M, 'dtype') and M.dtype.kind == 'f': Q = Q.astype(M.dtype, copy=False) if power_iteration_normalizer == 'auto': if n_iter <= 2: power_iteration_normalizer = 'none' else: power_iteration_normalizer = 'LU' for i in range(n_iter): if power_iteration_normalizer == 'none': Q = safe_sparse_dot(M, Q) Q = safe_sparse_dot(M.T, Q) elif power_iteration_normalizer == 'LU': (Q, _) = linalg.lu(safe_sparse_dot(M, Q), permute_l=True) (Q, _) = linalg.lu(safe_sparse_dot(M.T, Q), permute_l=True) elif power_iteration_normalizer == 'QR': (Q, _) = linalg.qr(safe_sparse_dot(M, Q), mode='economic') (Q, _) = linalg.qr(safe_sparse_dot(M.T, Q), mode='economic') (Q, _) = linalg.qr(safe_sparse_dot(M, Q), mode='economic') Q = Q </DeepExtract> <DeepExtract> if Q.T.ndim > 2 or M.ndim > 2: if sparse.issparse(Q.T): b_ = np.rollaxis(M, -2) b_2d = b_.reshape((M.shape[-2], -1)) ret = Q.T @ b_2d ret = ret.reshape(Q.T.shape[0], *b_.shape[1:]) elif sparse.issparse(M): a_2d = Q.T.reshape(-1, Q.T.shape[-1]) ret = a_2d @ M ret = ret.reshape(*Q.T.shape[:-1], M.shape[1]) else: ret = np.dot(Q.T, M) else: ret = Q.T @ M if sparse.issparse(Q.T) and sparse.issparse(M) and dense_output and hasattr(ret, 'toarray'): B = ret.toarray() B = ret </DeepExtract> (Uhat, s, Vt) = linalg.svd(B, full_matrices=False, lapack_driver=svd_lapack_driver) del B U = np.dot(Q, Uhat) if flip_sign: if not transpose: <DeepExtract> if u_based_decision: max_abs_cols = np.argmax(np.abs(U), axis=0) signs = np.sign(U[max_abs_cols, range(U.shape[1])]) U *= signs Vt *= signs[:, np.newaxis] else: max_abs_rows = np.argmax(np.abs(Vt), axis=1) signs = np.sign(Vt[range(Vt.shape[0]), max_abs_rows]) U *= signs Vt *= signs[:, np.newaxis] (U, Vt) = (U, Vt) </DeepExtract> else: <DeepExtract> if False: max_abs_cols = np.argmax(np.abs(U), axis=0) signs = np.sign(U[max_abs_cols, range(U.shape[1])]) U *= signs Vt *= signs[:, np.newaxis] else: max_abs_rows = np.argmax(np.abs(Vt), axis=1) signs = np.sign(Vt[range(Vt.shape[0]), max_abs_rows]) U *= signs Vt *= signs[:, np.newaxis] (U, Vt) = (U, Vt) </DeepExtract> if transpose: return (Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T) else: return (U[:, :n_components], s[:n_components], Vt[:n_components, :])
def _randomized_eigsh(M, n_components, *, n_oversamples=10, n_iter='auto', power_iteration_normalizer='auto', selection='module', random_state=None): """Computes a truncated eigendecomposition using randomized methods This method solves the fixed-rank approximation problem described in the Halko et al paper. The choice of which components to select can be tuned with the `selection` parameter. .. versionadded:: 0.24 Parameters ---------- M : ndarray or sparse matrix Matrix to decompose, it should be real symmetric square or complex hermitian n_components : int Number of eigenvalues and vectors to extract. n_oversamples : int, default=10 Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of eigenvectors and eigenvalues. Users might wish to increase this parameter up to `2*k - n_components` where k is the effective rank, for large matrices, noisy problems, matrices with slowly decaying spectrums, or to increase precision accuracy. See Halko et al (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) in which case `n_iter` is set to 7. This improves precision with few components. Note that in general users should rather increase `n_oversamples` before increasing `n_iter` as the principle of the randomized method is to avoid usage of these more costly power iterations steps. When `n_components` is equal or greater to the effective matrix rank and the spectrum does not present a slow decay, `n_iter=0` or `1` should even work fine in theory (see Halko et al paper, page 9). power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. selection : {'value', 'module'}, default='module' Strategy used to select the n components. When `selection` is `'value'` (not yet implemented, will become the default when implemented), the components corresponding to the n largest eigenvalues are returned. When `selection` is `'module'`, the components corresponding to the n eigenvalues with largest modules are returned. random_state : int, RandomState instance, default=None The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. Notes ----- This algorithm finds a (usually very good) approximate truncated eigendecomposition using randomized methods to speed up the computations. This method is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). To increase the precision it is recommended to increase `n_oversamples`, up to `2*k-n_components` where k is the effective rank. Usually, `n_components` is chosen to be greater than k so increasing `n_oversamples` up to `n_components` should be enough. Strategy 'value': not implemented yet. Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good condidates for a future implementation. Strategy 'module': The principle is that for diagonalizable matrices, the singular values and eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a singular value of A. This method relies on a randomized SVD to find the n singular components corresponding to the n singular values with largest modules, and then uses the signs of the singular vectors to find the true sign of t: if the sign of left and right singular vectors are different then the corresponding eigenvalue is negative. Returns ------- eigvals : 1D array of shape (n_components,) containing the `n_components` eigenvalues selected (see ``selection`` parameter). eigvecs : 2D array of shape (M.shape[0], n_components) containing the `n_components` eigenvectors corresponding to the `eigvals`, in the corresponding order. Note that this follows the `scipy.linalg.eigh` convention. See Also -------- :func:`randomized_svd` References ---------- * :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" (Algorithm 4.3 for strategy 'module') <0909.4061>` Halko, et al. (2009) """ if selection == 'value': raise NotImplementedError() elif selection == 'module': if isinstance(M, (sparse.lil_matrix, sparse.dok_matrix)): warnings.warn('Calculating SVD of a {} is expensive. csr_matrix is more efficient.'.format(type(M).__name__), sparse.SparseEfficiencyWarning) random_state = check_random_state(random_state) n_random = n_components + n_oversamples (n_samples, n_features) = M.shape if n_iter == 'auto': n_iter = 7 if n_components < 0.1 * min(M.shape) else 4 if transpose == 'auto': transpose = n_samples < n_features if transpose: M = M.T Q = randomized_range_finder(M, size=n_random, n_iter=n_iter, power_iteration_normalizer=power_iteration_normalizer, random_state=random_state) B = safe_sparse_dot(Q.T, M) (Uhat, s, Vt) = linalg.svd(B, full_matrices=False, lapack_driver=svd_lapack_driver) del B U = np.dot(Q, Uhat) if False: if not transpose: (U, Vt) = svd_flip(U, Vt) else: (U, Vt) = svd_flip(U, Vt, u_based_decision=False) if transpose: (U, S, Vt) = (Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T) else: (U, S, Vt) = (U[:, :n_components], s[:n_components], Vt[:n_components, :]) eigvecs = U[:, :n_components] eigvals = S[:n_components] diag_VtU = np.einsum('ji,ij->j', Vt[:n_components, :], U[:, :n_components]) signs = np.sign(diag_VtU) eigvals = eigvals * signs else: raise ValueError('Invalid `selection`: %r' % selection) return (eigvals, eigvecs)
def _randomized_eigsh(M, n_components, *, n_oversamples=10, n_iter='auto', power_iteration_normalizer='auto', selection='module', random_state=None): """Computes a truncated eigendecomposition using randomized methods This method solves the fixed-rank approximation problem described in the Halko et al paper. The choice of which components to select can be tuned with the `selection` parameter. .. versionadded:: 0.24 Parameters ---------- M : ndarray or sparse matrix Matrix to decompose, it should be real symmetric square or complex hermitian n_components : int Number of eigenvalues and vectors to extract. n_oversamples : int, default=10 Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of eigenvectors and eigenvalues. Users might wish to increase this parameter up to `2*k - n_components` where k is the effective rank, for large matrices, noisy problems, matrices with slowly decaying spectrums, or to increase precision accuracy. See Halko et al (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) in which case `n_iter` is set to 7. This improves precision with few components. Note that in general users should rather increase `n_oversamples` before increasing `n_iter` as the principle of the randomized method is to avoid usage of these more costly power iterations steps. When `n_components` is equal or greater to the effective matrix rank and the spectrum does not present a slow decay, `n_iter=0` or `1` should even work fine in theory (see Halko et al paper, page 9). power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. selection : {'value', 'module'}, default='module' Strategy used to select the n components. When `selection` is `'value'` (not yet implemented, will become the default when implemented), the components corresponding to the n largest eigenvalues are returned. When `selection` is `'module'`, the components corresponding to the n eigenvalues with largest modules are returned. random_state : int, RandomState instance, default=None The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. Notes ----- This algorithm finds a (usually very good) approximate truncated eigendecomposition using randomized methods to speed up the computations. This method is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). To increase the precision it is recommended to increase `n_oversamples`, up to `2*k-n_components` where k is the effective rank. Usually, `n_components` is chosen to be greater than k so increasing `n_oversamples` up to `n_components` should be enough. Strategy 'value': not implemented yet. Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good condidates for a future implementation. Strategy 'module': The principle is that for diagonalizable matrices, the singular values and eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a singular value of A. This method relies on a randomized SVD to find the n singular components corresponding to the n singular values with largest modules, and then uses the signs of the singular vectors to find the true sign of t: if the sign of left and right singular vectors are different then the corresponding eigenvalue is negative. Returns ------- eigvals : 1D array of shape (n_components,) containing the `n_components` eigenvalues selected (see ``selection`` parameter). eigvecs : 2D array of shape (M.shape[0], n_components) containing the `n_components` eigenvectors corresponding to the `eigvals`, in the corresponding order. Note that this follows the `scipy.linalg.eigh` convention. See Also -------- :func:`randomized_svd` References ---------- * :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" (Algorithm 4.3 for strategy 'module') <0909.4061>` Halko, et al. (2009) """ if selection == 'value': raise NotImplementedError() elif selection == 'module': <DeepExtract> if isinstance(M, (sparse.lil_matrix, sparse.dok_matrix)): warnings.warn('Calculating SVD of a {} is expensive. csr_matrix is more efficient.'.format(type(M).__name__), sparse.SparseEfficiencyWarning) random_state = check_random_state(random_state) n_random = n_components + n_oversamples (n_samples, n_features) = M.shape if n_iter == 'auto': n_iter = 7 if n_components < 0.1 * min(M.shape) else 4 if transpose == 'auto': transpose = n_samples < n_features if transpose: M = M.T Q = randomized_range_finder(M, size=n_random, n_iter=n_iter, power_iteration_normalizer=power_iteration_normalizer, random_state=random_state) B = safe_sparse_dot(Q.T, M) (Uhat, s, Vt) = linalg.svd(B, full_matrices=False, lapack_driver=svd_lapack_driver) del B U = np.dot(Q, Uhat) if False: if not transpose: (U, Vt) = svd_flip(U, Vt) else: (U, Vt) = svd_flip(U, Vt, u_based_decision=False) if transpose: (U, S, Vt) = (Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T) else: (U, S, Vt) = (U[:, :n_components], s[:n_components], Vt[:n_components, :]) </DeepExtract> eigvecs = U[:, :n_components] eigvals = S[:n_components] diag_VtU = np.einsum('ji,ij->j', Vt[:n_components, :], U[:, :n_components]) signs = np.sign(diag_VtU) eigvals = eigvals * signs else: raise ValueError('Invalid `selection`: %r' % selection) return (eigvals, eigvecs)
def test_davies_bouldin_score(): rng = np.random.RandomState(seed=0) with pytest.raises(ValueError, match='Number of labels is'): davies_bouldin_score(rng.rand(10, 2), np.zeros(10)) rng = np.random.RandomState(seed=0) with pytest.raises(ValueError, match='Number of labels is'): davies_bouldin_score(rng.rand(10, 2), np.arange(10)) assert davies_bouldin_score(np.ones((10, 2)), [0] * 5 + [1] * 5) == pytest.approx(0.0) assert davies_bouldin_score([[-1, -1], [1, 1]] * 10, [0] * 10 + [1] * 10) == pytest.approx(0.0) X = [[0, 0], [1, 1]] * 5 + [[3, 3], [4, 4]] * 5 + [[0, 4], [1, 3]] * 5 + [[3, 1], [4, 0]] * 5 labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10 pytest.approx(davies_bouldin_score(X, labels), 2 * np.sqrt(0.5) / 3) with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) davies_bouldin_score(X, labels) X = [[0, 0], [2, 2], [3, 3], [5, 5]] labels = [0, 0, 1, 2] pytest.approx(davies_bouldin_score(X, labels), 5.0 / 4 / 3)
def test_davies_bouldin_score(): <DeepExtract> rng = np.random.RandomState(seed=0) with pytest.raises(ValueError, match='Number of labels is'): davies_bouldin_score(rng.rand(10, 2), np.zeros(10)) </DeepExtract> <DeepExtract> rng = np.random.RandomState(seed=0) with pytest.raises(ValueError, match='Number of labels is'): davies_bouldin_score(rng.rand(10, 2), np.arange(10)) </DeepExtract> assert davies_bouldin_score(np.ones((10, 2)), [0] * 5 + [1] * 5) == pytest.approx(0.0) assert davies_bouldin_score([[-1, -1], [1, 1]] * 10, [0] * 10 + [1] * 10) == pytest.approx(0.0) X = [[0, 0], [1, 1]] * 5 + [[3, 3], [4, 4]] * 5 + [[0, 4], [1, 3]] * 5 + [[3, 1], [4, 0]] * 5 labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10 pytest.approx(davies_bouldin_score(X, labels), 2 * np.sqrt(0.5) / 3) with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) davies_bouldin_score(X, labels) X = [[0, 0], [2, 2], [3, 3], [5, 5]] labels = [0, 0, 1, 2] pytest.approx(davies_bouldin_score(X, labels), 5.0 / 4 / 3)
def test_sparse_enet_not_as_toy_dataset(): (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=False) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=False) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=True) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=True) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative </DeepExtract>
def test_sparse_enet_not_as_toy_dataset(): <DeepExtract> (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=False) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative </DeepExtract> <DeepExtract> (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=False) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.1, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=False, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative </DeepExtract> <DeepExtract> (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=True) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=False, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative </DeepExtract> <DeepExtract> (n_samples, n_features, max_iter) = (100, 100, 1000) n_informative = 10 (X, y) = make_sparse_data(n_samples, n_features, n_informative, positive=True) (X_train, X_test) = (X[n_samples // 2:], X[:n_samples // 2]) (y_train, y_test) = (y[n_samples // 2:], y[:n_samples // 2]) s_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) s_clf.fit(X_train, y_train) assert_almost_equal(s_clf.dual_gap_, 0, 4) assert s_clf.score(X_test, y_test) > 0.85 d_clf = ElasticNet(alpha=0.001, l1_ratio=0.8, fit_intercept=True, max_iter=max_iter, tol=1e-07, positive=True, warm_start=True) d_clf.fit(X_train.toarray(), y_train) assert_almost_equal(d_clf.dual_gap_, 0, 4) assert d_clf.score(X_test, y_test) > 0.85 assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative </DeepExtract>
def test_lasso_lars_vs_lasso_cd_ill_conditioned2(): X = [[1e+20, 1e+20, 0], [-1e-32, 0, 0], [1, 1, 1]] y = [10, 10, 1] alpha = 0.0001 def objective_function(coef): return 1.0 / (2.0 * len(X)) * linalg.norm(y - np.dot(X, coef)) ** 2 + alpha * linalg.norm(coef, 1) lars = linear_model.LassoLars(alpha=alpha) warning_message = 'Regressors in active set degenerate.' with pytest.warns(ConvergenceWarning, match=warning_message): lars.fit(X, y) lars_coef_ = lars.coef_ lars_obj = 1.0 / (2.0 * len(X)) * linalg.norm(y - np.dot(X, lars_coef_)) ** 2 + alpha * linalg.norm(lars_coef_, 1) coord_descent = linear_model.Lasso(alpha=alpha, tol=0.0001) cd_coef_ = coord_descent.fit(X, y).coef_ cd_obj = 1.0 / (2.0 * len(X)) * linalg.norm(y - np.dot(X, cd_coef_)) ** 2 + alpha * linalg.norm(cd_coef_, 1) assert lars_obj < cd_obj * (1.0 + 1e-08)
def test_lasso_lars_vs_lasso_cd_ill_conditioned2(): X = [[1e+20, 1e+20, 0], [-1e-32, 0, 0], [1, 1, 1]] y = [10, 10, 1] alpha = 0.0001 def objective_function(coef): return 1.0 / (2.0 * len(X)) * linalg.norm(y - np.dot(X, coef)) ** 2 + alpha * linalg.norm(coef, 1) lars = linear_model.LassoLars(alpha=alpha) warning_message = 'Regressors in active set degenerate.' with pytest.warns(ConvergenceWarning, match=warning_message): lars.fit(X, y) lars_coef_ = lars.coef_ <DeepExtract> lars_obj = 1.0 / (2.0 * len(X)) * linalg.norm(y - np.dot(X, lars_coef_)) ** 2 + alpha * linalg.norm(lars_coef_, 1) </DeepExtract> coord_descent = linear_model.Lasso(alpha=alpha, tol=0.0001) cd_coef_ = coord_descent.fit(X, y).coef_ <DeepExtract> cd_obj = 1.0 / (2.0 * len(X)) * linalg.norm(y - np.dot(X, cd_coef_)) ** 2 + alpha * linalg.norm(cd_coef_, 1) </DeepExtract> assert lars_obj < cd_obj * (1.0 + 1e-08)
def fit_transform(X, y=None, W=None, H=None): X = check_array(X, accept_sparse=('csr', 'csc')) check_non_negative(X, 'NMF (input X)') (n_samples, n_features) = X.shape n_components = self.n_components if n_components is None: n_components = n_features if not isinstance(n_components, numbers.Integral) or n_components <= 0: raise ValueError('Number of components must be a positive integer; got (n_components=%r)' % n_components) if not isinstance(self.max_iter, numbers.Integral) or self.max_iter < 0: raise ValueError('Maximum number of iterations must be a positive integer; got (max_iter=%r)' % self.max_iter) if not isinstance(self.tol, numbers.Number) or self.tol < 0: raise ValueError('Tolerance for stopping criteria must be positive; got (tol=%r)' % self.tol) if self.init == 'custom' and True: _check_init(H, (n_components, n_features), 'NMF (input H)') _check_init(W, (n_samples, n_components), 'NMF (input W)') elif not True: _check_init(H, (n_components, n_features), 'NMF (input H)') W = np.zeros((n_samples, n_components)) else: (W, H) = _initialize_nmf(X, n_components, init=self.init, random_state=self.random_state) if True: (W, H, n_iter) = _fit_projected_gradient(X, W, H, self.tol, self.max_iter, self.nls_max_iter, self.alpha, self.l1_ratio) else: (Wt, _, n_iter) = _nls_subproblem(X.T, H.T, W.T, self.tol, self.nls_max_iter, alpha=self.alpha, l1_ratio=self.l1_ratio) W = Wt.T if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iteration %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) (W, H, self.n_iter) = (W, H, n_iter) self.components_ = H return W
def fit_transform(X, y=None, W=None, H=None): <DeepExtract> X = check_array(X, accept_sparse=('csr', 'csc')) check_non_negative(X, 'NMF (input X)') (n_samples, n_features) = X.shape n_components = self.n_components if n_components is None: n_components = n_features if not isinstance(n_components, numbers.Integral) or n_components <= 0: raise ValueError('Number of components must be a positive integer; got (n_components=%r)' % n_components) if not isinstance(self.max_iter, numbers.Integral) or self.max_iter < 0: raise ValueError('Maximum number of iterations must be a positive integer; got (max_iter=%r)' % self.max_iter) if not isinstance(self.tol, numbers.Number) or self.tol < 0: raise ValueError('Tolerance for stopping criteria must be positive; got (tol=%r)' % self.tol) if self.init == 'custom' and True: _check_init(H, (n_components, n_features), 'NMF (input H)') _check_init(W, (n_samples, n_components), 'NMF (input W)') elif not True: _check_init(H, (n_components, n_features), 'NMF (input H)') W = np.zeros((n_samples, n_components)) else: (W, H) = _initialize_nmf(X, n_components, init=self.init, random_state=self.random_state) if True: (W, H, n_iter) = _fit_projected_gradient(X, W, H, self.tol, self.max_iter, self.nls_max_iter, self.alpha, self.l1_ratio) else: (Wt, _, n_iter) = _nls_subproblem(X.T, H.T, W.T, self.tol, self.nls_max_iter, alpha=self.alpha, l1_ratio=self.l1_ratio) W = Wt.T if n_iter == self.max_iter and self.tol > 0: warnings.warn('Maximum number of iteration %d reached. Increase it to improve convergence.' % self.max_iter, ConvergenceWarning) (W, H, self.n_iter) = (W, H, n_iter) </DeepExtract> self.components_ = H return W
def test_verbosity(): random_state = np.random.RandomState(0) w = 3.0 if intercept: c = 2.0 n_samples = 50 else: c = 0.1 n_samples = 100 x = random_state.normal(size=n_samples) noise = 0.1 * random_state.normal(size=n_samples) y = w * x + c + noise if intercept: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[33], y[33]) = (2.5, 1) (x[49], y[49]) = (2.1, 2) else: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[53], y[53]) = (2.5, 1) (x[60], y[60]) = (2.1, 2) (x[72], y[72]) = (1.8, -7) (X, y, w, c) = (x[:, np.newaxis], y, w, c) with no_stdout_stderr(): TheilSenRegressor(verbose=True, random_state=0).fit(X, y) TheilSenRegressor(verbose=True, max_subpopulation=10, random_state=0).fit(X, y)
def test_verbosity(): <DeepExtract> random_state = np.random.RandomState(0) w = 3.0 if intercept: c = 2.0 n_samples = 50 else: c = 0.1 n_samples = 100 x = random_state.normal(size=n_samples) noise = 0.1 * random_state.normal(size=n_samples) y = w * x + c + noise if intercept: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[33], y[33]) = (2.5, 1) (x[49], y[49]) = (2.1, 2) else: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[53], y[53]) = (2.5, 1) (x[60], y[60]) = (2.1, 2) (x[72], y[72]) = (1.8, -7) (X, y, w, c) = (x[:, np.newaxis], y, w, c) </DeepExtract> with no_stdout_stderr(): TheilSenRegressor(verbose=True, random_state=0).fit(X, y) TheilSenRegressor(verbose=True, max_subpopulation=10, random_state=0).fit(X, y)
@pytest.mark.parametrize('scoring', (('accuracy',), ['precision'], {'acc': 'accuracy', 'precision': 'precision'}, ('accuracy', 'precision'), ['precision', 'accuracy'], {'accuracy': make_scorer(accuracy_score), 'precision': make_scorer(precision_score)}), ids=['single_tuple', 'single_list', 'dict_str', 'multi_tuple', 'multi_list', 'dict_callable']) def test_check_scoring_and_check_multimetric_scoring(scoring): estimator = EstimatorWithoutFit() pattern = "estimator should be an estimator implementing 'fit' method, .* was passed" with pytest.raises(TypeError, match=pattern): check_scoring(estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert scorer is _passthrough_scorer assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = "If no scoring is specified, the estimator passed should have a 'score' method\\. The estimator .* does not\\." with pytest.raises(TypeError, match=pattern): check_scoring(estimator) scorer = check_scoring(estimator, scoring='accuracy') assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, scoring='accuracy') assert isinstance(scorer, _PredictScorer) if check_scoring is check_scoring: estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert scorer is None estimator = LinearSVC(random_state=0) estimator.fit([[1], [2], [3]], [1, 1, 0]) scorers = _check_multimetric_scoring(estimator, scoring) assert isinstance(scorers, dict) assert sorted(scorers.keys()) == sorted(list(scoring)) assert all([isinstance(scorer, _PredictScorer) for scorer in list(scorers.values())]) if 'acc' in scoring: assert_almost_equal(scorers['acc'](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0) if 'accuracy' in scoring: assert_almost_equal(scorers['accuracy'](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0) if 'precision' in scoring: assert_almost_equal(scorers['precision'](estimator, [[1], [2], [3]], [1, 0, 0]), 0.5)
@pytest.mark.parametrize('scoring', (('accuracy',), ['precision'], {'acc': 'accuracy', 'precision': 'precision'}, ('accuracy', 'precision'), ['precision', 'accuracy'], {'accuracy': make_scorer(accuracy_score), 'precision': make_scorer(precision_score)}), ids=['single_tuple', 'single_list', 'dict_str', 'multi_tuple', 'multi_list', 'dict_callable']) def test_check_scoring_and_check_multimetric_scoring(scoring): <DeepExtract> estimator = EstimatorWithoutFit() pattern = "estimator should be an estimator implementing 'fit' method, .* was passed" with pytest.raises(TypeError, match=pattern): check_scoring(estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert scorer is _passthrough_scorer assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = "If no scoring is specified, the estimator passed should have a 'score' method\\. The estimator .* does not\\." with pytest.raises(TypeError, match=pattern): check_scoring(estimator) scorer = check_scoring(estimator, scoring='accuracy') assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, scoring='accuracy') assert isinstance(scorer, _PredictScorer) if check_scoring is check_scoring: estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert scorer is None </DeepExtract> estimator = LinearSVC(random_state=0) estimator.fit([[1], [2], [3]], [1, 1, 0]) scorers = _check_multimetric_scoring(estimator, scoring) assert isinstance(scorers, dict) assert sorted(scorers.keys()) == sorted(list(scoring)) assert all([isinstance(scorer, _PredictScorer) for scorer in list(scorers.values())]) if 'acc' in scoring: assert_almost_equal(scorers['acc'](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0) if 'accuracy' in scoring: assert_almost_equal(scorers['accuracy'](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0) if 'precision' in scoring: assert_almost_equal(scorers['precision'](estimator, [[1], [2], [3]], [1, 0, 0]), 0.5)
def _transform(self, X, fitting): assert array('i').itemsize == 4, 'sizeof(int) != 4 on your platform; please report this at https://github.com/scikit-learn/scikit-learn/issues and include the output from platform.platform() in your bug report' dtype = self.dtype if fitting: feature_names = [] vocab = {} else: feature_names = self.feature_names_ vocab = self.vocabulary_ transforming = True X = [X] if isinstance(X, Mapping) else X indices = array('i') indptr = [0] values = [] for x in X: for (f, v) in x.items(): if isinstance(v, str): feature_name = '%s%s%s' % (f, self.separator, v) v = 1 elif isinstance(v, Number) or v is None: feature_name = f elif not isinstance(v, Mapping) and isinstance(v, Iterable): feature_name = None for vv in v: if isinstance(vv, str): feature_name = '%s%s%s' % (f, self.separator, vv) vv = 1 else: raise TypeError(f'Unsupported type {type(vv)} in iterable value. Only iterables of string are supported.') if fitting and feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if transforming and feature_name in vocab: indices.append(vocab[feature_name]) values.append(self.dtype(vv)) else: raise TypeError(f'Unsupported value Type {type(v)} for {f}: {v}.\n{type(v)} objects are not supported.') if feature_name is not None: if fitting and feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if feature_name in vocab: indices.append(vocab[feature_name]) values.append(self.dtype(v)) indptr.append(len(indices)) if len(indptr) == 1: raise ValueError('Sample sequence X is empty.') indices = np.frombuffer(indices, dtype=np.intc) shape = (len(indptr) - 1, len(vocab)) result_matrix = sp.csr_matrix((values, indices, indptr), shape=shape, dtype=dtype) if fitting and self.sort: feature_names.sort() map_index = np.empty(len(feature_names), dtype=np.int32) for (new_val, f) in enumerate(feature_names): map_index[new_val] = vocab[f] vocab[f] = new_val result_matrix = result_matrix[:, map_index] if self.sparse: result_matrix.sort_indices() else: result_matrix = result_matrix.toarray() if fitting: self.feature_names_ = feature_names self.vocabulary_ = vocab return result_matrix
def _transform(self, X, fitting): assert array('i').itemsize == 4, 'sizeof(int) != 4 on your platform; please report this at https://github.com/scikit-learn/scikit-learn/issues and include the output from platform.platform() in your bug report' dtype = self.dtype if fitting: feature_names = [] vocab = {} else: feature_names = self.feature_names_ vocab = self.vocabulary_ transforming = True X = [X] if isinstance(X, Mapping) else X indices = array('i') indptr = [0] values = [] for x in X: for (f, v) in x.items(): if isinstance(v, str): feature_name = '%s%s%s' % (f, self.separator, v) v = 1 elif isinstance(v, Number) or v is None: feature_name = f elif not isinstance(v, Mapping) and isinstance(v, Iterable): feature_name = None <DeepExtract> for vv in v: if isinstance(vv, str): feature_name = '%s%s%s' % (f, self.separator, vv) vv = 1 else: raise TypeError(f'Unsupported type {type(vv)} in iterable value. Only iterables of string are supported.') if fitting and feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if transforming and feature_name in vocab: indices.append(vocab[feature_name]) values.append(self.dtype(vv)) </DeepExtract> else: raise TypeError(f'Unsupported value Type {type(v)} for {f}: {v}.\n{type(v)} objects are not supported.') if feature_name is not None: if fitting and feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if feature_name in vocab: indices.append(vocab[feature_name]) values.append(self.dtype(v)) indptr.append(len(indices)) if len(indptr) == 1: raise ValueError('Sample sequence X is empty.') indices = np.frombuffer(indices, dtype=np.intc) shape = (len(indptr) - 1, len(vocab)) result_matrix = sp.csr_matrix((values, indices, indptr), shape=shape, dtype=dtype) if fitting and self.sort: feature_names.sort() map_index = np.empty(len(feature_names), dtype=np.int32) for (new_val, f) in enumerate(feature_names): map_index[new_val] = vocab[f] vocab[f] = new_val result_matrix = result_matrix[:, map_index] if self.sparse: result_matrix.sort_indices() else: result_matrix = result_matrix.toarray() if fitting: self.feature_names_ = feature_names self.vocabulary_ = vocab return result_matrix
def fit(self, X, y=None): """Fit the FactorAnalysis model to X using SVD based approach. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : Ignored Ignored parameter. Returns ------- self : object FactorAnalysis class instance. """ self._validate_params() X = self._validate_data(X, copy=self.copy, dtype=np.float64) (n_samples, n_features) = X.shape n_components = self.n_components if n_components is None: n_components = n_features self.mean_ = np.mean(X, axis=0) X -= self.mean_ nsqrt = sqrt(n_samples) llconst = n_features * log(2.0 * np.pi) + n_components var = np.var(X, axis=0) if self.noise_variance_init is None: psi = np.ones(n_features, dtype=X.dtype) else: if len(self.noise_variance_init) != n_features: raise ValueError('noise_variance_init dimension does not with number of features : %d != %d' % (len(self.noise_variance_init), n_features)) psi = np.array(self.noise_variance_init) loglike = [] old_ll = -np.inf SMALL = 1e-12 if self.svd_method == 'lapack': def my_svd(X): (_, s, Vt) = linalg.svd(X, full_matrices=False, check_finite=False) return (s[:n_components], Vt[:n_components], squared_norm(s[n_components:])) else: random_state = check_random_state(self.random_state) def my_svd(X): (_, s, Vt) = randomized_svd(X, n_components, random_state=random_state, n_iter=self.iterated_power) return (s, Vt, squared_norm(X) - squared_norm(s)) for i in range(self.max_iter): sqrt_psi = np.sqrt(psi) + SMALL (_, s, Vt) = linalg.svd(X / (sqrt_psi * nsqrt), full_matrices=False, check_finite=False) (s, Vt, unexp_var) = (s[:n_components], Vt[:n_components], squared_norm(s[n_components:])) s **= 2 W = np.sqrt(np.maximum(s - 1.0, 0.0))[:, np.newaxis] * Vt del Vt W *= sqrt_psi ll = llconst + np.sum(np.log(s)) ll += unexp_var + np.sum(np.log(psi)) ll *= -n_samples / 2.0 loglike.append(ll) if ll - old_ll < self.tol: break old_ll = ll psi = np.maximum(var - np.sum(W ** 2, axis=0), SMALL) else: warnings.warn('FactorAnalysis did not converge.' + ' You might want' + ' to increase the number of iterations.', ConvergenceWarning) self.components_ = W if self.rotation is not None: self.components_ = _ortho_rotation(W.T, method=self.rotation, tol=tol)[:self.n_components] self.noise_variance_ = psi self.loglike_ = loglike self.n_iter_ = i + 1 return self
def fit(self, X, y=None): """Fit the FactorAnalysis model to X using SVD based approach. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : Ignored Ignored parameter. Returns ------- self : object FactorAnalysis class instance. """ self._validate_params() X = self._validate_data(X, copy=self.copy, dtype=np.float64) (n_samples, n_features) = X.shape n_components = self.n_components if n_components is None: n_components = n_features self.mean_ = np.mean(X, axis=0) X -= self.mean_ nsqrt = sqrt(n_samples) llconst = n_features * log(2.0 * np.pi) + n_components var = np.var(X, axis=0) if self.noise_variance_init is None: psi = np.ones(n_features, dtype=X.dtype) else: if len(self.noise_variance_init) != n_features: raise ValueError('noise_variance_init dimension does not with number of features : %d != %d' % (len(self.noise_variance_init), n_features)) psi = np.array(self.noise_variance_init) loglike = [] old_ll = -np.inf SMALL = 1e-12 if self.svd_method == 'lapack': def my_svd(X): (_, s, Vt) = linalg.svd(X, full_matrices=False, check_finite=False) return (s[:n_components], Vt[:n_components], squared_norm(s[n_components:])) else: random_state = check_random_state(self.random_state) def my_svd(X): (_, s, Vt) = randomized_svd(X, n_components, random_state=random_state, n_iter=self.iterated_power) return (s, Vt, squared_norm(X) - squared_norm(s)) for i in range(self.max_iter): sqrt_psi = np.sqrt(psi) + SMALL <DeepExtract> (_, s, Vt) = linalg.svd(X / (sqrt_psi * nsqrt), full_matrices=False, check_finite=False) (s, Vt, unexp_var) = (s[:n_components], Vt[:n_components], squared_norm(s[n_components:])) </DeepExtract> s **= 2 W = np.sqrt(np.maximum(s - 1.0, 0.0))[:, np.newaxis] * Vt del Vt W *= sqrt_psi ll = llconst + np.sum(np.log(s)) ll += unexp_var + np.sum(np.log(psi)) ll *= -n_samples / 2.0 loglike.append(ll) if ll - old_ll < self.tol: break old_ll = ll psi = np.maximum(var - np.sum(W ** 2, axis=0), SMALL) else: warnings.warn('FactorAnalysis did not converge.' + ' You might want' + ' to increase the number of iterations.', ConvergenceWarning) self.components_ = W if self.rotation is not None: <DeepExtract> self.components_ = _ortho_rotation(W.T, method=self.rotation, tol=tol)[:self.n_components] </DeepExtract> self.noise_variance_ = psi self.loglike_ = loglike self.n_iter_ = i + 1 return self
def uniform_labelings_scores(score_func, n_samples, n_clusters_range, n_runs=5): scores = np.zeros((len(n_clusters_range), n_runs)) for (i, n_clusters) in enumerate(n_clusters_range): for j in range(n_runs): labels_a = rng.randint(low=0, high=n_clusters, size=n_samples) labels_b = rng.randint(low=0, high=n_clusters, size=n_samples) scores[i, j] = score_func(labels_a, labels_b) return scores
def uniform_labelings_scores(score_func, n_samples, n_clusters_range, n_runs=5): scores = np.zeros((len(n_clusters_range), n_runs)) for (i, n_clusters) in enumerate(n_clusters_range): for j in range(n_runs): <DeepExtract> labels_a = rng.randint(low=0, high=n_clusters, size=n_samples) </DeepExtract> <DeepExtract> labels_b = rng.randint(low=0, high=n_clusters, size=n_samples) </DeepExtract> scores[i, j] = score_func(labels_a, labels_b) return scores
@pytest.mark.filterwarnings('ignore:The max_iter was reached') def test_sag_classifier_computed_correctly(): """tests if the binary classifier is computed correctly""" alpha = 0.1 n_samples = 50 n_iter = 50 tol = 1e-05 fit_intercept = True (X, y) = make_blobs(n_samples=n_samples, centers=2, 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) y_tmp = np.ones(n_samples) y_tmp[y != classes[1]] = -1 y = y_tmp clf1 = LogisticRegression(solver='sag', C=1.0 / alpha / n_samples, max_iter=n_iter, tol=tol, random_state=77, fit_intercept=fit_intercept, multi_class='ovr') clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) 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(n_iter * n_samples) if sparse: decay = 0.01 counter = 0 for epoch in range(n_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[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 (spweights, spintercept) = (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(n_iter * n_samples) if True: decay = 0.01 counter = 0 for epoch in range(n_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[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) assert_array_almost_equal(clf1.coef_.ravel(), spweights.ravel(), decimal=2) assert_almost_equal(clf1.intercept_, spintercept, decimal=1) assert_array_almost_equal(clf2.coef_.ravel(), spweights2.ravel(), decimal=2) assert_almost_equal(clf2.intercept_, spintercept2, decimal=1)
@pytest.mark.filterwarnings('ignore:The max_iter was reached') def test_sag_classifier_computed_correctly(): """tests if the binary classifier is computed correctly""" alpha = 0.1 n_samples = 50 n_iter = 50 tol = 1e-05 fit_intercept = True (X, y) = make_blobs(n_samples=n_samples, centers=2, 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) y_tmp = np.ones(n_samples) y_tmp[y != classes[1]] = -1 y = y_tmp clf1 = LogisticRegression(solver='sag', C=1.0 / alpha / n_samples, max_iter=n_iter, tol=tol, random_state=77, fit_intercept=fit_intercept, multi_class='ovr') clf2 = clone(clf1) clf1.fit(X, y) clf2.fit(sp.csr_matrix(X), y) <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(n_iter * n_samples) if sparse: decay = 0.01 counter = 0 for epoch in range(n_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[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 (spweights, spintercept) = (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(n_iter * n_samples) if True: decay = 0.01 counter = 0 for epoch in range(n_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[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> assert_array_almost_equal(clf1.coef_.ravel(), spweights.ravel(), decimal=2) assert_almost_equal(clf1.intercept_, spintercept, decimal=1) assert_array_almost_equal(clf2.coef_.ravel(), spweights2.ravel(), decimal=2) assert_almost_equal(clf2.intercept_, spintercept2, decimal=1)
@ignore_warnings def check_estimators_dtypes(name, estimator_orig): rnd = np.random.RandomState(0) X_train_32 = 3 * rnd.uniform(size=(20, 5)).astype(np.float32) if '1darray' in _safe_tags(estimator_orig, key='X_types'): X_train_32 = X_train_32[:, 0] if _safe_tags(estimator_orig, key='requires_positive_X'): X_train_32 = X_train_32 - X_train_32.min() if 'categorical' in _safe_tags(estimator_orig, key='X_types'): X_train_32 = (X_train_32 - X_train_32.min()).astype(np.int32) if estimator_orig.__class__.__name__ == 'SkewedChi2Sampler': X_train_32 = X_train_32 - X_train_32.min() if _is_pairwise_metric(estimator_orig): X_train_32 = pairwise_distances(X_train_32, metric='euclidean') elif _safe_tags(estimator_orig, key='pairwise'): X_train_32 = kernel(X_train_32, X_train_32) X_train_32 = X_train_32 X_train_64 = X_train_32.astype(np.float64) X_train_int_64 = X_train_32.astype(np.int64) X_train_int_32 = X_train_32.astype(np.int32) y = X_train_int_64[:, 0] if _safe_tags(estimator_orig, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(estimator_orig, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(estimator_orig, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y methods = ['predict', 'transform', 'decision_function', 'predict_proba'] for X_train in [X_train_32, X_train_64, X_train_int_64, X_train_int_32]: estimator = clone(estimator_orig) set_random_state(estimator, 1) estimator.fit(X_train, y) for method in methods: if hasattr(estimator, method): getattr(estimator, method)(X_train)
@ignore_warnings def check_estimators_dtypes(name, estimator_orig): rnd = np.random.RandomState(0) X_train_32 = 3 * rnd.uniform(size=(20, 5)).astype(np.float32) <DeepExtract> if '1darray' in _safe_tags(estimator_orig, key='X_types'): X_train_32 = X_train_32[:, 0] if _safe_tags(estimator_orig, key='requires_positive_X'): X_train_32 = X_train_32 - X_train_32.min() if 'categorical' in _safe_tags(estimator_orig, key='X_types'): X_train_32 = (X_train_32 - X_train_32.min()).astype(np.int32) if estimator_orig.__class__.__name__ == 'SkewedChi2Sampler': X_train_32 = X_train_32 - X_train_32.min() if _is_pairwise_metric(estimator_orig): X_train_32 = pairwise_distances(X_train_32, metric='euclidean') elif _safe_tags(estimator_orig, key='pairwise'): X_train_32 = kernel(X_train_32, X_train_32) X_train_32 = X_train_32 </DeepExtract> X_train_64 = X_train_32.astype(np.float64) X_train_int_64 = X_train_32.astype(np.int64) X_train_int_32 = X_train_32.astype(np.int32) y = X_train_int_64[:, 0] <DeepExtract> if _safe_tags(estimator_orig, key='requires_positive_y'): y += 1 + abs(y.min()) if _safe_tags(estimator_orig, key='binary_only') and y.size > 0: y = np.where(y == y.flat[0], y, y.flat[0] + 1) if _safe_tags(estimator_orig, key='multioutput_only'): y = np.reshape(y, (-1, 1)) y = y </DeepExtract> methods = ['predict', 'transform', 'decision_function', 'predict_proba'] for X_train in [X_train_32, X_train_64, X_train_int_64, X_train_int_32]: estimator = clone(estimator_orig) set_random_state(estimator, 1) estimator.fit(X_train, y) for method in methods: if hasattr(estimator, method): getattr(estimator, method)(X_train)
def fit(self, X, y): """Fit Gaussian process classification model. Parameters ---------- X : array-like of shape (n_samples, n_features) or list of object Feature vectors or other representations of training data. y : array-like of shape (n_samples,) Target values, must be binary. Returns ------- self : returns an instance of self. """ if self.kernel is None: self.kernel_ = C(1.0, constant_value_bounds='fixed') * RBF(1.0, length_scale_bounds='fixed') else: self.kernel_ = clone(self.kernel) self.rng = check_random_state(self.random_state) self.X_train_ = np.copy(X) if self.copy_X_train else X label_encoder = LabelEncoder() self.y_train_ = label_encoder.fit_transform(y) self.classes_ = label_encoder.classes_ if self.classes_.size > 2: raise ValueError('%s supports only binary classification. y contains classes %s' % (self.__class__.__name__, self.classes_)) elif self.classes_.size == 1: raise ValueError('{0:s} requires 2 classes; got {1:d} class'.format(self.__class__.__name__, self.classes_.size)) if self.optimizer is not None and self.kernel_.n_dims > 0: def obj_func(theta, eval_gradient=True): if eval_gradient: if theta is None: if True: raise ValueError('Gradient can only be evaluated for theta!=None') (lml, grad) = self.log_marginal_likelihood_value_ if False: kernel = self.kernel_.clone_with_theta(theta) else: kernel = self.kernel_ kernel.theta = theta if True: (K, K_gradient) = kernel(self.X_train_, eval_gradient=True) else: K = kernel(self.X_train_) (Z, (pi, W_sr, L, b, a)) = self._posterior_mode(K, return_temporaries=True) if not True: (lml, grad) = Z d_Z = np.empty(theta.shape[0]) R = W_sr[:, np.newaxis] * cho_solve((L, True), np.diag(W_sr)) C = solve(L, W_sr[:, np.newaxis] * K) s_2 = -0.5 * (np.diag(K) - np.einsum('ij, ij -> j', C, C)) * (pi * (1 - pi) * (1 - 2 * pi)) for j in range(d_Z.shape[0]): C = K_gradient[:, :, j] s_1 = 0.5 * a.T.dot(C).dot(a) - 0.5 * R.T.ravel().dot(C.ravel()) b = C.dot(self.y_train_ - pi) s_3 = b - K.dot(R.dot(b)) d_Z[j] = s_1 + s_2.T.dot(s_3) (lml, grad) = (Z, d_Z) return (-lml, -grad) else: return -self.log_marginal_likelihood(theta, clone_kernel=False) optima = [self._constrained_optimization(obj_func, self.kernel_.theta, self.kernel_.bounds)] if self.n_restarts_optimizer > 0: if not np.isfinite(self.kernel_.bounds).all(): raise ValueError('Multiple optimizer restarts (n_restarts_optimizer>0) requires that all bounds are finite.') bounds = self.kernel_.bounds for iteration in range(self.n_restarts_optimizer): theta_initial = np.exp(self.rng.uniform(bounds[:, 0], bounds[:, 1])) optima.append(self._constrained_optimization(obj_func, theta_initial, bounds)) lml_values = list(map(itemgetter(1), optima)) self.kernel_.theta = optima[np.argmin(lml_values)][0] self.kernel_._check_bounds_params() self.log_marginal_likelihood_value_ = -np.min(lml_values) else: if self.kernel_.theta is None: if eval_gradient: raise ValueError('Gradient can only be evaluated for theta!=None') self.log_marginal_likelihood_value_ = self.log_marginal_likelihood_value_ if clone_kernel: kernel = self.kernel_.clone_with_theta(self.kernel_.theta) else: kernel = self.kernel_ kernel.theta = self.kernel_.theta if eval_gradient: (K, K_gradient) = kernel(self.X_train_, eval_gradient=True) else: K = kernel(self.X_train_) (Z, (pi, W_sr, L, b, a)) = self._posterior_mode(K, return_temporaries=True) if not eval_gradient: self.log_marginal_likelihood_value_ = Z d_Z = np.empty(self.kernel_.theta.shape[0]) R = W_sr[:, np.newaxis] * cho_solve((L, True), np.diag(W_sr)) C = solve(L, W_sr[:, np.newaxis] * K) s_2 = -0.5 * (np.diag(K) - np.einsum('ij, ij -> j', C, C)) * (pi * (1 - pi) * (1 - 2 * pi)) for j in range(d_Z.shape[0]): C = K_gradient[:, :, j] s_1 = 0.5 * a.T.dot(C).dot(a) - 0.5 * R.T.ravel().dot(C.ravel()) b = C.dot(self.y_train_ - pi) s_3 = b - K.dot(R.dot(b)) d_Z[j] = s_1 + s_2.T.dot(s_3) self.log_marginal_likelihood_value_ = (Z, d_Z) if self.n_classes_ == 2: K = self.base_estimator_.kernel_ else: K = CompoundKernel([estimator.kernel_ for estimator in self.base_estimator_.estimators_]) if self.warm_start and hasattr(self, 'f_cached') and (self.f_cached.shape == self.y_train_.shape): f = self.f_cached else: f = np.zeros_like(self.y_train_, dtype=np.float64) log_marginal_likelihood = -np.inf for _ in range(self.max_iter_predict): pi = expit(f) W = pi * (1 - pi) W_sr = np.sqrt(W) W_sr_K = W_sr[:, np.newaxis] * K B = np.eye(W.shape[0]) + W_sr_K * W_sr L = cholesky(B, lower=True) b = W * f + (self.y_train_ - pi) a = b - W_sr * cho_solve((L, True), W_sr_K.dot(b)) f = K.dot(a) lml = -0.5 * a.T.dot(f) - np.log1p(np.exp(-(self.y_train_ * 2 - 1) * f)).sum() - np.log(np.diag(L)).sum() if lml - log_marginal_likelihood < 1e-10: break log_marginal_likelihood = lml self.f_cached = f if True: (_, (self.pi_, self.W_sr_, self.L_, _, _)) = (log_marginal_likelihood, (pi, W_sr, L, b, a)) else: (_, (self.pi_, self.W_sr_, self.L_, _, _)) = log_marginal_likelihood return self
def fit(self, X, y): """Fit Gaussian process classification model. Parameters ---------- X : array-like of shape (n_samples, n_features) or list of object Feature vectors or other representations of training data. y : array-like of shape (n_samples,) Target values, must be binary. Returns ------- self : returns an instance of self. """ if self.kernel is None: self.kernel_ = C(1.0, constant_value_bounds='fixed') * RBF(1.0, length_scale_bounds='fixed') else: self.kernel_ = clone(self.kernel) self.rng = check_random_state(self.random_state) self.X_train_ = np.copy(X) if self.copy_X_train else X label_encoder = LabelEncoder() self.y_train_ = label_encoder.fit_transform(y) self.classes_ = label_encoder.classes_ if self.classes_.size > 2: raise ValueError('%s supports only binary classification. y contains classes %s' % (self.__class__.__name__, self.classes_)) elif self.classes_.size == 1: raise ValueError('{0:s} requires 2 classes; got {1:d} class'.format(self.__class__.__name__, self.classes_.size)) if self.optimizer is not None and self.kernel_.n_dims > 0: def obj_func(theta, eval_gradient=True): if eval_gradient: <DeepExtract> if theta is None: if True: raise ValueError('Gradient can only be evaluated for theta!=None') (lml, grad) = self.log_marginal_likelihood_value_ if False: kernel = self.kernel_.clone_with_theta(theta) else: kernel = self.kernel_ kernel.theta = theta if True: (K, K_gradient) = kernel(self.X_train_, eval_gradient=True) else: K = kernel(self.X_train_) (Z, (pi, W_sr, L, b, a)) = self._posterior_mode(K, return_temporaries=True) if not True: (lml, grad) = Z d_Z = np.empty(theta.shape[0]) R = W_sr[:, np.newaxis] * cho_solve((L, True), np.diag(W_sr)) C = solve(L, W_sr[:, np.newaxis] * K) s_2 = -0.5 * (np.diag(K) - np.einsum('ij, ij -> j', C, C)) * (pi * (1 - pi) * (1 - 2 * pi)) for j in range(d_Z.shape[0]): C = K_gradient[:, :, j] s_1 = 0.5 * a.T.dot(C).dot(a) - 0.5 * R.T.ravel().dot(C.ravel()) b = C.dot(self.y_train_ - pi) s_3 = b - K.dot(R.dot(b)) d_Z[j] = s_1 + s_2.T.dot(s_3) (lml, grad) = (Z, d_Z) </DeepExtract> return (-lml, -grad) else: return -self.log_marginal_likelihood(theta, clone_kernel=False) optima = [self._constrained_optimization(obj_func, self.kernel_.theta, self.kernel_.bounds)] if self.n_restarts_optimizer > 0: if not np.isfinite(self.kernel_.bounds).all(): raise ValueError('Multiple optimizer restarts (n_restarts_optimizer>0) requires that all bounds are finite.') bounds = self.kernel_.bounds for iteration in range(self.n_restarts_optimizer): theta_initial = np.exp(self.rng.uniform(bounds[:, 0], bounds[:, 1])) optima.append(self._constrained_optimization(obj_func, theta_initial, bounds)) lml_values = list(map(itemgetter(1), optima)) self.kernel_.theta = optima[np.argmin(lml_values)][0] self.kernel_._check_bounds_params() self.log_marginal_likelihood_value_ = -np.min(lml_values) else: <DeepExtract> if self.kernel_.theta is None: if eval_gradient: raise ValueError('Gradient can only be evaluated for theta!=None') self.log_marginal_likelihood_value_ = self.log_marginal_likelihood_value_ if clone_kernel: kernel = self.kernel_.clone_with_theta(self.kernel_.theta) else: kernel = self.kernel_ kernel.theta = self.kernel_.theta if eval_gradient: (K, K_gradient) = kernel(self.X_train_, eval_gradient=True) else: K = kernel(self.X_train_) (Z, (pi, W_sr, L, b, a)) = self._posterior_mode(K, return_temporaries=True) if not eval_gradient: self.log_marginal_likelihood_value_ = Z d_Z = np.empty(self.kernel_.theta.shape[0]) R = W_sr[:, np.newaxis] * cho_solve((L, True), np.diag(W_sr)) C = solve(L, W_sr[:, np.newaxis] * K) s_2 = -0.5 * (np.diag(K) - np.einsum('ij, ij -> j', C, C)) * (pi * (1 - pi) * (1 - 2 * pi)) for j in range(d_Z.shape[0]): C = K_gradient[:, :, j] s_1 = 0.5 * a.T.dot(C).dot(a) - 0.5 * R.T.ravel().dot(C.ravel()) b = C.dot(self.y_train_ - pi) s_3 = b - K.dot(R.dot(b)) d_Z[j] = s_1 + s_2.T.dot(s_3) self.log_marginal_likelihood_value_ = (Z, d_Z) </DeepExtract> <DeepExtract> if self.n_classes_ == 2: K = self.base_estimator_.kernel_ else: K = CompoundKernel([estimator.kernel_ for estimator in self.base_estimator_.estimators_]) </DeepExtract> <DeepExtract> if self.warm_start and hasattr(self, 'f_cached') and (self.f_cached.shape == self.y_train_.shape): f = self.f_cached else: f = np.zeros_like(self.y_train_, dtype=np.float64) log_marginal_likelihood = -np.inf for _ in range(self.max_iter_predict): pi = expit(f) W = pi * (1 - pi) W_sr = np.sqrt(W) W_sr_K = W_sr[:, np.newaxis] * K B = np.eye(W.shape[0]) + W_sr_K * W_sr L = cholesky(B, lower=True) b = W * f + (self.y_train_ - pi) a = b - W_sr * cho_solve((L, True), W_sr_K.dot(b)) f = K.dot(a) lml = -0.5 * a.T.dot(f) - np.log1p(np.exp(-(self.y_train_ * 2 - 1) * f)).sum() - np.log(np.diag(L)).sum() if lml - log_marginal_likelihood < 1e-10: break log_marginal_likelihood = lml self.f_cached = f if True: (_, (self.pi_, self.W_sr_, self.L_, _, _)) = (log_marginal_likelihood, (pi, W_sr, L, b, a)) else: (_, (self.pi_, self.W_sr_, self.L_, _, _)) = log_marginal_likelihood </DeepExtract> return self
def paired_distances(X, Y, *, metric='euclidean', **kwds): """ Compute the paired distances between X and Y. Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc... Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : ndarray of shape (n_samples, n_features) Array 1 for distance computation. Y : ndarray of shape (n_samples, n_features) Array 2 for distance computation. metric : str or callable, default="euclidean" The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options specified in PAIRED_DISTANCES, including "euclidean", "manhattan", or "cosine". Alternatively, 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 from `X` as input and return a value indicating the distance between them. **kwds : dict Unused parameters. Returns ------- distances : ndarray of shape (n_samples,) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- pairwise_distances : Computes the distance between every pair of samples. Examples -------- >>> from sklearn.metrics.pairwise import paired_distances >>> X = [[0, 1], [1, 1]] >>> Y = [[0, 1], [2, 1]] >>> paired_distances(X, Y) array([0., 1.]) """ if metric in PAIRED_DISTANCES: func = PAIRED_DISTANCES[metric] return func(X, Y) elif callable(metric): (X, Y) = check_pairwise_arrays(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)) (X, Y) = (X, Y) distances = np.zeros(len(X)) for i in range(len(X)): distances[i] = metric(X[i], Y[i]) return distances else: raise ValueError('Unknown distance %s' % metric)
def paired_distances(X, Y, *, metric='euclidean', **kwds): """ Compute the paired distances between X and Y. Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc... Read more in the :ref:`User Guide <metrics>`. Parameters ---------- X : ndarray of shape (n_samples, n_features) Array 1 for distance computation. Y : ndarray of shape (n_samples, n_features) Array 2 for distance computation. metric : str or callable, default="euclidean" The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options specified in PAIRED_DISTANCES, including "euclidean", "manhattan", or "cosine". Alternatively, 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 from `X` as input and return a value indicating the distance between them. **kwds : dict Unused parameters. Returns ------- distances : ndarray of shape (n_samples,) Returns the distances between the row vectors of `X` and the row vectors of `Y`. See Also -------- pairwise_distances : Computes the distance between every pair of samples. Examples -------- >>> from sklearn.metrics.pairwise import paired_distances >>> X = [[0, 1], [1, 1]] >>> Y = [[0, 1], [2, 1]] >>> paired_distances(X, Y) array([0., 1.]) """ if metric in PAIRED_DISTANCES: func = PAIRED_DISTANCES[metric] return func(X, Y) elif callable(metric): <DeepExtract> (X, Y) = check_pairwise_arrays(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)) (X, Y) = (X, Y) </DeepExtract> distances = np.zeros(len(X)) for i in range(len(X)): distances[i] = metric(X[i], Y[i]) return distances else: raise ValueError('Unknown distance %s' % metric)
@validate_params({'shape': [tuple], 'n_clusters': [Interval(Integral, 1, None, closed='left'), 'array-like'], 'noise': [Interval(Real, 0, None, closed='left')], 'minval': [Interval(Real, None, None, closed='neither')], 'maxval': [Interval(Real, None, None, closed='neither')], 'shuffle': ['boolean'], 'random_state': ['random_state']}) def make_checkerboard(shape, n_clusters, *, noise=0.0, minval=10, maxval=100, shuffle=True, random_state=None): """Generate an array with block checkerboard structure for biclustering. Read more in the :ref:`User Guide <sample_generators>`. Parameters ---------- shape : tuple of shape (n_rows, n_cols) The shape of the result. n_clusters : int or array-like or shape (n_row_clusters, n_column_clusters) The number of row and column clusters. noise : float, default=0.0 The standard deviation of the gaussian noise. minval : float, default=10 Minimum value of a bicluster. maxval : float, default=100 Maximum value of a bicluster. shuffle : bool, default=True Shuffle the samples. 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 `shape` The generated array. rows : ndarray of shape (n_clusters, X.shape[0]) The indicators for cluster membership of each row. cols : ndarray of shape (n_clusters, X.shape[1]) The indicators for cluster membership of each column. See Also -------- make_biclusters : Generate an array with constant block diagonal structure for biclustering. References ---------- .. [1] Kluger, Y., Basri, R., Chang, J. T., & Gerstein, M. (2003). Spectral biclustering of microarray data: coclustering genes and conditions. Genome research, 13(4), 703-716. """ generator = check_random_state(random_state) if hasattr(n_clusters, '__len__'): (n_row_clusters, n_col_clusters) = n_clusters else: n_row_clusters = n_col_clusters = n_clusters (n_rows, n_cols) = shape row_sizes = generator.multinomial(n_rows, np.repeat(1.0 / n_row_clusters, n_row_clusters)) col_sizes = generator.multinomial(n_cols, np.repeat(1.0 / n_col_clusters, n_col_clusters)) row_labels = np.hstack([np.repeat(val, rep) for (val, rep) in zip(range(n_row_clusters), row_sizes)]) col_labels = np.hstack([np.repeat(val, rep) for (val, rep) in zip(range(n_col_clusters), col_sizes)]) result = np.zeros(shape, dtype=np.float64) for i in range(n_row_clusters): for j in range(n_col_clusters): selector = np.outer(row_labels == i, col_labels == j) result[selector] += generator.uniform(minval, maxval) if noise > 0: result += generator.normal(scale=noise, size=result.shape) if shuffle: generator = check_random_state(random_state) (n_rows, n_cols) = result.shape row_idx = generator.permutation(n_rows) col_idx = generator.permutation(n_cols) result = result[row_idx][:, col_idx] (result, row_idx, col_idx) = (result, row_idx, col_idx) row_labels = row_labels[row_idx] col_labels = col_labels[col_idx] rows = np.vstack([row_labels == label for label in range(n_row_clusters) for _ in range(n_col_clusters)]) cols = np.vstack([col_labels == label for _ in range(n_row_clusters) for label in range(n_col_clusters)]) return (result, rows, cols)
@validate_params({'shape': [tuple], 'n_clusters': [Interval(Integral, 1, None, closed='left'), 'array-like'], 'noise': [Interval(Real, 0, None, closed='left')], 'minval': [Interval(Real, None, None, closed='neither')], 'maxval': [Interval(Real, None, None, closed='neither')], 'shuffle': ['boolean'], 'random_state': ['random_state']}) def make_checkerboard(shape, n_clusters, *, noise=0.0, minval=10, maxval=100, shuffle=True, random_state=None): """Generate an array with block checkerboard structure for biclustering. Read more in the :ref:`User Guide <sample_generators>`. Parameters ---------- shape : tuple of shape (n_rows, n_cols) The shape of the result. n_clusters : int or array-like or shape (n_row_clusters, n_column_clusters) The number of row and column clusters. noise : float, default=0.0 The standard deviation of the gaussian noise. minval : float, default=10 Minimum value of a bicluster. maxval : float, default=100 Maximum value of a bicluster. shuffle : bool, default=True Shuffle the samples. 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 `shape` The generated array. rows : ndarray of shape (n_clusters, X.shape[0]) The indicators for cluster membership of each row. cols : ndarray of shape (n_clusters, X.shape[1]) The indicators for cluster membership of each column. See Also -------- make_biclusters : Generate an array with constant block diagonal structure for biclustering. References ---------- .. [1] Kluger, Y., Basri, R., Chang, J. T., & Gerstein, M. (2003). Spectral biclustering of microarray data: coclustering genes and conditions. Genome research, 13(4), 703-716. """ generator = check_random_state(random_state) if hasattr(n_clusters, '__len__'): (n_row_clusters, n_col_clusters) = n_clusters else: n_row_clusters = n_col_clusters = n_clusters (n_rows, n_cols) = shape row_sizes = generator.multinomial(n_rows, np.repeat(1.0 / n_row_clusters, n_row_clusters)) col_sizes = generator.multinomial(n_cols, np.repeat(1.0 / n_col_clusters, n_col_clusters)) row_labels = np.hstack([np.repeat(val, rep) for (val, rep) in zip(range(n_row_clusters), row_sizes)]) col_labels = np.hstack([np.repeat(val, rep) for (val, rep) in zip(range(n_col_clusters), col_sizes)]) result = np.zeros(shape, dtype=np.float64) for i in range(n_row_clusters): for j in range(n_col_clusters): selector = np.outer(row_labels == i, col_labels == j) result[selector] += generator.uniform(minval, maxval) if noise > 0: result += generator.normal(scale=noise, size=result.shape) if shuffle: <DeepExtract> generator = check_random_state(random_state) (n_rows, n_cols) = result.shape row_idx = generator.permutation(n_rows) col_idx = generator.permutation(n_cols) result = result[row_idx][:, col_idx] (result, row_idx, col_idx) = (result, row_idx, col_idx) </DeepExtract> row_labels = row_labels[row_idx] col_labels = col_labels[col_idx] rows = np.vstack([row_labels == label for label in range(n_row_clusters) for _ in range(n_col_clusters)]) cols = np.vstack([col_labels == label for _ in range(n_row_clusters) for label in range(n_col_clusters)]) return (result, rows, cols)
@hides def score(self, X, y, *args, **kwargs): check_is_fitted(self) return 1.0
@hides def score(self, X, y, *args, **kwargs): <DeepExtract> check_is_fitted(self) </DeepExtract> return 1.0
def test_classification_report_multiclass_with_label_detection(): 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 0 0.83 0.79 0.81 24\n 1 0.33 0.10 0.15 31\n 2 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) assert report == expected_report
def test_classification_report_multiclass_with_label_detection(): 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 0 0.83 0.79 0.81 24\n 1 0.33 0.10 0.15 31\n 2 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) assert report == expected_report
def _spatial_median(X, max_iter=300, tol=0.001): """Spatial median (L1 median). The spatial median is member of a class of so-called M-estimators which are defined by an optimization problem. Given a number of p points in an n-dimensional space, the point x minimizing the sum of all distances to the p other points is called spatial median. Parameters ---------- X : array-like of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. max_iter : int, default=300 Maximum number of iterations. tol : float, default=1.e-3 Stop the algorithm if spatial_median has converged. Returns ------- spatial_median : ndarray of shape = (n_features,) Spatial median. n_iter : int Number of iterations needed. References ---------- - On Computation of Spatial Median for Robust Data Mining, 2005 T. Kärkkäinen and S. Äyrämö http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf """ if X.shape[1] == 1: return (1, np.median(X.ravel(), keepdims=True)) tol **= 2 spatial_median_old = np.mean(X, axis=0) for n_iter in range(max_iter): diff = X - spatial_median_old diff_norm = np.sqrt(np.sum(diff ** 2, axis=1)) mask = diff_norm >= _EPSILON is_x_old_in_X = int(mask.sum() < X.shape[0]) diff = diff[mask] diff_norm = diff_norm[mask][:, np.newaxis] quotient_norm = linalg.norm(np.sum(diff / diff_norm, axis=0)) if quotient_norm > _EPSILON: new_direction = np.sum(X[mask, :] / diff_norm, axis=0) / np.sum(1 / diff_norm, axis=0) else: new_direction = 1.0 quotient_norm = 1.0 spatial_median = max(0.0, 1.0 - is_x_old_in_X / quotient_norm) * new_direction + min(1.0, is_x_old_in_X / quotient_norm) * spatial_median_old if np.sum((spatial_median_old - spatial_median) ** 2) < tol: break else: spatial_median_old = spatial_median else: warnings.warn('Maximum number of iterations {max_iter} reached in spatial median for TheilSen regressor.'.format(max_iter=max_iter), ConvergenceWarning) return (n_iter, spatial_median)
def _spatial_median(X, max_iter=300, tol=0.001): """Spatial median (L1 median). The spatial median is member of a class of so-called M-estimators which are defined by an optimization problem. Given a number of p points in an n-dimensional space, the point x minimizing the sum of all distances to the p other points is called spatial median. Parameters ---------- X : array-like of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. max_iter : int, default=300 Maximum number of iterations. tol : float, default=1.e-3 Stop the algorithm if spatial_median has converged. Returns ------- spatial_median : ndarray of shape = (n_features,) Spatial median. n_iter : int Number of iterations needed. References ---------- - On Computation of Spatial Median for Robust Data Mining, 2005 T. Kärkkäinen and S. Äyrämö http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf """ if X.shape[1] == 1: return (1, np.median(X.ravel(), keepdims=True)) tol **= 2 spatial_median_old = np.mean(X, axis=0) for n_iter in range(max_iter): <DeepExtract> diff = X - spatial_median_old diff_norm = np.sqrt(np.sum(diff ** 2, axis=1)) mask = diff_norm >= _EPSILON is_x_old_in_X = int(mask.sum() < X.shape[0]) diff = diff[mask] diff_norm = diff_norm[mask][:, np.newaxis] quotient_norm = linalg.norm(np.sum(diff / diff_norm, axis=0)) if quotient_norm > _EPSILON: new_direction = np.sum(X[mask, :] / diff_norm, axis=0) / np.sum(1 / diff_norm, axis=0) else: new_direction = 1.0 quotient_norm = 1.0 spatial_median = max(0.0, 1.0 - is_x_old_in_X / quotient_norm) * new_direction + min(1.0, is_x_old_in_X / quotient_norm) * spatial_median_old </DeepExtract> if np.sum((spatial_median_old - spatial_median) ** 2) < tol: break else: spatial_median_old = spatial_median else: warnings.warn('Maximum number of iterations {max_iter} reached in spatial median for TheilSen regressor.'.format(max_iter=max_iter), ConvergenceWarning) return (n_iter, spatial_median)
def transform(self, X): """Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by `transform` will typically be dense. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data to transform. Returns ------- X_new : ndarray of shape (n_samples, n_clusters) X transformed in the new space. """ check_is_fitted(self) X = self._validate_data(X, accept_sparse='csr', reset=False, dtype=[np.float64, np.float32], order='C', accept_large_sparse=False) X = X return self._transform(X)
def transform(self, X): """Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by `transform` will typically be dense. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data to transform. Returns ------- X_new : ndarray of shape (n_samples, n_clusters) X transformed in the new space. """ check_is_fitted(self) <DeepExtract> X = self._validate_data(X, accept_sparse='csr', reset=False, dtype=[np.float64, np.float32], order='C', accept_large_sparse=False) X = X </DeepExtract> return self._transform(X)
def fit_predict(X, y=None): """Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for `max_iter` times until the change of likelihood or lower bound is less than `tol`, otherwise, a :class:`~sklearn.exceptions.ConvergenceWarning` is raised. After fitting, it predicts the most probable label for the input data points. .. versionadded:: 0.20 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. y : Ignored Not used, present for API consistency by convention. Returns ------- labels : array, shape (n_samples,) Component labels. """ self._validate_params() X = self._validate_data(X, dtype=[np.float64, np.float32], ensure_min_samples=2) if X.shape[0] < self.n_components: raise ValueError(f'Expected n_samples >= n_components but got n_components = {self.n_components}, n_samples = {X.shape[0]}') pass do_init = not (self.warm_start and hasattr(self, 'converged_')) n_init = self.n_init if do_init else 1 max_lower_bound = -np.inf self.converged_ = False random_state = check_random_state(self.random_state) (n_samples, _) = X.shape for init in range(n_init): if self.verbose == 1: print('Initialization %d' % init) elif self.verbose >= 2: print('Initialization %d' % init) self._init_prev_time = time() self._iter_prev_time = self._init_prev_time if do_init: (n_samples, _) = X.shape if self.init_params == 'kmeans': resp = np.zeros((n_samples, self.n_components)) label = cluster.KMeans(n_clusters=self.n_components, n_init=1, random_state=random_state).fit(X).labels_ resp[np.arange(n_samples), label] = 1 elif self.init_params == 'random': resp = random_state.uniform(size=(n_samples, self.n_components)) resp /= resp.sum(axis=1)[:, np.newaxis] elif self.init_params == 'random_from_data': resp = np.zeros((n_samples, self.n_components)) indices = random_state.choice(n_samples, size=self.n_components, replace=False) resp[indices, np.arange(self.n_components)] = 1 elif self.init_params == 'k-means++': resp = np.zeros((n_samples, self.n_components)) (_, indices) = kmeans_plusplus(X, self.n_components, random_state=random_state) resp[indices, np.arange(self.n_components)] = 1 self._initialize(X, resp) lower_bound = -np.inf if do_init else self.lower_bound_ if self.max_iter == 0: pass best_n_iter = 0 else: for n_iter in range(1, self.max_iter + 1): prev_lower_bound = lower_bound (log_prob_norm, log_resp) = self._estimate_log_prob_resp(X) (log_prob_norm, log_resp) = (np.mean(log_prob_norm), log_resp) pass lower_bound = self._compute_lower_bound(log_resp, log_prob_norm) change = lower_bound - prev_lower_bound if n_iter % self.verbose_interval == 0: if self.verbose == 1: print(' Iteration %d' % n_iter) elif self.verbose >= 2: cur_time = time() print(' Iteration %d\t time lapse %.5fs\t ll change %.5f' % (n_iter, cur_time - self._iter_prev_time, change)) self._iter_prev_time = cur_time if abs(change) < self.tol: self.converged_ = True break if self.verbose == 1: print('Initialization converged: %s' % self.converged_) elif self.verbose >= 2: print('Initialization converged: %s\t time lapse %.5fs\t ll %.5f' % (self.converged_, time() - self._init_prev_time, lower_bound)) if lower_bound > max_lower_bound or max_lower_bound == -np.inf: max_lower_bound = lower_bound pass best_n_iter = n_iter if not self.converged_ and self.max_iter > 0: warnings.warn('Initialization %d did not converge. Try different init parameters, or increase max_iter, tol or check for degenerate data.' % (init + 1), ConvergenceWarning) pass self.n_iter_ = best_n_iter self.lower_bound_ = max_lower_bound (log_prob_norm, log_resp) = self._estimate_log_prob_resp(X) (_, log_resp) = (np.mean(log_prob_norm), log_resp) return log_resp.argmax(axis=1)
def fit_predict(X, y=None): """Estimate model parameters using X and predict the labels for X. The method fits the model n_init times and sets the parameters with which the model has the largest likelihood or lower bound. Within each trial, the method iterates between E-step and M-step for `max_iter` times until the change of likelihood or lower bound is less than `tol`, otherwise, a :class:`~sklearn.exceptions.ConvergenceWarning` is raised. After fitting, it predicts the most probable label for the input data points. .. versionadded:: 0.20 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. y : Ignored Not used, present for API consistency by convention. Returns ------- labels : array, shape (n_samples,) Component labels. """ self._validate_params() X = self._validate_data(X, dtype=[np.float64, np.float32], ensure_min_samples=2) if X.shape[0] < self.n_components: raise ValueError(f'Expected n_samples >= n_components but got n_components = {self.n_components}, n_samples = {X.shape[0]}') <DeepExtract> pass </DeepExtract> do_init = not (self.warm_start and hasattr(self, 'converged_')) n_init = self.n_init if do_init else 1 max_lower_bound = -np.inf self.converged_ = False random_state = check_random_state(self.random_state) (n_samples, _) = X.shape for init in range(n_init): <DeepExtract> if self.verbose == 1: print('Initialization %d' % init) elif self.verbose >= 2: print('Initialization %d' % init) self._init_prev_time = time() self._iter_prev_time = self._init_prev_time </DeepExtract> if do_init: <DeepExtract> (n_samples, _) = X.shape if self.init_params == 'kmeans': resp = np.zeros((n_samples, self.n_components)) label = cluster.KMeans(n_clusters=self.n_components, n_init=1, random_state=random_state).fit(X).labels_ resp[np.arange(n_samples), label] = 1 elif self.init_params == 'random': resp = random_state.uniform(size=(n_samples, self.n_components)) resp /= resp.sum(axis=1)[:, np.newaxis] elif self.init_params == 'random_from_data': resp = np.zeros((n_samples, self.n_components)) indices = random_state.choice(n_samples, size=self.n_components, replace=False) resp[indices, np.arange(self.n_components)] = 1 elif self.init_params == 'k-means++': resp = np.zeros((n_samples, self.n_components)) (_, indices) = kmeans_plusplus(X, self.n_components, random_state=random_state) resp[indices, np.arange(self.n_components)] = 1 self._initialize(X, resp) </DeepExtract> lower_bound = -np.inf if do_init else self.lower_bound_ if self.max_iter == 0: <DeepExtract> pass </DeepExtract> best_n_iter = 0 else: for n_iter in range(1, self.max_iter + 1): prev_lower_bound = lower_bound <DeepExtract> (log_prob_norm, log_resp) = self._estimate_log_prob_resp(X) (log_prob_norm, log_resp) = (np.mean(log_prob_norm), log_resp) </DeepExtract> <DeepExtract> pass </DeepExtract> lower_bound = self._compute_lower_bound(log_resp, log_prob_norm) change = lower_bound - prev_lower_bound <DeepExtract> if n_iter % self.verbose_interval == 0: if self.verbose == 1: print(' Iteration %d' % n_iter) elif self.verbose >= 2: cur_time = time() print(' Iteration %d\t time lapse %.5fs\t ll change %.5f' % (n_iter, cur_time - self._iter_prev_time, change)) self._iter_prev_time = cur_time </DeepExtract> if abs(change) < self.tol: self.converged_ = True break <DeepExtract> if self.verbose == 1: print('Initialization converged: %s' % self.converged_) elif self.verbose >= 2: print('Initialization converged: %s\t time lapse %.5fs\t ll %.5f' % (self.converged_, time() - self._init_prev_time, lower_bound)) </DeepExtract> if lower_bound > max_lower_bound or max_lower_bound == -np.inf: max_lower_bound = lower_bound <DeepExtract> pass </DeepExtract> best_n_iter = n_iter if not self.converged_ and self.max_iter > 0: warnings.warn('Initialization %d did not converge. Try different init parameters, or increase max_iter, tol or check for degenerate data.' % (init + 1), ConvergenceWarning) <DeepExtract> pass </DeepExtract> self.n_iter_ = best_n_iter self.lower_bound_ = max_lower_bound <DeepExtract> (log_prob_norm, log_resp) = self._estimate_log_prob_resp(X) (_, log_resp) = (np.mean(log_prob_norm), log_resp) </DeepExtract> return log_resp.argmax(axis=1)
def _solve_eigen_gram(self, alpha, y, sqrt_sw, X_mean, eigvals, Q, QT_y): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X.X^T (n_samples <= n_features). """ w = 1.0 / (eigvals + alpha) if self.fit_intercept: normalized_sw = sqrt_sw / np.linalg.norm(sqrt_sw) abs_cosine = np.abs(normalized_sw.dot(Q)) index = np.argmax(abs_cosine) intercept_dim = index w[intercept_dim] = 0 c = np.dot(Q, self._diag_dot(w, QT_y)) G_inverse_diag = (w * Q ** 2).sum(axis=-1) if len(y.shape) != 1: G_inverse_diag = G_inverse_diag[:, np.newaxis] return (G_inverse_diag, c)
def _solve_eigen_gram(self, alpha, y, sqrt_sw, X_mean, eigvals, Q, QT_y): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X.X^T (n_samples <= n_features). """ w = 1.0 / (eigvals + alpha) if self.fit_intercept: normalized_sw = sqrt_sw / np.linalg.norm(sqrt_sw) <DeepExtract> abs_cosine = np.abs(normalized_sw.dot(Q)) index = np.argmax(abs_cosine) intercept_dim = index </DeepExtract> w[intercept_dim] = 0 c = np.dot(Q, self._diag_dot(w, QT_y)) <DeepExtract> G_inverse_diag = (w * Q ** 2).sum(axis=-1) </DeepExtract> if len(y.shape) != 1: G_inverse_diag = G_inverse_diag[:, np.newaxis] return (G_inverse_diag, c)
def _download_data_to_bunch(url: str, sparse: bool, data_home: Optional[str], *, as_frame: bool, openml_columns_info: List[dict], data_columns: List[str], target_columns: List[str], shape: Optional[Tuple[int, int]], md5_checksum: str, n_retries: int=3, delay: float=1.0, parser: str): """Download ARFF data, load it to a specific container and create to Bunch. This function has a mechanism to retry/cache/clean the data. Parameters ---------- url : str The URL of the ARFF file on OpenML. sparse : bool Whether the dataset is expected to use the sparse ARFF format. data_home : str The location where to cache the data. as_frame : bool Whether or not to return the data into a pandas DataFrame. openml_columns_info : list of dict The information regarding the columns provided by OpenML for the ARFF dataset. The information is stored as a list of dictionaries. data_columns : list of str The list of the features to be selected. target_columns : list of str The list of the target variables to be selected. shape : tuple or None With `parser="liac-arff"`, when using a generator to load the data, one needs to provide the shape of the data beforehand. md5_checksum : str The MD5 checksum provided by OpenML to check the data integrity. 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. parser : {"liac-arff", "pandas"} The parser used to parse the ARFF file. Returns ------- data : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. 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"`. """ features_dict = {feature['name']: feature for feature in openml_columns_info} if sparse: output_type = 'sparse' elif as_frame: output_type = 'pandas' else: output_type = 'numpy' if not isinstance(target_columns, list): raise ValueError('target_column should be list, got: %s' % type(target_columns)) found_types = set() for target_column in target_columns: if target_column not in features_dict: raise KeyError(f"Could not find target_column='{target_column}'") if features_dict[target_column]['data_type'] == 'numeric': found_types.add(np.float64) else: found_types.add(object) if features_dict[target_column]['is_ignore'] == 'true': warn(f"target_column='{target_column}' has flag is_ignore.") if features_dict[target_column]['is_row_identifier'] == 'true': warn(f"target_column='{target_column}' has flag is_row_identifier.") if len(found_types) > 1: raise ValueError('Can only handle homogeneous multi-target datasets, i.e., all targets are either numeric or categorical.') for name in target_columns: column_info = features_dict[name] n_missing_values = int(column_info['number_of_missing_values']) if n_missing_values > 0: raise ValueError(f"Target column '{column_info['name']}' has {n_missing_values} missing values. Missing values are not supported for target columns.") no_retry_exception = None if parser == 'pandas': from pandas.errors import ParserError no_retry_exception = ParserError (X, y, frame, categories) = _retry_with_clean_cache(url, data_home, no_retry_exception)(_load_arff_response)(url, data_home, parser=parser, output_type=output_type, openml_columns_info=features_dict, feature_names_to_select=data_columns, target_names_to_select=target_columns, shape=shape, md5_checksum=md5_checksum, n_retries=n_retries, delay=delay) return Bunch(data=X, target=y, frame=frame, categories=categories, feature_names=data_columns, target_names=target_columns)
def _download_data_to_bunch(url: str, sparse: bool, data_home: Optional[str], *, as_frame: bool, openml_columns_info: List[dict], data_columns: List[str], target_columns: List[str], shape: Optional[Tuple[int, int]], md5_checksum: str, n_retries: int=3, delay: float=1.0, parser: str): """Download ARFF data, load it to a specific container and create to Bunch. This function has a mechanism to retry/cache/clean the data. Parameters ---------- url : str The URL of the ARFF file on OpenML. sparse : bool Whether the dataset is expected to use the sparse ARFF format. data_home : str The location where to cache the data. as_frame : bool Whether or not to return the data into a pandas DataFrame. openml_columns_info : list of dict The information regarding the columns provided by OpenML for the ARFF dataset. The information is stored as a list of dictionaries. data_columns : list of str The list of the features to be selected. target_columns : list of str The list of the target variables to be selected. shape : tuple or None With `parser="liac-arff"`, when using a generator to load the data, one needs to provide the shape of the data beforehand. md5_checksum : str The MD5 checksum provided by OpenML to check the data integrity. 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. parser : {"liac-arff", "pandas"} The parser used to parse the ARFF file. Returns ------- data : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. 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"`. """ features_dict = {feature['name']: feature for feature in openml_columns_info} if sparse: output_type = 'sparse' elif as_frame: output_type = 'pandas' else: output_type = 'numpy' <DeepExtract> if not isinstance(target_columns, list): raise ValueError('target_column should be list, got: %s' % type(target_columns)) found_types = set() for target_column in target_columns: if target_column not in features_dict: raise KeyError(f"Could not find target_column='{target_column}'") if features_dict[target_column]['data_type'] == 'numeric': found_types.add(np.float64) else: found_types.add(object) if features_dict[target_column]['is_ignore'] == 'true': warn(f"target_column='{target_column}' has flag is_ignore.") if features_dict[target_column]['is_row_identifier'] == 'true': warn(f"target_column='{target_column}' has flag is_row_identifier.") if len(found_types) > 1: raise ValueError('Can only handle homogeneous multi-target datasets, i.e., all targets are either numeric or categorical.') </DeepExtract> for name in target_columns: column_info = features_dict[name] n_missing_values = int(column_info['number_of_missing_values']) if n_missing_values > 0: raise ValueError(f"Target column '{column_info['name']}' has {n_missing_values} missing values. Missing values are not supported for target columns.") no_retry_exception = None if parser == 'pandas': from pandas.errors import ParserError no_retry_exception = ParserError (X, y, frame, categories) = _retry_with_clean_cache(url, data_home, no_retry_exception)(_load_arff_response)(url, data_home, parser=parser, output_type=output_type, openml_columns_info=features_dict, feature_names_to_select=data_columns, target_names_to_select=target_columns, shape=shape, md5_checksum=md5_checksum, n_retries=n_retries, delay=delay) return Bunch(data=X, target=y, frame=frame, categories=categories, feature_names=data_columns, target_names=target_columns)
def check_global_ouptut_transform_pandas(name, transformer_orig): """Check that setting globally the output of a transformer to pandas lead to the right results.""" try: import pandas as pd except ImportError: raise SkipTest('pandas is not installed: not checking column name consistency for pandas') 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) feature_names_in = [f'col{i}' for i in range(X.shape[1])] df = pd.DataFrame(X, columns=feature_names_in) transformer_default = clone(transformer).set_output(transform='default') outputs = {} cases = [('fit.transform/df/df', df, df), ('fit.transform/df/array', df, X), ('fit.transform/array/df', X, df), ('fit.transform/array/array', X, X)] if all((hasattr(transformer_default, meth) for meth in ['fit', 'transform'])): for (case, data_fit, data_transform) in cases: transformer_default.fit(data_fit, y) if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_default.transform(data_transform, y) else: X_trans = transformer_default.transform(data_transform) outputs[case] = (X_trans, transformer_default.get_feature_names_out()) cases = [('fit_transform/df', df), ('fit_transform/array', X)] if hasattr(transformer_default, 'fit_transform'): for (case, data) in cases: if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_default.fit_transform(data, y) else: X_trans = transformer_default.fit_transform(data, y) outputs[case] = (X_trans, transformer_default.get_feature_names_out()) outputs_default = outputs transformer_pandas = clone(transformer) try: with config_context(transform_output='pandas'): outputs = {} cases = [('fit.transform/df/df', df, df), ('fit.transform/df/array', df, X), ('fit.transform/array/df', X, df), ('fit.transform/array/array', X, X)] if all((hasattr(transformer_pandas, meth) for meth in ['fit', 'transform'])): for (case, data_fit, data_transform) in cases: transformer_pandas.fit(data_fit, y) if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_pandas.transform(data_transform, y) else: X_trans = transformer_pandas.transform(data_transform) outputs[case] = (X_trans, transformer_pandas.get_feature_names_out()) cases = [('fit_transform/df', df), ('fit_transform/array', X)] if hasattr(transformer_pandas, 'fit_transform'): for (case, data) in cases: if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_pandas.fit_transform(data, y) else: X_trans = transformer_pandas.fit_transform(data, y) outputs[case] = (X_trans, transformer_pandas.get_feature_names_out()) outputs_pandas = outputs except ValueError as e: assert str(e) == 'Pandas output does not support sparse data.', e return for case in outputs_default: import pandas as pd (X_trans, feature_names_default) = outputs_default[case] (df_trans, feature_names_pandas) = outputs_pandas[case] assert isinstance(df_trans, pd.DataFrame) expected_dataframe = pd.DataFrame(X_trans, columns=feature_names_pandas) try: pd.testing.assert_frame_equal(df_trans, expected_dataframe) except AssertionError as e: raise AssertionError(f'{name} does not generate a valid dataframe in the {case} case. The generated dataframe is not equal to the expected dataframe. The error message is: {e}') from e </DeepExtract>
def check_global_ouptut_transform_pandas(name, transformer_orig): """Check that setting globally the output of a transformer to pandas lead to the right results.""" try: import pandas as pd except ImportError: raise SkipTest('pandas is not installed: not checking column name consistency for pandas') 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) feature_names_in = [f'col{i}' for i in range(X.shape[1])] df = pd.DataFrame(X, columns=feature_names_in) transformer_default = clone(transformer).set_output(transform='default') <DeepExtract> outputs = {} cases = [('fit.transform/df/df', df, df), ('fit.transform/df/array', df, X), ('fit.transform/array/df', X, df), ('fit.transform/array/array', X, X)] if all((hasattr(transformer_default, meth) for meth in ['fit', 'transform'])): for (case, data_fit, data_transform) in cases: transformer_default.fit(data_fit, y) if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_default.transform(data_transform, y) else: X_trans = transformer_default.transform(data_transform) outputs[case] = (X_trans, transformer_default.get_feature_names_out()) cases = [('fit_transform/df', df), ('fit_transform/array', X)] if hasattr(transformer_default, 'fit_transform'): for (case, data) in cases: if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_default.fit_transform(data, y) else: X_trans = transformer_default.fit_transform(data, y) outputs[case] = (X_trans, transformer_default.get_feature_names_out()) outputs_default = outputs </DeepExtract> transformer_pandas = clone(transformer) try: with config_context(transform_output='pandas'): <DeepExtract> outputs = {} cases = [('fit.transform/df/df', df, df), ('fit.transform/df/array', df, X), ('fit.transform/array/df', X, df), ('fit.transform/array/array', X, X)] if all((hasattr(transformer_pandas, meth) for meth in ['fit', 'transform'])): for (case, data_fit, data_transform) in cases: transformer_pandas.fit(data_fit, y) if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_pandas.transform(data_transform, y) else: X_trans = transformer_pandas.transform(data_transform) outputs[case] = (X_trans, transformer_pandas.get_feature_names_out()) cases = [('fit_transform/df', df), ('fit_transform/array', X)] if hasattr(transformer_pandas, 'fit_transform'): for (case, data) in cases: if name in CROSS_DECOMPOSITION: (X_trans, _) = transformer_pandas.fit_transform(data, y) else: X_trans = transformer_pandas.fit_transform(data, y) outputs[case] = (X_trans, transformer_pandas.get_feature_names_out()) outputs_pandas = outputs </DeepExtract> except ValueError as e: assert str(e) == 'Pandas output does not support sparse data.', e return for case in outputs_default: <DeepExtract> import pandas as pd (X_trans, feature_names_default) = outputs_default[case] (df_trans, feature_names_pandas) = outputs_pandas[case] assert isinstance(df_trans, pd.DataFrame) expected_dataframe = pd.DataFrame(X_trans, columns=feature_names_pandas) try: pd.testing.assert_frame_equal(df_trans, expected_dataframe) except AssertionError as e: raise AssertionError(f'{name} does not generate a valid dataframe in the {case} case. The generated dataframe is not equal to the expected dataframe. The error message is: {e}') from e </DeepExtract>
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': (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') probs = 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] probs = probabilities classes_ = self.classes_ if not self.outputs_2d_: probs = [probs] classes_ = [self.classes_] n_outputs = len(classes_) n_queries = probs[0].shape[0] y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype) for (k, prob) in enumerate(probs): max_prob_index = prob.argmax(axis=1) y_pred[:, k] = classes_[k].take(max_prob_index) outlier_zero_probs = (prob == 0).all(axis=1) if outlier_zero_probs.any(): zero_prob_index = np.flatnonzero(outlier_zero_probs) y_pred[zero_prob_index, k] = self.outlier_label_[k] 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. """ <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') probs = 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] probs = probabilities </DeepExtract> classes_ = self.classes_ if not self.outputs_2d_: probs = [probs] classes_ = [self.classes_] n_outputs = len(classes_) n_queries = probs[0].shape[0] y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype) for (k, prob) in enumerate(probs): max_prob_index = prob.argmax(axis=1) y_pred[:, k] = classes_[k].take(max_prob_index) outlier_zero_probs = (prob == 0).all(axis=1) if outlier_zero_probs.any(): zero_prob_index = np.flatnonzero(outlier_zero_probs) y_pred[zero_prob_index, k] = self.outlier_label_[k] if not self.outputs_2d_: y_pred = y_pred.ravel() return y_pred
def partial_dependence(estimator, X, features, *, categorical_features=None, feature_names=None, response_method='auto', percentiles=(0.05, 0.95), grid_resolution=100, method='auto', kind='average'): """Partial dependence of ``features``. Partial dependence of a feature (or a set of features) corresponds to the average response of an estimator for each possible value of the feature. Read more in the :ref:`User Guide <partial_dependence>`. .. warning:: For :class:`~sklearn.ensemble.GradientBoostingClassifier` and :class:`~sklearn.ensemble.GradientBoostingRegressor`, the `'recursion'` method (used by default) will not account for the `init` predictor of the boosting process. In practice, this will produce the same values as `'brute'` up to a constant offset in the target response, provided that `init` is a constant estimator (which is the default). However, if `init` is not a constant estimator, the partial dependence values are incorrect for `'recursion'` because the offset will be sample-dependent. It is preferable to use the `'brute'` method. Note that this only applies to :class:`~sklearn.ensemble.GradientBoostingClassifier` and :class:`~sklearn.ensemble.GradientBoostingRegressor`, not to :class:`~sklearn.ensemble.HistGradientBoostingClassifier` and :class:`~sklearn.ensemble.HistGradientBoostingRegressor`. Parameters ---------- estimator : BaseEstimator A fitted estimator object implementing :term:`predict`, :term:`predict_proba`, or :term:`decision_function`. Multioutput-multiclass classifiers are not supported. X : {array-like or dataframe} of shape (n_samples, n_features) ``X`` is used to generate a grid of values for the target ``features`` (where the partial dependence will be evaluated), and also to generate values for the complement features when the `method` is 'brute'. features : array-like of {int, str} The feature (e.g. `[0]`) or pair of interacting features (e.g. `[(0, 1)]`) for which the partial dependency should be computed. categorical_features : array-like of shape (n_features,) or shape (n_categorical_features,), dtype={bool, int, str}, default=None Indicates the categorical features. - `None`: no feature will be considered categorical; - boolean array-like: boolean mask of shape `(n_features,)` indicating which features are categorical. Thus, this array has the same shape has `X.shape[1]`; - integer or string array-like: integer indices or strings indicating categorical features. .. versionadded:: 1.2 feature_names : array-like of shape (n_features,), dtype=str, default=None Name of each feature; `feature_names[i]` holds the name of the feature with index `i`. By default, the name of the feature corresponds to their numerical index for NumPy array and their column name for pandas dataframe. .. versionadded:: 1.2 response_method : {'auto', 'predict_proba', 'decision_function'}, default='auto' Specifies whether to use :term:`predict_proba` or :term:`decision_function` as the target response. For regressors this parameter is ignored and the response is always the output of :term:`predict`. By default, :term:`predict_proba` is tried first and we revert to :term:`decision_function` if it doesn't exist. If ``method`` is 'recursion', the response is always the output of :term:`decision_function`. percentiles : tuple of float, default=(0.05, 0.95) The lower and upper percentile used to create the extreme values for the grid. Must be in [0, 1]. grid_resolution : int, default=100 The number of equally spaced points on the grid, for each target feature. method : {'auto', 'recursion', 'brute'}, default='auto' The method used to calculate the averaged predictions: - `'recursion'` is only supported for some tree-based estimators (namely :class:`~sklearn.ensemble.GradientBoostingClassifier`, :class:`~sklearn.ensemble.GradientBoostingRegressor`, :class:`~sklearn.ensemble.HistGradientBoostingClassifier`, :class:`~sklearn.ensemble.HistGradientBoostingRegressor`, :class:`~sklearn.tree.DecisionTreeRegressor`, :class:`~sklearn.ensemble.RandomForestRegressor`, ) when `kind='average'`. This is more efficient in terms of speed. With this method, the target response of a classifier is always the decision function, not the predicted probabilities. Since the `'recursion'` method implicitly computes the average of the Individual Conditional Expectation (ICE) by design, it is not compatible with ICE and thus `kind` must be `'average'`. - `'brute'` is supported for any estimator, but is more computationally intensive. - `'auto'`: the `'recursion'` is used for estimators that support it, and `'brute'` is used otherwise. Please see :ref:`this note <pdp_method_differences>` for differences between the `'brute'` and `'recursion'` method. kind : {'average', 'individual', 'both'}, default='average' Whether to return the partial dependence averaged across all the samples in the dataset or one value per sample or both. See Returns below. Note that the fast `method='recursion'` option is only available for `kind='average'`. Computing individual dependencies requires using the slower `method='brute'` option. .. versionadded:: 0.24 Returns ------- predictions : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. individual : ndarray of shape (n_outputs, n_instances, len(values[0]), len(values[1]), ...) The predictions for all the points in the grid for all samples in X. This is also known as Individual Conditional Expectation (ICE) average : ndarray of shape (n_outputs, len(values[0]), len(values[1]), ...) The predictions for all the points in the grid, averaged over all samples in X (or over the training data if ``method`` is 'recursion'). Only available when ``kind='both'``. values : seq of 1d ndarrays The values with which the grid has been created. .. deprecated:: 1.3 The key `values` has been deprecated in 1.3 and will be removed in 1.5 in favor of `grid_values`. See `grid_values` for details about the `values` attribute. grid_values : seq of 1d ndarrays The values with which the grid has been created. The generated grid is a cartesian product of the arrays in ``grid_values`` where ``len(grid_values) == len(features)``. The size of each array ``grid_values[j]`` is either ``grid_resolution``, or the number of unique values in ``X[:, j]``, whichever is smaller. .. versionadded:: 1.3 ``n_outputs`` corresponds to the number of classes in a multi-class setting, or to the number of tasks for multi-output regression. For classical regression and binary classification ``n_outputs==1``. ``n_values_feature_j`` corresponds to the size ``grid_values[j]``. See Also -------- PartialDependenceDisplay.from_estimator : Plot Partial Dependence. PartialDependenceDisplay : Partial Dependence visualization. Examples -------- >>> X = [[0, 0, 2], [1, 0, 0]] >>> y = [0, 1] >>> from sklearn.ensemble import GradientBoostingClassifier >>> gb = GradientBoostingClassifier(random_state=0).fit(X, y) >>> partial_dependence(gb, features=[0], X=X, percentiles=(0, 1), ... grid_resolution=2) # doctest: +SKIP (array([[-4.52..., 4.52...]]), [array([ 0., 1.])]) """ check_is_fitted(estimator) if not (is_classifier(estimator) or is_regressor(estimator)): raise ValueError("'estimator' must be a fitted regressor or classifier.") if is_classifier(estimator) and isinstance(estimator.classes_[0], np.ndarray): raise ValueError('Multiclass-multioutput estimators are not supported') if not (hasattr(X, '__array__') or sparse.issparse(X)): X = check_array(X, force_all_finite='allow-nan', dtype=object) accepted_responses = ('auto', 'predict_proba', 'decision_function') if response_method not in accepted_responses: raise ValueError('response_method {} is invalid. Accepted response_method names are {}.'.format(response_method, ', '.join(accepted_responses))) if is_regressor(estimator) and response_method != 'auto': raise ValueError("The response_method parameter is ignored for regressors and must be 'auto'.") accepted_methods = ('brute', 'recursion', 'auto') if method not in accepted_methods: raise ValueError('method {} is invalid. Accepted method names are {}.'.format(method, ', '.join(accepted_methods))) if kind != 'average': if method == 'recursion': raise ValueError("The 'recursion' method only applies when 'kind' is set to 'average'") method = 'brute' if method == 'auto': if isinstance(estimator, BaseGradientBoosting) and estimator.init is None: method = 'recursion' elif isinstance(estimator, (BaseHistGradientBoosting, DecisionTreeRegressor, RandomForestRegressor)): method = 'recursion' else: method = 'brute' if method == 'recursion': if not isinstance(estimator, (BaseGradientBoosting, BaseHistGradientBoosting, DecisionTreeRegressor, RandomForestRegressor)): supported_classes_recursion = ('GradientBoostingClassifier', 'GradientBoostingRegressor', 'HistGradientBoostingClassifier', 'HistGradientBoostingRegressor', 'HistGradientBoostingRegressor', 'DecisionTreeRegressor', 'RandomForestRegressor') raise ValueError("Only the following estimators support the 'recursion' method: {}. Try using method='brute'.".format(', '.join(supported_classes_recursion))) if response_method == 'auto': response_method = 'decision_function' if response_method != 'decision_function': raise ValueError("With the 'recursion' method, the response_method must be 'decision_function'. Got {}.".format(response_method)) if _determine_key_type(features, accept_slice=False) == 'int': if np.any(np.less(features, 0)): raise ValueError('all features must be in [0, {}]'.format(X.shape[1] - 1)) features_indices = np.asarray(_get_column_indices(X, features), dtype=np.int32, order='C').ravel() feature_names = _check_feature_names(X, feature_names) n_features = X.shape[1] if categorical_features is None: is_categorical = [False] * len(features_indices) else: categorical_features = np.array(categorical_features, copy=False) if categorical_features.dtype.kind == 'b': if categorical_features.size != n_features: raise ValueError(f'When `categorical_features` is a boolean array-like, the array should be of shape (n_features,). Got {categorical_features.size} elements while `X` contains {n_features} features.') is_categorical = [categorical_features[idx] for idx in features_indices] elif categorical_features.dtype.kind in ('i', 'O', 'U'): categorical_features_idx = [_get_feature_index(cat, feature_names=feature_names) for cat in categorical_features] is_categorical = [idx in categorical_features_idx for idx in features_indices] else: raise ValueError(f'Expected `categorical_features` to be an array-like of boolean, integer, or string. Got {categorical_features.dtype} instead.') if not isinstance(percentiles, Iterable) or len(percentiles) != 2: raise ValueError("'percentiles' must be a sequence of 2 elements.") if not all((0 <= x <= 1 for x in percentiles)): raise ValueError("'percentiles' values must be in [0, 1].") if percentiles[0] >= percentiles[1]: raise ValueError('percentiles[0] must be strictly less than percentiles[1].') if grid_resolution <= 1: raise ValueError("'grid_resolution' must be strictly greater than 1.") values = [] for (feature, is_cat) in enumerate(is_categorical): try: uniques = np.unique(_safe_indexing(_safe_indexing(X, features_indices, axis=1), feature, axis=1)) except TypeError as exc: raise ValueError(f'The column #{feature} contains mixed data types. Finding unique categories fail due to sorting. It usually means that the column contains `np.nan` values together with `str` categories. Such use case is not yet supported in scikit-learn.') from exc if is_cat or uniques.shape[0] < grid_resolution: axis = uniques else: emp_percentiles = mquantiles(_safe_indexing(_safe_indexing(X, features_indices, axis=1), feature, axis=1), prob=percentiles, axis=0) if np.allclose(emp_percentiles[0], emp_percentiles[1]): raise ValueError('percentiles are too close to each other, unable to build the grid. Please choose percentiles that are further apart.') axis = np.linspace(emp_percentiles[0], emp_percentiles[1], num=grid_resolution, endpoint=True) values.append(axis) (grid, values) = (cartesian(values), values) if method == 'brute': predictions = [] averaged_predictions = [] if is_regressor(estimator): prediction_method = estimator.predict else: predict_proba = getattr(estimator, 'predict_proba', None) decision_function = getattr(estimator, 'decision_function', None) if response_method == 'auto': prediction_method = predict_proba or decision_function else: prediction_method = predict_proba if response_method == 'predict_proba' else decision_function if prediction_method is None: if response_method == 'auto': raise ValueError('The estimator has no predict_proba and no decision_function method.') elif response_method == 'predict_proba': raise ValueError('The estimator has no predict_proba method.') else: raise ValueError('The estimator has no decision_function method.') X_eval = X.copy() for new_values in grid: for (i, variable) in enumerate(features_indices): _safe_assign(X_eval, new_values[i], column_indexer=variable) try: pred = prediction_method(X_eval) predictions.append(pred) averaged_predictions.append(np.mean(pred, axis=0)) except NotFittedError as e: raise ValueError("'estimator' parameter must be a fitted estimator") from e n_samples = X.shape[0] predictions = np.array(predictions).T if is_regressor(estimator) and predictions.ndim == 2: predictions = predictions.reshape(n_samples, -1) elif is_classifier(estimator) and predictions.shape[0] == 2: predictions = predictions[1] predictions = predictions.reshape(n_samples, -1) averaged_predictions = np.array(averaged_predictions).T if is_regressor(estimator) and averaged_predictions.ndim == 1: averaged_predictions = averaged_predictions.reshape(1, -1) elif is_classifier(estimator) and averaged_predictions.shape[0] == 2: averaged_predictions = averaged_predictions[1] averaged_predictions = averaged_predictions.reshape(1, -1) (averaged_predictions, predictions) = (averaged_predictions, predictions) predictions = predictions.reshape(-1, X.shape[0], *[val.shape[0] for val in values]) else: averaged_predictions = estimator._compute_partial_dependence_recursion(grid, features_indices) if averaged_predictions.ndim == 1: averaged_predictions = averaged_predictions.reshape(1, -1) averaged_predictions = averaged_predictions averaged_predictions = averaged_predictions.reshape(-1, *[val.shape[0] for val in values]) pdp_results = Bunch() msg = "Key: 'values', is deprecated in 1.3 and will be removed in 1.5. Please use 'grid_values' instead." pdp_results._set_deprecated(values, new_key='grid_values', deprecated_key='values', warning_message=msg) if kind == 'average': pdp_results['average'] = averaged_predictions elif kind == 'individual': pdp_results['individual'] = predictions else: pdp_results['average'] = averaged_predictions pdp_results['individual'] = predictions return pdp_results
def partial_dependence(estimator, X, features, *, categorical_features=None, feature_names=None, response_method='auto', percentiles=(0.05, 0.95), grid_resolution=100, method='auto', kind='average'): """Partial dependence of ``features``. Partial dependence of a feature (or a set of features) corresponds to the average response of an estimator for each possible value of the feature. Read more in the :ref:`User Guide <partial_dependence>`. .. warning:: For :class:`~sklearn.ensemble.GradientBoostingClassifier` and :class:`~sklearn.ensemble.GradientBoostingRegressor`, the `'recursion'` method (used by default) will not account for the `init` predictor of the boosting process. In practice, this will produce the same values as `'brute'` up to a constant offset in the target response, provided that `init` is a constant estimator (which is the default). However, if `init` is not a constant estimator, the partial dependence values are incorrect for `'recursion'` because the offset will be sample-dependent. It is preferable to use the `'brute'` method. Note that this only applies to :class:`~sklearn.ensemble.GradientBoostingClassifier` and :class:`~sklearn.ensemble.GradientBoostingRegressor`, not to :class:`~sklearn.ensemble.HistGradientBoostingClassifier` and :class:`~sklearn.ensemble.HistGradientBoostingRegressor`. Parameters ---------- estimator : BaseEstimator A fitted estimator object implementing :term:`predict`, :term:`predict_proba`, or :term:`decision_function`. Multioutput-multiclass classifiers are not supported. X : {array-like or dataframe} of shape (n_samples, n_features) ``X`` is used to generate a grid of values for the target ``features`` (where the partial dependence will be evaluated), and also to generate values for the complement features when the `method` is 'brute'. features : array-like of {int, str} The feature (e.g. `[0]`) or pair of interacting features (e.g. `[(0, 1)]`) for which the partial dependency should be computed. categorical_features : array-like of shape (n_features,) or shape (n_categorical_features,), dtype={bool, int, str}, default=None Indicates the categorical features. - `None`: no feature will be considered categorical; - boolean array-like: boolean mask of shape `(n_features,)` indicating which features are categorical. Thus, this array has the same shape has `X.shape[1]`; - integer or string array-like: integer indices or strings indicating categorical features. .. versionadded:: 1.2 feature_names : array-like of shape (n_features,), dtype=str, default=None Name of each feature; `feature_names[i]` holds the name of the feature with index `i`. By default, the name of the feature corresponds to their numerical index for NumPy array and their column name for pandas dataframe. .. versionadded:: 1.2 response_method : {'auto', 'predict_proba', 'decision_function'}, default='auto' Specifies whether to use :term:`predict_proba` or :term:`decision_function` as the target response. For regressors this parameter is ignored and the response is always the output of :term:`predict`. By default, :term:`predict_proba` is tried first and we revert to :term:`decision_function` if it doesn't exist. If ``method`` is 'recursion', the response is always the output of :term:`decision_function`. percentiles : tuple of float, default=(0.05, 0.95) The lower and upper percentile used to create the extreme values for the grid. Must be in [0, 1]. grid_resolution : int, default=100 The number of equally spaced points on the grid, for each target feature. method : {'auto', 'recursion', 'brute'}, default='auto' The method used to calculate the averaged predictions: - `'recursion'` is only supported for some tree-based estimators (namely :class:`~sklearn.ensemble.GradientBoostingClassifier`, :class:`~sklearn.ensemble.GradientBoostingRegressor`, :class:`~sklearn.ensemble.HistGradientBoostingClassifier`, :class:`~sklearn.ensemble.HistGradientBoostingRegressor`, :class:`~sklearn.tree.DecisionTreeRegressor`, :class:`~sklearn.ensemble.RandomForestRegressor`, ) when `kind='average'`. This is more efficient in terms of speed. With this method, the target response of a classifier is always the decision function, not the predicted probabilities. Since the `'recursion'` method implicitly computes the average of the Individual Conditional Expectation (ICE) by design, it is not compatible with ICE and thus `kind` must be `'average'`. - `'brute'` is supported for any estimator, but is more computationally intensive. - `'auto'`: the `'recursion'` is used for estimators that support it, and `'brute'` is used otherwise. Please see :ref:`this note <pdp_method_differences>` for differences between the `'brute'` and `'recursion'` method. kind : {'average', 'individual', 'both'}, default='average' Whether to return the partial dependence averaged across all the samples in the dataset or one value per sample or both. See Returns below. Note that the fast `method='recursion'` option is only available for `kind='average'`. Computing individual dependencies requires using the slower `method='brute'` option. .. versionadded:: 0.24 Returns ------- predictions : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. individual : ndarray of shape (n_outputs, n_instances, len(values[0]), len(values[1]), ...) The predictions for all the points in the grid for all samples in X. This is also known as Individual Conditional Expectation (ICE) average : ndarray of shape (n_outputs, len(values[0]), len(values[1]), ...) The predictions for all the points in the grid, averaged over all samples in X (or over the training data if ``method`` is 'recursion'). Only available when ``kind='both'``. values : seq of 1d ndarrays The values with which the grid has been created. .. deprecated:: 1.3 The key `values` has been deprecated in 1.3 and will be removed in 1.5 in favor of `grid_values`. See `grid_values` for details about the `values` attribute. grid_values : seq of 1d ndarrays The values with which the grid has been created. The generated grid is a cartesian product of the arrays in ``grid_values`` where ``len(grid_values) == len(features)``. The size of each array ``grid_values[j]`` is either ``grid_resolution``, or the number of unique values in ``X[:, j]``, whichever is smaller. .. versionadded:: 1.3 ``n_outputs`` corresponds to the number of classes in a multi-class setting, or to the number of tasks for multi-output regression. For classical regression and binary classification ``n_outputs==1``. ``n_values_feature_j`` corresponds to the size ``grid_values[j]``. See Also -------- PartialDependenceDisplay.from_estimator : Plot Partial Dependence. PartialDependenceDisplay : Partial Dependence visualization. Examples -------- >>> X = [[0, 0, 2], [1, 0, 0]] >>> y = [0, 1] >>> from sklearn.ensemble import GradientBoostingClassifier >>> gb = GradientBoostingClassifier(random_state=0).fit(X, y) >>> partial_dependence(gb, features=[0], X=X, percentiles=(0, 1), ... grid_resolution=2) # doctest: +SKIP (array([[-4.52..., 4.52...]]), [array([ 0., 1.])]) """ check_is_fitted(estimator) if not (is_classifier(estimator) or is_regressor(estimator)): raise ValueError("'estimator' must be a fitted regressor or classifier.") if is_classifier(estimator) and isinstance(estimator.classes_[0], np.ndarray): raise ValueError('Multiclass-multioutput estimators are not supported') if not (hasattr(X, '__array__') or sparse.issparse(X)): X = check_array(X, force_all_finite='allow-nan', dtype=object) accepted_responses = ('auto', 'predict_proba', 'decision_function') if response_method not in accepted_responses: raise ValueError('response_method {} is invalid. Accepted response_method names are {}.'.format(response_method, ', '.join(accepted_responses))) if is_regressor(estimator) and response_method != 'auto': raise ValueError("The response_method parameter is ignored for regressors and must be 'auto'.") accepted_methods = ('brute', 'recursion', 'auto') if method not in accepted_methods: raise ValueError('method {} is invalid. Accepted method names are {}.'.format(method, ', '.join(accepted_methods))) if kind != 'average': if method == 'recursion': raise ValueError("The 'recursion' method only applies when 'kind' is set to 'average'") method = 'brute' if method == 'auto': if isinstance(estimator, BaseGradientBoosting) and estimator.init is None: method = 'recursion' elif isinstance(estimator, (BaseHistGradientBoosting, DecisionTreeRegressor, RandomForestRegressor)): method = 'recursion' else: method = 'brute' if method == 'recursion': if not isinstance(estimator, (BaseGradientBoosting, BaseHistGradientBoosting, DecisionTreeRegressor, RandomForestRegressor)): supported_classes_recursion = ('GradientBoostingClassifier', 'GradientBoostingRegressor', 'HistGradientBoostingClassifier', 'HistGradientBoostingRegressor', 'HistGradientBoostingRegressor', 'DecisionTreeRegressor', 'RandomForestRegressor') raise ValueError("Only the following estimators support the 'recursion' method: {}. Try using method='brute'.".format(', '.join(supported_classes_recursion))) if response_method == 'auto': response_method = 'decision_function' if response_method != 'decision_function': raise ValueError("With the 'recursion' method, the response_method must be 'decision_function'. Got {}.".format(response_method)) if _determine_key_type(features, accept_slice=False) == 'int': if np.any(np.less(features, 0)): raise ValueError('all features must be in [0, {}]'.format(X.shape[1] - 1)) features_indices = np.asarray(_get_column_indices(X, features), dtype=np.int32, order='C').ravel() feature_names = _check_feature_names(X, feature_names) n_features = X.shape[1] if categorical_features is None: is_categorical = [False] * len(features_indices) else: categorical_features = np.array(categorical_features, copy=False) if categorical_features.dtype.kind == 'b': if categorical_features.size != n_features: raise ValueError(f'When `categorical_features` is a boolean array-like, the array should be of shape (n_features,). Got {categorical_features.size} elements while `X` contains {n_features} features.') is_categorical = [categorical_features[idx] for idx in features_indices] elif categorical_features.dtype.kind in ('i', 'O', 'U'): categorical_features_idx = [_get_feature_index(cat, feature_names=feature_names) for cat in categorical_features] is_categorical = [idx in categorical_features_idx for idx in features_indices] else: raise ValueError(f'Expected `categorical_features` to be an array-like of boolean, integer, or string. Got {categorical_features.dtype} instead.') <DeepExtract> if not isinstance(percentiles, Iterable) or len(percentiles) != 2: raise ValueError("'percentiles' must be a sequence of 2 elements.") if not all((0 <= x <= 1 for x in percentiles)): raise ValueError("'percentiles' values must be in [0, 1].") if percentiles[0] >= percentiles[1]: raise ValueError('percentiles[0] must be strictly less than percentiles[1].') if grid_resolution <= 1: raise ValueError("'grid_resolution' must be strictly greater than 1.") values = [] for (feature, is_cat) in enumerate(is_categorical): try: uniques = np.unique(_safe_indexing(_safe_indexing(X, features_indices, axis=1), feature, axis=1)) except TypeError as exc: raise ValueError(f'The column #{feature} contains mixed data types. Finding unique categories fail due to sorting. It usually means that the column contains `np.nan` values together with `str` categories. Such use case is not yet supported in scikit-learn.') from exc if is_cat or uniques.shape[0] < grid_resolution: axis = uniques else: emp_percentiles = mquantiles(_safe_indexing(_safe_indexing(X, features_indices, axis=1), feature, axis=1), prob=percentiles, axis=0) if np.allclose(emp_percentiles[0], emp_percentiles[1]): raise ValueError('percentiles are too close to each other, unable to build the grid. Please choose percentiles that are further apart.') axis = np.linspace(emp_percentiles[0], emp_percentiles[1], num=grid_resolution, endpoint=True) values.append(axis) (grid, values) = (cartesian(values), values) </DeepExtract> if method == 'brute': <DeepExtract> predictions = [] averaged_predictions = [] if is_regressor(estimator): prediction_method = estimator.predict else: predict_proba = getattr(estimator, 'predict_proba', None) decision_function = getattr(estimator, 'decision_function', None) if response_method == 'auto': prediction_method = predict_proba or decision_function else: prediction_method = predict_proba if response_method == 'predict_proba' else decision_function if prediction_method is None: if response_method == 'auto': raise ValueError('The estimator has no predict_proba and no decision_function method.') elif response_method == 'predict_proba': raise ValueError('The estimator has no predict_proba method.') else: raise ValueError('The estimator has no decision_function method.') X_eval = X.copy() for new_values in grid: for (i, variable) in enumerate(features_indices): _safe_assign(X_eval, new_values[i], column_indexer=variable) try: pred = prediction_method(X_eval) predictions.append(pred) averaged_predictions.append(np.mean(pred, axis=0)) except NotFittedError as e: raise ValueError("'estimator' parameter must be a fitted estimator") from e n_samples = X.shape[0] predictions = np.array(predictions).T if is_regressor(estimator) and predictions.ndim == 2: predictions = predictions.reshape(n_samples, -1) elif is_classifier(estimator) and predictions.shape[0] == 2: predictions = predictions[1] predictions = predictions.reshape(n_samples, -1) averaged_predictions = np.array(averaged_predictions).T if is_regressor(estimator) and averaged_predictions.ndim == 1: averaged_predictions = averaged_predictions.reshape(1, -1) elif is_classifier(estimator) and averaged_predictions.shape[0] == 2: averaged_predictions = averaged_predictions[1] averaged_predictions = averaged_predictions.reshape(1, -1) (averaged_predictions, predictions) = (averaged_predictions, predictions) </DeepExtract> predictions = predictions.reshape(-1, X.shape[0], *[val.shape[0] for val in values]) else: <DeepExtract> averaged_predictions = estimator._compute_partial_dependence_recursion(grid, features_indices) if averaged_predictions.ndim == 1: averaged_predictions = averaged_predictions.reshape(1, -1) averaged_predictions = averaged_predictions </DeepExtract> averaged_predictions = averaged_predictions.reshape(-1, *[val.shape[0] for val in values]) pdp_results = Bunch() msg = "Key: 'values', is deprecated in 1.3 and will be removed in 1.5. Please use 'grid_values' instead." pdp_results._set_deprecated(values, new_key='grid_values', deprecated_key='values', warning_message=msg) if kind == 'average': pdp_results['average'] = averaged_predictions elif kind == 'individual': pdp_results['individual'] = predictions else: pdp_results['average'] = averaged_predictions pdp_results['individual'] = predictions return pdp_results
@classmethod def from_estimator(cls, estimator, X, *, grid_resolution=100, eps=1.0, plot_method='contourf', response_method='auto', xlabel=None, ylabel=None, ax=None, **kwargs): """Plot decision boundary given an estimator. Read more in the :ref:`User Guide <visualizations>`. Parameters ---------- estimator : object Trained estimator used to plot the decision boundary. X : {array-like, sparse matrix, dataframe} of shape (n_samples, 2) Input data that should be only 2-dimensional. grid_resolution : int, default=100 Number of grid points to use for plotting decision boundary. Higher values will make the plot look nicer but be slower to render. eps : float, default=1.0 Extends the minimum and maximum values of X for evaluating the response function. plot_method : {'contourf', 'contour', 'pcolormesh'}, default='contourf' Plotting method to call when plotting the response. Please refer to the following matplotlib documentation for details: :func:`contourf <matplotlib.pyplot.contourf>`, :func:`contour <matplotlib.pyplot.contour>`, :func:`pcolormesh <matplotlib.pyplot.pcolormesh>`. response_method : {'auto', 'predict_proba', 'decision_function', 'predict'}, default='auto' Specifies whether to use :term:`predict_proba`, :term:`decision_function`, :term:`predict` as the target response. If set to 'auto', the response method is tried in the following order: :term:`decision_function`, :term:`predict_proba`, :term:`predict`. For multiclass problems, :term:`predict` is selected when `response_method="auto"`. xlabel : str, default=None The label used for the x-axis. If `None`, an attempt is made to extract a label from `X` if it is a dataframe, otherwise an empty string is used. ylabel : str, default=None The label used for the y-axis. If `None`, an attempt is made to extract a label from `X` if it is a dataframe, otherwise an empty string is used. ax : Matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. **kwargs : dict Additional keyword arguments to be passed to the `plot_method`. Returns ------- display : :class:`~sklearn.inspection.DecisionBoundaryDisplay` Object that stores the result. See Also -------- DecisionBoundaryDisplay : Decision boundary visualization. ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix given an estimator, the data, and the label. ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix given the true and predicted labels. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import load_iris >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.inspection import DecisionBoundaryDisplay >>> iris = load_iris() >>> X = iris.data[:, :2] >>> classifier = LogisticRegression().fit(X, iris.target) >>> disp = DecisionBoundaryDisplay.from_estimator( ... classifier, X, response_method="predict", ... xlabel=iris.feature_names[0], ylabel=iris.feature_names[1], ... alpha=0.5, ... ) >>> disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor="k") <...> >>> plt.show() """ check_matplotlib_support(f'{cls.__name__}.from_estimator') check_is_fitted(estimator) if not grid_resolution > 1: raise ValueError(f'grid_resolution must be greater than 1. Got {grid_resolution} instead.') if not eps >= 0: raise ValueError(f'eps must be greater than or equal to 0. Got {eps} instead.') possible_plot_methods = ('contourf', 'contour', 'pcolormesh') if plot_method not in possible_plot_methods: available_methods = ', '.join(possible_plot_methods) raise ValueError(f'plot_method must be one of {available_methods}. Got {plot_method} instead.') num_features = _num_features(X) if num_features != 2: raise ValueError(f'n_features must be equal to 2. Got {num_features} instead.') (x0, x1) = (_safe_indexing(X, 0, axis=1), _safe_indexing(X, 1, axis=1)) (x0_min, x0_max) = (x0.min() - eps, x0.max() + eps) (x1_min, x1_max) = (x1.min() - eps, x1.max() + eps) (xx0, xx1) = np.meshgrid(np.linspace(x0_min, x0_max, grid_resolution), np.linspace(x1_min, x1_max, grid_resolution)) if hasattr(X, 'iloc'): X_grid = X.iloc[[], :].copy() X_grid.iloc[:, 0] = xx0.ravel() X_grid.iloc[:, 1] = xx1.ravel() else: X_grid = np.c_[xx0.ravel(), xx1.ravel()] has_classes = hasattr(estimator, 'classes_') if has_classes and _is_arraylike_not_scalar(estimator.classes_[0]): msg = 'Multi-label and multi-output multi-class classifiers are not supported' raise ValueError(msg) if has_classes and len(estimator.classes_) > 2: if response_method not in {'auto', 'predict'}: msg = "Multiclass classifiers are only supported when response_method is 'predict' or 'auto'" raise ValueError(msg) methods_list = ['predict'] elif response_method == 'auto': methods_list = ['decision_function', 'predict_proba', 'predict'] else: methods_list = [response_method] prediction_method = [getattr(estimator, method, None) for method in methods_list] prediction_method = reduce(lambda x, y: x or y, prediction_method) if prediction_method is None: raise ValueError(f"{estimator.__class__.__name__} has none of the following attributes: {', '.join(methods_list)}.") pred_func = prediction_method response = pred_func(X_grid) if pred_func.__name__ == 'predict' and hasattr(estimator, 'classes_'): encoder = LabelEncoder() encoder.classes_ = estimator.classes_ response = encoder.transform(response) if response.ndim != 1: if is_regressor(estimator): raise ValueError('Multi-output regressors are not supported') response = response[:, 1] if xlabel is None: xlabel = X.columns[0] if hasattr(X, 'columns') else '' if ylabel is None: ylabel = X.columns[1] if hasattr(X, 'columns') else '' display = DecisionBoundaryDisplay(xx0=xx0, xx1=xx1, response=response.reshape(xx0.shape), xlabel=xlabel, ylabel=ylabel) return display.plot(ax=ax, plot_method=plot_method, **kwargs)
@classmethod def from_estimator(cls, estimator, X, *, grid_resolution=100, eps=1.0, plot_method='contourf', response_method='auto', xlabel=None, ylabel=None, ax=None, **kwargs): """Plot decision boundary given an estimator. Read more in the :ref:`User Guide <visualizations>`. Parameters ---------- estimator : object Trained estimator used to plot the decision boundary. X : {array-like, sparse matrix, dataframe} of shape (n_samples, 2) Input data that should be only 2-dimensional. grid_resolution : int, default=100 Number of grid points to use for plotting decision boundary. Higher values will make the plot look nicer but be slower to render. eps : float, default=1.0 Extends the minimum and maximum values of X for evaluating the response function. plot_method : {'contourf', 'contour', 'pcolormesh'}, default='contourf' Plotting method to call when plotting the response. Please refer to the following matplotlib documentation for details: :func:`contourf <matplotlib.pyplot.contourf>`, :func:`contour <matplotlib.pyplot.contour>`, :func:`pcolormesh <matplotlib.pyplot.pcolormesh>`. response_method : {'auto', 'predict_proba', 'decision_function', 'predict'}, default='auto' Specifies whether to use :term:`predict_proba`, :term:`decision_function`, :term:`predict` as the target response. If set to 'auto', the response method is tried in the following order: :term:`decision_function`, :term:`predict_proba`, :term:`predict`. For multiclass problems, :term:`predict` is selected when `response_method="auto"`. xlabel : str, default=None The label used for the x-axis. If `None`, an attempt is made to extract a label from `X` if it is a dataframe, otherwise an empty string is used. ylabel : str, default=None The label used for the y-axis. If `None`, an attempt is made to extract a label from `X` if it is a dataframe, otherwise an empty string is used. ax : Matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. **kwargs : dict Additional keyword arguments to be passed to the `plot_method`. Returns ------- display : :class:`~sklearn.inspection.DecisionBoundaryDisplay` Object that stores the result. See Also -------- DecisionBoundaryDisplay : Decision boundary visualization. ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix given an estimator, the data, and the label. ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix given the true and predicted labels. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import load_iris >>> from sklearn.linear_model import LogisticRegression >>> from sklearn.inspection import DecisionBoundaryDisplay >>> iris = load_iris() >>> X = iris.data[:, :2] >>> classifier = LogisticRegression().fit(X, iris.target) >>> disp = DecisionBoundaryDisplay.from_estimator( ... classifier, X, response_method="predict", ... xlabel=iris.feature_names[0], ylabel=iris.feature_names[1], ... alpha=0.5, ... ) >>> disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor="k") <...> >>> plt.show() """ check_matplotlib_support(f'{cls.__name__}.from_estimator') check_is_fitted(estimator) if not grid_resolution > 1: raise ValueError(f'grid_resolution must be greater than 1. Got {grid_resolution} instead.') if not eps >= 0: raise ValueError(f'eps must be greater than or equal to 0. Got {eps} instead.') possible_plot_methods = ('contourf', 'contour', 'pcolormesh') if plot_method not in possible_plot_methods: available_methods = ', '.join(possible_plot_methods) raise ValueError(f'plot_method must be one of {available_methods}. Got {plot_method} instead.') num_features = _num_features(X) if num_features != 2: raise ValueError(f'n_features must be equal to 2. Got {num_features} instead.') (x0, x1) = (_safe_indexing(X, 0, axis=1), _safe_indexing(X, 1, axis=1)) (x0_min, x0_max) = (x0.min() - eps, x0.max() + eps) (x1_min, x1_max) = (x1.min() - eps, x1.max() + eps) (xx0, xx1) = np.meshgrid(np.linspace(x0_min, x0_max, grid_resolution), np.linspace(x1_min, x1_max, grid_resolution)) if hasattr(X, 'iloc'): X_grid = X.iloc[[], :].copy() X_grid.iloc[:, 0] = xx0.ravel() X_grid.iloc[:, 1] = xx1.ravel() else: X_grid = np.c_[xx0.ravel(), xx1.ravel()] <DeepExtract> has_classes = hasattr(estimator, 'classes_') if has_classes and _is_arraylike_not_scalar(estimator.classes_[0]): msg = 'Multi-label and multi-output multi-class classifiers are not supported' raise ValueError(msg) if has_classes and len(estimator.classes_) > 2: if response_method not in {'auto', 'predict'}: msg = "Multiclass classifiers are only supported when response_method is 'predict' or 'auto'" raise ValueError(msg) methods_list = ['predict'] elif response_method == 'auto': methods_list = ['decision_function', 'predict_proba', 'predict'] else: methods_list = [response_method] prediction_method = [getattr(estimator, method, None) for method in methods_list] prediction_method = reduce(lambda x, y: x or y, prediction_method) if prediction_method is None: raise ValueError(f"{estimator.__class__.__name__} has none of the following attributes: {', '.join(methods_list)}.") pred_func = prediction_method </DeepExtract> response = pred_func(X_grid) if pred_func.__name__ == 'predict' and hasattr(estimator, 'classes_'): encoder = LabelEncoder() encoder.classes_ = estimator.classes_ response = encoder.transform(response) if response.ndim != 1: if is_regressor(estimator): raise ValueError('Multi-output regressors are not supported') response = response[:, 1] if xlabel is None: xlabel = X.columns[0] if hasattr(X, 'columns') else '' if ylabel is None: ylabel = X.columns[1] if hasattr(X, 'columns') else '' display = DecisionBoundaryDisplay(xx0=xx0, xx1=xx1, response=response.reshape(xx0.shape), xlabel=xlabel, ylabel=ylabel) return display.plot(ax=ax, plot_method=plot_method, **kwargs)
@fails_if_pypy @pytest.mark.parametrize('as_frame, parser', [(True, 'liac-arff'), (False, 'liac-arff'), (True, 'pandas'), (False, 'pandas')]) def test_fetch_openml_verify_checksum(monkeypatch, as_frame, cache, tmpdir, parser): """Check that the checksum is working as expected.""" if as_frame or parser == 'pandas': pytest.importorskip('pandas') data_id = 2 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 True: 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) original_data_module = OPENML_TEST_DATA_MODULE + '.' + f'id_{data_id}' original_data_file_name = 'data-v1-dl-1666876.arff.gz' corrupt_copy_path = tmpdir / 'test_invalid_checksum.arff' with _open_binary(original_data_module, original_data_file_name) as orig_file: orig_gzip = gzip.open(orig_file, 'rb') data = bytearray(orig_gzip.read()) data[len(data) - 1] = 37 with gzip.GzipFile(corrupt_copy_path, 'wb') as modified_gzip: modified_gzip.write(data) mocked_openml_url = sklearn.datasets._openml.urlopen def swap_file_mock(request, *args, **kwargs): url = request.get_full_url() if url.endswith('data/v1/download/1666876'): with open(corrupt_copy_path, 'rb') as f: corrupted_data = f.read() return _MockHTTPResponse(BytesIO(corrupted_data), is_gzip=True) else: return mocked_openml_url(request) monkeypatch.setattr(sklearn.datasets._openml, 'urlopen', swap_file_mock) with pytest.raises(ValueError) as exc: sklearn.datasets.fetch_openml(data_id=data_id, cache=False, as_frame=as_frame, parser=parser) assert exc.match('1666876')
@fails_if_pypy @pytest.mark.parametrize('as_frame, parser', [(True, 'liac-arff'), (False, 'liac-arff'), (True, 'pandas'), (False, 'pandas')]) def test_fetch_openml_verify_checksum(monkeypatch, as_frame, cache, tmpdir, parser): """Check that the checksum is working as expected.""" if as_frame or parser == 'pandas': pytest.importorskip('pandas') data_id = 2 <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 True: 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> original_data_module = OPENML_TEST_DATA_MODULE + '.' + f'id_{data_id}' original_data_file_name = 'data-v1-dl-1666876.arff.gz' corrupt_copy_path = tmpdir / 'test_invalid_checksum.arff' with _open_binary(original_data_module, original_data_file_name) as orig_file: orig_gzip = gzip.open(orig_file, 'rb') data = bytearray(orig_gzip.read()) data[len(data) - 1] = 37 with gzip.GzipFile(corrupt_copy_path, 'wb') as modified_gzip: modified_gzip.write(data) mocked_openml_url = sklearn.datasets._openml.urlopen def swap_file_mock(request, *args, **kwargs): url = request.get_full_url() if url.endswith('data/v1/download/1666876'): with open(corrupt_copy_path, 'rb') as f: corrupted_data = f.read() return _MockHTTPResponse(BytesIO(corrupted_data), is_gzip=True) else: return mocked_openml_url(request) monkeypatch.setattr(sklearn.datasets._openml, 'urlopen', swap_file_mock) with pytest.raises(ValueError) as exc: sklearn.datasets.fetch_openml(data_id=data_id, cache=False, as_frame=as_frame, parser=parser) assert exc.match('1666876')
@pytest.mark.parametrize('algorithm', ALGORITHMS) @pytest.mark.parametrize('weights', WEIGHTS) def test_radius_neighbors_classifier_outlier_labeling(global_dtype, algorithm, weights): X = np.array([[1.0, 1.0], [2.0, 2.0], [0.99, 0.99], [0.98, 0.98], [2.01, 2.01]], dtype=global_dtype) y = np.array([1, 2, 1, 1, 2]) radius = 0.1 z1 = np.array([[1.01, 1.01], [2.01, 2.01]], dtype=global_dtype) z2 = np.array([[1.4, 1.4], [1.01, 1.01], [2.01, 2.01]], dtype=global_dtype) correct_labels1 = np.array([1, 2]) correct_labels2 = np.array([-1, 1, 2]) outlier_proba = np.array([0, 0]) clf = neighbors.RadiusNeighborsClassifier(radius=radius, weights=weights, algorithm=algorithm, outlier_label=-1) clf.fit(X, y) assert_array_equal(correct_labels1, clf.predict(z1)) with pytest.warns(UserWarning, match='Outlier label -1 is not in training classes'): assert_array_equal(correct_labels2, clf.predict(z2)) with pytest.warns(UserWarning, match='Outlier label -1 is not in training classes'): assert_allclose(outlier_proba, clf.predict_proba(z2)[0]) RNC = neighbors.RadiusNeighborsClassifier X = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]], dtype=global_dtype) y = np.array([0, 2, 2, 1, 1, 1, 3, 3, 3, 3]) def check_array_exception(): clf = RNC(radius=1, outlier_label=[[5]]) clf.fit(X, y) with pytest.raises(TypeError): clf = RNC(radius=1, outlier_label=[[5]]) clf.fit(X, y) def check_dtype_exception(): clf = RNC(radius=1, outlier_label='a') clf.fit(X, y) with pytest.raises(TypeError): clf = RNC(radius=1, outlier_label='a') clf.fit(X, y) clf = RNC(radius=1, outlier_label='most_frequent') clf.fit(X, y) proba = clf.predict_proba([[1], [15]]) assert_array_equal(proba[1, :], [0, 0, 0, 1]) clf = RNC(radius=1, outlier_label=1) clf.fit(X, y) proba = clf.predict_proba([[1], [15]]) assert_array_equal(proba[1, :], [0, 1, 0, 0]) pred = clf.predict([[1], [15]]) assert_array_equal(pred, [2, 1]) def check_warning(): clf = RNC(radius=1, outlier_label=4) clf.fit(X, y) clf.predict_proba([[1], [15]]) with pytest.warns(UserWarning): clf = RNC(radius=1, outlier_label=4) clf.fit(X, y) clf.predict_proba([[1], [15]]) y_multi = [[0, 1], [2, 1], [2, 2], [1, 2], [1, 2], [1, 3], [3, 3], [3, 3], [3, 0], [3, 0]] clf = RNC(radius=1, outlier_label=1) clf.fit(X, y_multi) proba = clf.predict_proba([[7], [15]]) assert_array_equal(proba[1][1, :], [0, 1, 0, 0]) pred = clf.predict([[7], [15]]) assert_array_equal(pred[1, :], [1, 1]) y_multi = [[0, 0], [2, 2], [2, 2], [1, 1], [1, 1], [1, 1], [3, 3], [3, 3], [3, 3], [3, 3]] clf = RNC(radius=1, outlier_label=[0, 1]) clf.fit(X, y_multi) proba = clf.predict_proba([[7], [15]]) assert_array_equal(proba[0][1, :], [1, 0, 0, 0]) assert_array_equal(proba[1][1, :], [0, 1, 0, 0]) pred = clf.predict([[7], [15]]) assert_array_equal(pred[1, :], [0, 1]) def check_exception(): clf = RNC(radius=1, outlier_label=[0, 1, 2]) clf.fit(X, y_multi) with pytest.raises(ValueError): clf = RNC(radius=1, outlier_label=[0, 1, 2]) clf.fit(X, y_multi) </DeepExtract>
@pytest.mark.parametrize('algorithm', ALGORITHMS) @pytest.mark.parametrize('weights', WEIGHTS) def test_radius_neighbors_classifier_outlier_labeling(global_dtype, algorithm, weights): X = np.array([[1.0, 1.0], [2.0, 2.0], [0.99, 0.99], [0.98, 0.98], [2.01, 2.01]], dtype=global_dtype) y = np.array([1, 2, 1, 1, 2]) radius = 0.1 z1 = np.array([[1.01, 1.01], [2.01, 2.01]], dtype=global_dtype) z2 = np.array([[1.4, 1.4], [1.01, 1.01], [2.01, 2.01]], dtype=global_dtype) correct_labels1 = np.array([1, 2]) correct_labels2 = np.array([-1, 1, 2]) outlier_proba = np.array([0, 0]) clf = neighbors.RadiusNeighborsClassifier(radius=radius, weights=weights, algorithm=algorithm, outlier_label=-1) clf.fit(X, y) assert_array_equal(correct_labels1, clf.predict(z1)) with pytest.warns(UserWarning, match='Outlier label -1 is not in training classes'): assert_array_equal(correct_labels2, clf.predict(z2)) with pytest.warns(UserWarning, match='Outlier label -1 is not in training classes'): assert_allclose(outlier_proba, clf.predict_proba(z2)[0]) RNC = neighbors.RadiusNeighborsClassifier X = np.array([[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]], dtype=global_dtype) y = np.array([0, 2, 2, 1, 1, 1, 3, 3, 3, 3]) def check_array_exception(): clf = RNC(radius=1, outlier_label=[[5]]) clf.fit(X, y) with pytest.raises(TypeError): <DeepExtract> clf = RNC(radius=1, outlier_label=[[5]]) clf.fit(X, y) </DeepExtract> def check_dtype_exception(): clf = RNC(radius=1, outlier_label='a') clf.fit(X, y) with pytest.raises(TypeError): <DeepExtract> clf = RNC(radius=1, outlier_label='a') clf.fit(X, y) </DeepExtract> clf = RNC(radius=1, outlier_label='most_frequent') clf.fit(X, y) proba = clf.predict_proba([[1], [15]]) assert_array_equal(proba[1, :], [0, 0, 0, 1]) clf = RNC(radius=1, outlier_label=1) clf.fit(X, y) proba = clf.predict_proba([[1], [15]]) assert_array_equal(proba[1, :], [0, 1, 0, 0]) pred = clf.predict([[1], [15]]) assert_array_equal(pred, [2, 1]) def check_warning(): clf = RNC(radius=1, outlier_label=4) clf.fit(X, y) clf.predict_proba([[1], [15]]) with pytest.warns(UserWarning): <DeepExtract> clf = RNC(radius=1, outlier_label=4) clf.fit(X, y) clf.predict_proba([[1], [15]]) </DeepExtract> y_multi = [[0, 1], [2, 1], [2, 2], [1, 2], [1, 2], [1, 3], [3, 3], [3, 3], [3, 0], [3, 0]] clf = RNC(radius=1, outlier_label=1) clf.fit(X, y_multi) proba = clf.predict_proba([[7], [15]]) assert_array_equal(proba[1][1, :], [0, 1, 0, 0]) pred = clf.predict([[7], [15]]) assert_array_equal(pred[1, :], [1, 1]) y_multi = [[0, 0], [2, 2], [2, 2], [1, 1], [1, 1], [1, 1], [3, 3], [3, 3], [3, 3], [3, 3]] clf = RNC(radius=1, outlier_label=[0, 1]) clf.fit(X, y_multi) proba = clf.predict_proba([[7], [15]]) assert_array_equal(proba[0][1, :], [1, 0, 0, 0]) assert_array_equal(proba[1][1, :], [0, 1, 0, 0]) pred = clf.predict([[7], [15]]) assert_array_equal(pred[1, :], [0, 1]) def check_exception(): clf = RNC(radius=1, outlier_label=[0, 1, 2]) clf.fit(X, y_multi) with pytest.raises(ValueError): <DeepExtract> clf = RNC(radius=1, outlier_label=[0, 1, 2]) clf.fit(X, y_multi) </DeepExtract>
def fit(self, X, y=None, **fit_params): """Fit the SelectFromModel meta-transformer. Parameters ---------- X : array-like of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,), default=None The target values (integers that correspond to classes in classification, real numbers in regression). **fit_params : dict Other estimator specific parameters. Returns ------- self : object Fitted estimator. """ self._validate_params() if self.max_features is not None: n_features = _num_features(X) if callable(self.max_features): max_features = self.max_features(X) else: max_features = self.max_features check_scalar(max_features, 'max_features', Integral, min_val=0, max_val=n_features) self.max_features_ = max_features if self.prefit: try: check_is_fitted(self.estimator) except NotFittedError as exc: raise NotFittedError('When `prefit=True`, `estimator` is expected to be a fitted estimator.') from exc self.estimator_ = deepcopy(self.estimator) else: self.estimator_ = clone(self.estimator) self.estimator_.fit(X, y, **fit_params) if hasattr(self.estimator_, 'feature_names_in_'): self.feature_names_in_ = self.estimator_.feature_names_in_ else: self._check_feature_names(X, reset=True) return self
def fit(self, X, y=None, **fit_params): """Fit the SelectFromModel meta-transformer. Parameters ---------- X : array-like of shape (n_samples, n_features) The training input samples. y : array-like of shape (n_samples,), default=None The target values (integers that correspond to classes in classification, real numbers in regression). **fit_params : dict Other estimator specific parameters. Returns ------- self : object Fitted estimator. """ self._validate_params() <DeepExtract> if self.max_features is not None: n_features = _num_features(X) if callable(self.max_features): max_features = self.max_features(X) else: max_features = self.max_features check_scalar(max_features, 'max_features', Integral, min_val=0, max_val=n_features) self.max_features_ = max_features </DeepExtract> if self.prefit: try: check_is_fitted(self.estimator) except NotFittedError as exc: raise NotFittedError('When `prefit=True`, `estimator` is expected to be a fitted estimator.') from exc self.estimator_ = deepcopy(self.estimator) else: self.estimator_ = clone(self.estimator) self.estimator_.fit(X, y, **fit_params) if hasattr(self.estimator_, 'feature_names_in_'): self.feature_names_in_ = self.estimator_.feature_names_in_ else: self._check_feature_names(X, reset=True) return self
def test_binarizer(): X_ = np.array([[1, 0, 5], [2, 3, -1]]) for init in (np.array, list, sparse.csr_matrix, sparse.csc_matrix): X = init(X_.copy()) binarizer = Binarizer(threshold=2.0, copy=True) if hasattr(binarizer.transform(X), 'toarray'): binarizer.transform(X) = binarizer.transform(X).toarray() X_bin = binarizer.transform(X) assert np.sum(X_bin == 0) == 4 assert np.sum(X_bin == 1) == 2 X_bin = binarizer.transform(X) assert sparse.issparse(X) == sparse.issparse(X_bin) binarizer = Binarizer(copy=True).fit(X) if hasattr(binarizer.transform(X), 'toarray'): binarizer.transform(X) = binarizer.transform(X).toarray() X_bin = binarizer.transform(X) assert X_bin is not X assert np.sum(X_bin == 0) == 2 assert np.sum(X_bin == 1) == 4 binarizer = Binarizer(copy=True) X_bin = binarizer.transform(X) assert X_bin is not X if hasattr(X_bin, 'toarray'): X_bin = X_bin.toarray() X_bin = X_bin assert np.sum(X_bin == 0) == 2 assert np.sum(X_bin == 1) == 4 binarizer = Binarizer(copy=False) X_bin = binarizer.transform(X) if init is not list: assert X_bin is X binarizer = Binarizer(copy=False) X_float = np.array([[1, 0, 5], [2, 3, -1]], dtype=np.float64) X_bin = binarizer.transform(X_float) if init is not list: assert X_bin is X_float if hasattr(X_bin, 'toarray'): X_bin = X_bin.toarray() X_bin = X_bin assert np.sum(X_bin == 0) == 2 assert np.sum(X_bin == 1) == 4 binarizer = Binarizer(threshold=-0.5, copy=True) for init in (np.array, list): X = init(X_.copy()) if hasattr(binarizer.transform(X), 'toarray'): binarizer.transform(X) = binarizer.transform(X).toarray() X_bin = binarizer.transform(X) assert np.sum(X_bin == 0) == 1 assert np.sum(X_bin == 1) == 5 X_bin = binarizer.transform(X) with pytest.raises(ValueError): binarizer.transform(sparse.csc_matrix(X))
def test_binarizer(): X_ = np.array([[1, 0, 5], [2, 3, -1]]) for init in (np.array, list, sparse.csr_matrix, sparse.csc_matrix): X = init(X_.copy()) binarizer = Binarizer(threshold=2.0, copy=True) <DeepExtract> if hasattr(binarizer.transform(X), 'toarray'): binarizer.transform(X) = binarizer.transform(X).toarray() X_bin = binarizer.transform(X) </DeepExtract> assert np.sum(X_bin == 0) == 4 assert np.sum(X_bin == 1) == 2 X_bin = binarizer.transform(X) assert sparse.issparse(X) == sparse.issparse(X_bin) binarizer = Binarizer(copy=True).fit(X) <DeepExtract> if hasattr(binarizer.transform(X), 'toarray'): binarizer.transform(X) = binarizer.transform(X).toarray() X_bin = binarizer.transform(X) </DeepExtract> assert X_bin is not X assert np.sum(X_bin == 0) == 2 assert np.sum(X_bin == 1) == 4 binarizer = Binarizer(copy=True) X_bin = binarizer.transform(X) assert X_bin is not X <DeepExtract> if hasattr(X_bin, 'toarray'): X_bin = X_bin.toarray() X_bin = X_bin </DeepExtract> assert np.sum(X_bin == 0) == 2 assert np.sum(X_bin == 1) == 4 binarizer = Binarizer(copy=False) X_bin = binarizer.transform(X) if init is not list: assert X_bin is X binarizer = Binarizer(copy=False) X_float = np.array([[1, 0, 5], [2, 3, -1]], dtype=np.float64) X_bin = binarizer.transform(X_float) if init is not list: assert X_bin is X_float <DeepExtract> if hasattr(X_bin, 'toarray'): X_bin = X_bin.toarray() X_bin = X_bin </DeepExtract> assert np.sum(X_bin == 0) == 2 assert np.sum(X_bin == 1) == 4 binarizer = Binarizer(threshold=-0.5, copy=True) for init in (np.array, list): X = init(X_.copy()) <DeepExtract> if hasattr(binarizer.transform(X), 'toarray'): binarizer.transform(X) = binarizer.transform(X).toarray() X_bin = binarizer.transform(X) </DeepExtract> assert np.sum(X_bin == 0) == 1 assert np.sum(X_bin == 1) == 5 X_bin = binarizer.transform(X) with pytest.raises(ValueError): binarizer.transform(sparse.csc_matrix(X))
def _encode(values, *, uniques, check_unknown=True): """Helper function to encode values into [0, n_uniques - 1]. Uses pure python method for object dtype, and numpy method for all other dtypes. The numpy method has the limitation that the `uniques` need to be sorted. Importantly, this is not checked but assumed to already be the case. The calling method needs to ensure this for all non-object values. Parameters ---------- values : ndarray Values to encode. uniques : ndarray The unique values in `values`. If the dtype is not object, then `uniques` needs to be sorted. check_unknown : bool, default=True If True, check for values in `values` that are not in `unique` and raise an error. This is ignored for object dtype, and treated as True in this case. This parameter is useful for _BaseEncoder._transform() to avoid calling _check_unknown() twice. Returns ------- encoded : ndarray Encoded values """ if values.dtype.kind in 'OUS': try: return _map_to_integer(values, uniques) except KeyError as e: raise ValueError(f'y contains previously unseen labels: {str(e)}') else: if check_unknown: valid_mask = None if values.dtype.kind in 'OUS': values_set = set(values) (values_set, missing_in_values) = _extract_missing(values_set) uniques_set = set(uniques) (uniques_set, missing_in_uniques) = _extract_missing(uniques_set) diff = values_set - uniques_set nan_in_diff = missing_in_values.nan and (not missing_in_uniques.nan) none_in_diff = missing_in_values.none and (not missing_in_uniques.none) def is_valid(value): diff = value in uniques_set or (missing_in_uniques.none and value is None) or (missing_in_uniques.nan and is_scalar_nan(value)) if return_mask: if diff or nan_in_diff or none_in_diff: valid_mask = np.array([is_valid(value) for value in values]) else: valid_mask = np.ones(len(values), dtype=bool) diff = list(diff) if none_in_diff: diff.append(None) if nan_in_diff: diff.append(np.nan) else: unique_values = np.unique(values) diff = np.setdiff1d(unique_values, uniques, assume_unique=True) if return_mask: if diff.size: valid_mask = np.in1d(values, uniques) else: valid_mask = np.ones(len(values), dtype=bool) if np.isnan(uniques).any(): diff_is_nan = np.isnan(diff) if diff_is_nan.any(): if diff.size and return_mask: is_nan = np.isnan(values) valid_mask[is_nan] = 1 diff = diff[~diff_is_nan] diff = list(diff) if return_mask: diff = (diff, valid_mask) diff = diff if diff: raise ValueError(f'y contains previously unseen labels: {str(diff)}') return np.searchsorted(uniques, values)
def _encode(values, *, uniques, check_unknown=True): """Helper function to encode values into [0, n_uniques - 1]. Uses pure python method for object dtype, and numpy method for all other dtypes. The numpy method has the limitation that the `uniques` need to be sorted. Importantly, this is not checked but assumed to already be the case. The calling method needs to ensure this for all non-object values. Parameters ---------- values : ndarray Values to encode. uniques : ndarray The unique values in `values`. If the dtype is not object, then `uniques` needs to be sorted. check_unknown : bool, default=True If True, check for values in `values` that are not in `unique` and raise an error. This is ignored for object dtype, and treated as True in this case. This parameter is useful for _BaseEncoder._transform() to avoid calling _check_unknown() twice. Returns ------- encoded : ndarray Encoded values """ if values.dtype.kind in 'OUS': try: return _map_to_integer(values, uniques) except KeyError as e: raise ValueError(f'y contains previously unseen labels: {str(e)}') else: if check_unknown: <DeepExtract> valid_mask = None if values.dtype.kind in 'OUS': values_set = set(values) (values_set, missing_in_values) = _extract_missing(values_set) uniques_set = set(uniques) (uniques_set, missing_in_uniques) = _extract_missing(uniques_set) diff = values_set - uniques_set nan_in_diff = missing_in_values.nan and (not missing_in_uniques.nan) none_in_diff = missing_in_values.none and (not missing_in_uniques.none) def is_valid(value): diff = value in uniques_set or (missing_in_uniques.none and value is None) or (missing_in_uniques.nan and is_scalar_nan(value)) if return_mask: if diff or nan_in_diff or none_in_diff: valid_mask = np.array([is_valid(value) for value in values]) else: valid_mask = np.ones(len(values), dtype=bool) diff = list(diff) if none_in_diff: diff.append(None) if nan_in_diff: diff.append(np.nan) else: unique_values = np.unique(values) diff = np.setdiff1d(unique_values, uniques, assume_unique=True) if return_mask: if diff.size: valid_mask = np.in1d(values, uniques) else: valid_mask = np.ones(len(values), dtype=bool) if np.isnan(uniques).any(): diff_is_nan = np.isnan(diff) if diff_is_nan.any(): if diff.size and return_mask: is_nan = np.isnan(values) valid_mask[is_nan] = 1 diff = diff[~diff_is_nan] diff = list(diff) if return_mask: diff = (diff, valid_mask) diff = diff </DeepExtract> if diff: raise ValueError(f'y contains previously unseen labels: {str(diff)}') return np.searchsorted(uniques, values)
def fit(self, X, y=None): """Learn a list of feature name -> indices mappings. Parameters ---------- X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). .. versionchanged:: 0.24 Accepts multiple string values for one categorical feature. y : (ignored) Ignored parameter. Returns ------- self : object DictVectorizer class instance. """ self._validate_params() feature_names = [] vocab = {} for x in X: for (f, v) in x.items(): if isinstance(v, str): feature_name = '%s%s%s' % (f, self.separator, v) elif isinstance(v, Number) or v is None: feature_name = f elif isinstance(v, Mapping): raise TypeError(f'Unsupported value type {type(v)} for {f}: {v}.\nMapping objects are not supported.') elif isinstance(v, Iterable): feature_name = None for vv in v: if isinstance(vv, str): feature_name = '%s%s%s' % (f, self.separator, vv) vv = 1 else: raise TypeError(f'Unsupported type {type(vv)} in iterable value. Only iterables of string are supported.') if fitting and feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if transforming and feature_name in vocab: indices.append(vocab[feature_name]) values.append(self.dtype(vv)) if feature_name is not None: if feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if self.sort: feature_names.sort() vocab = {f: i for (i, f) in enumerate(feature_names)} self.feature_names_ = feature_names self.vocabulary_ = vocab return self
def fit(self, X, y=None): """Learn a list of feature name -> indices mappings. Parameters ---------- X : Mapping or iterable over Mappings Dict(s) or Mapping(s) from feature names (arbitrary Python objects) to feature values (strings or convertible to dtype). .. versionchanged:: 0.24 Accepts multiple string values for one categorical feature. y : (ignored) Ignored parameter. Returns ------- self : object DictVectorizer class instance. """ self._validate_params() feature_names = [] vocab = {} for x in X: for (f, v) in x.items(): if isinstance(v, str): feature_name = '%s%s%s' % (f, self.separator, v) elif isinstance(v, Number) or v is None: feature_name = f elif isinstance(v, Mapping): raise TypeError(f'Unsupported value type {type(v)} for {f}: {v}.\nMapping objects are not supported.') elif isinstance(v, Iterable): feature_name = None <DeepExtract> for vv in v: if isinstance(vv, str): feature_name = '%s%s%s' % (f, self.separator, vv) vv = 1 else: raise TypeError(f'Unsupported type {type(vv)} in iterable value. Only iterables of string are supported.') if fitting and feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if transforming and feature_name in vocab: indices.append(vocab[feature_name]) values.append(self.dtype(vv)) </DeepExtract> if feature_name is not None: if feature_name not in vocab: vocab[feature_name] = len(feature_names) feature_names.append(feature_name) if self.sort: feature_names.sort() vocab = {f: i for (i, f) in enumerate(feature_names)} self.feature_names_ = feature_names self.vocabulary_ = vocab return self
def setResultsName(self, name, listAllMatches=False): """ Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") """ ret = ParseResults(self.__toklist) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name newself = ret if name.endswith('*'): name = name[:-1] listAllMatches = True newself.resultsName = name newself.modalResults = not listAllMatches return newself
def setResultsName(self, name, listAllMatches=False): """ Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original C{ParserElement} object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. You can also set results names using the abbreviated syntax, C{expr("name")} in place of C{expr.setResultsName("name")} - see L{I{__call__}<__call__>}. Example:: date_str = (integer.setResultsName("year") + '/' + integer.setResultsName("month") + '/' + integer.setResultsName("day")) # equivalent form: date_str = integer("year") + '/' + integer("month") + '/' + integer("day") """ <DeepExtract> ret = ParseResults(self.__toklist) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name newself = ret </DeepExtract> if name.endswith('*'): name = name[:-1] listAllMatches = True newself.resultsName = name newself.modalResults = not listAllMatches return newself
def __init__(self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} self.__asList = asList self.__modal = modal if toklist is None: toklist = [] if isinstance(toklist, list): self.__toklist = toklist[:] elif isinstance(toklist, _generatorType): self.__toklist = list(toklist) else: self.__toklist = [toklist] self.__tokdict = dict() if name is not None and name: if not modal: self.__accumNames[name] = 0 if isinstance(name, int): if isinstance(name, unicode): name = name try: name = str(name) except UnicodeEncodeError: ret = unicode(name).encode(sys.getdefaultencoding(), 'xmlcharrefreplace') xmlcharref = Regex('&#\\d+;') xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:]) name = xmlcharref.transformString(ret) self.__name = name if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None, '', [])): if isinstance(toklist, basestring): toklist = [toklist] if asList: if isinstance(toklist, ParseResults): self[name] = _ParseResultsWithOffset(toklist.copy(), 0) else: self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0) self[name].__name = name else: try: self[name] = toklist[0] except (KeyError, TypeError, IndexError): self[name] = toklist
def __init__(self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} self.__asList = asList self.__modal = modal if toklist is None: toklist = [] if isinstance(toklist, list): self.__toklist = toklist[:] elif isinstance(toklist, _generatorType): self.__toklist = list(toklist) else: self.__toklist = [toklist] self.__tokdict = dict() if name is not None and name: if not modal: self.__accumNames[name] = 0 if isinstance(name, int): <DeepExtract> if isinstance(name, unicode): name = name try: name = str(name) except UnicodeEncodeError: ret = unicode(name).encode(sys.getdefaultencoding(), 'xmlcharrefreplace') xmlcharref = Regex('&#\\d+;') xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:]) name = xmlcharref.transformString(ret) </DeepExtract> self.__name = name if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None, '', [])): if isinstance(toklist, basestring): toklist = [toklist] if asList: if isinstance(toklist, ParseResults): self[name] = _ParseResultsWithOffset(toklist.copy(), 0) else: self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]), 0) self[name].__name = name else: try: self[name] = toklist[0] except (KeyError, TypeError, IndexError): self[name] = toklist
def fit(self, X, y=None): """Fit the GraphicalLasso model to X. Parameters ---------- X : array-like of shape (n_samples, n_features) Data from which to compute the covariance estimate. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Returns the instance itself. """ self._validate_params() X = self._validate_data(X, ensure_min_features=2, ensure_min_samples=2) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) emp_cov = empirical_covariance(X, assume_centered=self.assume_centered) (_, n_features) = emp_cov.shape if self.alpha == 0: if return_costs: precision_ = linalg.inv(emp_cov) cost = -2.0 * log_likelihood(emp_cov, precision_) cost += n_features * np.log(2 * np.pi) d_gap = np.sum(emp_cov * precision_) - n_features if True: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, precision_, (cost, d_gap), 0) else: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, precision_, (cost, d_gap)) elif True: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, linalg.inv(emp_cov), 0) else: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, linalg.inv(emp_cov)) if cov_init is None: covariance_ = emp_cov.copy() else: covariance_ = cov_init.copy() covariance_ *= 0.95 diagonal = emp_cov.flat[::n_features + 1] covariance_.flat[::n_features + 1] = diagonal precision_ = linalg.pinvh(covariance_) indices = np.arange(n_features) costs = list() if self.mode == 'cd': errors = dict(over='raise', invalid='ignore') else: errors = dict(invalid='raise') try: d_gap = np.inf sub_covariance = np.copy(covariance_[1:, 1:], order='C') for i in range(self.max_iter): for idx in range(n_features): if idx > 0: di = idx - 1 sub_covariance[di] = covariance_[di][indices != idx] sub_covariance[:, di] = covariance_[:, di][indices != idx] else: sub_covariance[:] = covariance_[1:, 1:] row = emp_cov[idx, indices != idx] with np.errstate(**errors): if self.mode == 'cd': coefs = -(precision_[indices != idx, idx] / (precision_[idx, idx] + 1000 * eps)) (coefs, _, _, _) = cd_fast.enet_coordinate_descent_gram(coefs, self.alpha, 0, sub_covariance, row, row, self.max_iter, self.enet_tol, check_random_state(None), False) else: (_, _, coefs) = lars_path_gram(Xy=row, Gram=sub_covariance, n_samples=row.size, alpha_min=self.alpha / (n_features - 1), copy_Gram=True, eps=eps, method='lars', return_path=False) precision_[idx, idx] = 1.0 / (covariance_[idx, idx] - np.dot(covariance_[indices != idx, idx], coefs)) precision_[indices != idx, idx] = -precision_[idx, idx] * coefs precision_[idx, indices != idx] = -precision_[idx, idx] * coefs coefs = np.dot(sub_covariance, coefs) covariance_[idx, indices != idx] = coefs covariance_[indices != idx, idx] = coefs if not np.isfinite(precision_.sum()): raise FloatingPointError('The system is too ill-conditioned for this solver') d_gap = _dual_gap(emp_cov, precision_, self.alpha) cost = _objective(emp_cov, precision_, self.alpha) if self.verbose: print('[graphical_lasso] Iteration % 3i, cost % 3.2e, dual gap %.3e' % (i, cost, d_gap)) if return_costs: costs.append((cost, d_gap)) if np.abs(d_gap) < self.tol: break if not np.isfinite(cost) and i > 0: raise FloatingPointError('Non SPD result: the system is too ill-conditioned for this solver') else: warnings.warn('graphical_lasso: did not converge after %i iteration: dual gap: %.3e' % (self.max_iter, d_gap), ConvergenceWarning) except FloatingPointError as e: e.args = (e.args[0] + '. The system is too ill-conditioned for this solver',) raise e if return_costs: if True: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_, costs, i + 1) else: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_, costs) elif True: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_, i + 1) else: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_) return self
def fit(self, X, y=None): """Fit the GraphicalLasso model to X. Parameters ---------- X : array-like of shape (n_samples, n_features) Data from which to compute the covariance estimate. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Returns the instance itself. """ self._validate_params() X = self._validate_data(X, ensure_min_features=2, ensure_min_samples=2) if self.assume_centered: self.location_ = np.zeros(X.shape[1]) else: self.location_ = X.mean(0) emp_cov = empirical_covariance(X, assume_centered=self.assume_centered) <DeepExtract> (_, n_features) = emp_cov.shape if self.alpha == 0: if return_costs: precision_ = linalg.inv(emp_cov) cost = -2.0 * log_likelihood(emp_cov, precision_) cost += n_features * np.log(2 * np.pi) d_gap = np.sum(emp_cov * precision_) - n_features if True: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, precision_, (cost, d_gap), 0) else: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, precision_, (cost, d_gap)) elif True: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, linalg.inv(emp_cov), 0) else: (self.covariance_, self.precision_, self.n_iter_) = (emp_cov, linalg.inv(emp_cov)) if cov_init is None: covariance_ = emp_cov.copy() else: covariance_ = cov_init.copy() covariance_ *= 0.95 diagonal = emp_cov.flat[::n_features + 1] covariance_.flat[::n_features + 1] = diagonal precision_ = linalg.pinvh(covariance_) indices = np.arange(n_features) costs = list() if self.mode == 'cd': errors = dict(over='raise', invalid='ignore') else: errors = dict(invalid='raise') try: d_gap = np.inf sub_covariance = np.copy(covariance_[1:, 1:], order='C') for i in range(self.max_iter): for idx in range(n_features): if idx > 0: di = idx - 1 sub_covariance[di] = covariance_[di][indices != idx] sub_covariance[:, di] = covariance_[:, di][indices != idx] else: sub_covariance[:] = covariance_[1:, 1:] row = emp_cov[idx, indices != idx] with np.errstate(**errors): if self.mode == 'cd': coefs = -(precision_[indices != idx, idx] / (precision_[idx, idx] + 1000 * eps)) (coefs, _, _, _) = cd_fast.enet_coordinate_descent_gram(coefs, self.alpha, 0, sub_covariance, row, row, self.max_iter, self.enet_tol, check_random_state(None), False) else: (_, _, coefs) = lars_path_gram(Xy=row, Gram=sub_covariance, n_samples=row.size, alpha_min=self.alpha / (n_features - 1), copy_Gram=True, eps=eps, method='lars', return_path=False) precision_[idx, idx] = 1.0 / (covariance_[idx, idx] - np.dot(covariance_[indices != idx, idx], coefs)) precision_[indices != idx, idx] = -precision_[idx, idx] * coefs precision_[idx, indices != idx] = -precision_[idx, idx] * coefs coefs = np.dot(sub_covariance, coefs) covariance_[idx, indices != idx] = coefs covariance_[indices != idx, idx] = coefs if not np.isfinite(precision_.sum()): raise FloatingPointError('The system is too ill-conditioned for this solver') d_gap = _dual_gap(emp_cov, precision_, self.alpha) cost = _objective(emp_cov, precision_, self.alpha) if self.verbose: print('[graphical_lasso] Iteration % 3i, cost % 3.2e, dual gap %.3e' % (i, cost, d_gap)) if return_costs: costs.append((cost, d_gap)) if np.abs(d_gap) < self.tol: break if not np.isfinite(cost) and i > 0: raise FloatingPointError('Non SPD result: the system is too ill-conditioned for this solver') else: warnings.warn('graphical_lasso: did not converge after %i iteration: dual gap: %.3e' % (self.max_iter, d_gap), ConvergenceWarning) except FloatingPointError as e: e.args = (e.args[0] + '. The system is too ill-conditioned for this solver',) raise e if return_costs: if True: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_, costs, i + 1) else: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_, costs) elif True: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_, i + 1) else: (self.covariance_, self.precision_, self.n_iter_) = (covariance_, precision_) </DeepExtract> return self
def explained_variance_score(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average', force_finite=True): """Explained variance regression score function. Best possible score is 1.0, lower values are worse. In the particular case when ``y_true`` is constant, the explained variance score is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to pollute higher-level experiments such as a grid search cross-validation, by default these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect predictions) respectively. If ``force_finite`` is set to ``False``, this score falls back on the original :math:`R^2` definition. .. note:: The Explained Variance score is similar to the :func:`R^2 score <r2_score>`, with the notable difference that it does not account for systematic offsets in the prediction. Most often the :func:`R^2 score <r2_score>` should be preferred. Read more in the :ref:`User Guide <explained_variance_score>`. 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. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. force_finite : bool, default=True Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant data should be replaced with real numbers (``1.0`` if prediction is perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting for hyperparameters' search procedures (e.g. grid search cross-validation). .. versionadded:: 1.1 Returns ------- score : float or ndarray of floats The explained variance or ndarray if 'multioutput' is 'raw_values'. See Also -------- r2_score : Similar metric, but accounting for systematic offsets in prediction. Notes ----- This is not a symmetric function. Examples -------- >>> from sklearn.metrics import explained_variance_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> explained_variance_score(y_true, y_pred) 0.957... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') 0.983... >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2] >>> explained_variance_score(y_true, y_pred) 1.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) nan >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2 + 1e-8] >>> explained_variance_score(y_true, y_pred) 0.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) -inf """ 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) y_diff_avg = np.average(y_true - y_pred, weights=sample_weight, axis=0) numerator = np.average((y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0) y_true_avg = np.average(y_true, weights=sample_weight, axis=0) denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) return _assemble_r2_explained_variance(numerator=numerator, denominator=denominator, n_outputs=y_true.shape[1], multioutput=multioutput, force_finite=force_finite)
def explained_variance_score(y_true, y_pred, *, sample_weight=None, multioutput='uniform_average', force_finite=True): """Explained variance regression score function. Best possible score is 1.0, lower values are worse. In the particular case when ``y_true`` is constant, the explained variance score is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to pollute higher-level experiments such as a grid search cross-validation, by default these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect predictions) respectively. If ``force_finite`` is set to ``False``, this score falls back on the original :math:`R^2` definition. .. note:: The Explained Variance score is similar to the :func:`R^2 score <r2_score>`, with the notable difference that it does not account for systematic offsets in the prediction. Most often the :func:`R^2 score <r2_score>` should be preferred. Read more in the :ref:`User Guide <explained_variance_score>`. 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. multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or array-like of shape (n_outputs,), default='uniform_average' Defines aggregating of multiple output scores. Array-like value defines weights used to average scores. 'raw_values' : Returns a full set of scores in case of multioutput input. 'uniform_average' : Scores of all outputs are averaged with uniform weight. 'variance_weighted' : Scores of all outputs are averaged, weighted by the variances of each individual output. force_finite : bool, default=True Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant data should be replaced with real numbers (``1.0`` if prediction is perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting for hyperparameters' search procedures (e.g. grid search cross-validation). .. versionadded:: 1.1 Returns ------- score : float or ndarray of floats The explained variance or ndarray if 'multioutput' is 'raw_values'. See Also -------- r2_score : Similar metric, but accounting for systematic offsets in prediction. Notes ----- This is not a symmetric function. Examples -------- >>> from sklearn.metrics import explained_variance_score >>> y_true = [3, -0.5, 2, 7] >>> y_pred = [2.5, 0.0, 2, 8] >>> explained_variance_score(y_true, y_pred) 0.957... >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] >>> y_pred = [[0, 2], [-1, 2], [8, -5]] >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') 0.983... >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2] >>> explained_variance_score(y_true, y_pred) 1.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) nan >>> y_true = [-2, -2, -2] >>> y_pred = [-2, -2, -2 + 1e-8] >>> explained_variance_score(y_true, y_pred) 0.0 >>> explained_variance_score(y_true, y_pred, force_finite=False) -inf """ <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) y_diff_avg = np.average(y_true - y_pred, weights=sample_weight, axis=0) numerator = np.average((y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0) y_true_avg = np.average(y_true, weights=sample_weight, axis=0) denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) return _assemble_r2_explained_variance(numerator=numerator, denominator=denominator, n_outputs=y_true.shape[1], multioutput=multioutput, force_finite=force_finite)
def fit(self, X, y, sample_weight=None): """ Fit the model according to the given training data. 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. y : array-like of shape (n_samples,) Target vector relative to X. sample_weight : array-like of shape (n_samples,) default=None Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. .. versionadded:: 0.17 *sample_weight* support to LogisticRegression. Returns ------- self Fitted estimator. Notes ----- The SAGA solver supports both float64 and float32 bit arrays. """ self._validate_params() if self.solver not in ['liblinear', 'saga'] and self.penalty not in ('l2', 'none', None): raise ValueError("Solver %s supports only 'l2' or 'none' penalties, got %s penalty." % (self.solver, self.penalty)) if self.solver != 'liblinear' and self.dual: raise ValueError('Solver %s supports only dual=False, got dual=%s' % (self.solver, self.dual)) if self.penalty == 'elasticnet' and self.solver != 'saga': raise ValueError("Only 'saga' solver supports elasticnet penalty, got solver={}.".format(self.solver)) if self.solver == 'liblinear' and self.penalty == 'none': raise ValueError("penalty='none' is not supported for the liblinear solver") self.solver = self.solver if self.penalty != 'elasticnet' and self.l1_ratio is not None: warnings.warn("l1_ratio parameter is only used when penalty is 'elasticnet'. Got (penalty={})".format(self.penalty)) if self.penalty == 'elasticnet' and self.l1_ratio is None: raise ValueError('l1_ratio must be specified when penalty is elasticnet.') if self.penalty == 'none': warnings.warn("`penalty='none'`has been deprecated in 1.2 and will be removed in 1.4. To keep the past behaviour, set `penalty=None`.", FutureWarning) if self.penalty is None or self.penalty == 'none': if self.C != 1.0: warnings.warn('Setting penalty=None will ignore the C and l1_ratio parameters') C_ = np.inf penalty = 'l2' else: C_ = self.C penalty = self.penalty if solver == 'lbfgs': _dtype = np.float64 else: _dtype = [np.float64, np.float32] (X, y) = self._validate_data(X, y, accept_sparse='csr', dtype=_dtype, order='C', accept_large_sparse=solver not in ['liblinear', 'sag', 'saga']) check_classification_targets(y) self.classes_ = np.unique(y) if self.multi_class == 'auto': if solver in ('liblinear', 'newton-cholesky'): self.multi_class = 'ovr' elif len(self.classes_) > 2: self.multi_class = 'multinomial' else: self.multi_class = 'ovr' if self.multi_class == 'multinomial' and solver in ('liblinear', 'newton-cholesky'): raise ValueError('Solver %s does not support a multinomial backend.' % solver) self.multi_class = self.multi_class if solver == 'liblinear': if effective_n_jobs(self.n_jobs) != 1: warnings.warn("'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = {}.".format(effective_n_jobs(self.n_jobs))) (self.coef_, self.intercept_, self.n_iter_) = _fit_liblinear(X, y, self.C, self.fit_intercept, self.intercept_scaling, self.class_weight, self.penalty, self.dual, self.verbose, self.max_iter, self.tol, self.random_state, sample_weight=sample_weight) return self if solver in ['sag', 'saga']: max_squared_sum = row_norms(X, squared=True).max() else: max_squared_sum = None n_classes = len(self.classes_) classes_ = self.classes_ if n_classes < 2: raise ValueError('This solver needs samples of at least 2 classes in the data, but the data contains only one class: %r' % classes_[0]) if len(self.classes_) == 2: n_classes = 1 classes_ = classes_[1:] if self.warm_start: warm_start_coef = getattr(self, 'coef_', None) else: warm_start_coef = None if warm_start_coef is not None and self.fit_intercept: warm_start_coef = np.append(warm_start_coef, self.intercept_[:, np.newaxis], axis=1) if multi_class == 'multinomial': classes_ = [None] warm_start_coef = [warm_start_coef] if warm_start_coef is None: warm_start_coef = [None] * n_classes path_func = delayed(_logistic_regression_path) if solver in ['sag', 'saga']: prefer = 'threads' else: prefer = 'processes' if solver in ['lbfgs', 'newton-cg', 'newton-cholesky'] and len(classes_) == 1 and (effective_n_jobs(self.n_jobs) == 1): n_threads = 1 else: n_threads = 1 fold_coefs_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, prefer=prefer)((path_func(X, y, pos_class=class_, Cs=[C_], l1_ratio=self.l1_ratio, fit_intercept=self.fit_intercept, tol=self.tol, verbose=self.verbose, solver=solver, multi_class=multi_class, max_iter=self.max_iter, class_weight=self.class_weight, check_input=False, random_state=self.random_state, coef=warm_start_coef_, penalty=penalty, max_squared_sum=max_squared_sum, sample_weight=sample_weight, n_threads=n_threads) for (class_, warm_start_coef_) in zip(classes_, warm_start_coef))) (fold_coefs_, _, n_iter_) = zip(*fold_coefs_) self.n_iter_ = np.asarray(n_iter_, dtype=np.int32)[:, 0] n_features = X.shape[1] if multi_class == 'multinomial': self.coef_ = fold_coefs_[0][0] else: self.coef_ = np.asarray(fold_coefs_) self.coef_ = self.coef_.reshape(n_classes, n_features + int(self.fit_intercept)) if self.fit_intercept: self.intercept_ = self.coef_[:, -1] self.coef_ = self.coef_[:, :-1] else: self.intercept_ = np.zeros(n_classes) return self
def fit(self, X, y, sample_weight=None): """ Fit the model according to the given training data. 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. y : array-like of shape (n_samples,) Target vector relative to X. sample_weight : array-like of shape (n_samples,) default=None Array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. .. versionadded:: 0.17 *sample_weight* support to LogisticRegression. Returns ------- self Fitted estimator. Notes ----- The SAGA solver supports both float64 and float32 bit arrays. """ self._validate_params() <DeepExtract> if self.solver not in ['liblinear', 'saga'] and self.penalty not in ('l2', 'none', None): raise ValueError("Solver %s supports only 'l2' or 'none' penalties, got %s penalty." % (self.solver, self.penalty)) if self.solver != 'liblinear' and self.dual: raise ValueError('Solver %s supports only dual=False, got dual=%s' % (self.solver, self.dual)) if self.penalty == 'elasticnet' and self.solver != 'saga': raise ValueError("Only 'saga' solver supports elasticnet penalty, got solver={}.".format(self.solver)) if self.solver == 'liblinear' and self.penalty == 'none': raise ValueError("penalty='none' is not supported for the liblinear solver") self.solver = self.solver </DeepExtract> if self.penalty != 'elasticnet' and self.l1_ratio is not None: warnings.warn("l1_ratio parameter is only used when penalty is 'elasticnet'. Got (penalty={})".format(self.penalty)) if self.penalty == 'elasticnet' and self.l1_ratio is None: raise ValueError('l1_ratio must be specified when penalty is elasticnet.') if self.penalty == 'none': warnings.warn("`penalty='none'`has been deprecated in 1.2 and will be removed in 1.4. To keep the past behaviour, set `penalty=None`.", FutureWarning) if self.penalty is None or self.penalty == 'none': if self.C != 1.0: warnings.warn('Setting penalty=None will ignore the C and l1_ratio parameters') C_ = np.inf penalty = 'l2' else: C_ = self.C penalty = self.penalty if solver == 'lbfgs': _dtype = np.float64 else: _dtype = [np.float64, np.float32] (X, y) = self._validate_data(X, y, accept_sparse='csr', dtype=_dtype, order='C', accept_large_sparse=solver not in ['liblinear', 'sag', 'saga']) check_classification_targets(y) self.classes_ = np.unique(y) <DeepExtract> if self.multi_class == 'auto': if solver in ('liblinear', 'newton-cholesky'): self.multi_class = 'ovr' elif len(self.classes_) > 2: self.multi_class = 'multinomial' else: self.multi_class = 'ovr' if self.multi_class == 'multinomial' and solver in ('liblinear', 'newton-cholesky'): raise ValueError('Solver %s does not support a multinomial backend.' % solver) self.multi_class = self.multi_class </DeepExtract> if solver == 'liblinear': if effective_n_jobs(self.n_jobs) != 1: warnings.warn("'n_jobs' > 1 does not have any effect when 'solver' is set to 'liblinear'. Got 'n_jobs' = {}.".format(effective_n_jobs(self.n_jobs))) (self.coef_, self.intercept_, self.n_iter_) = _fit_liblinear(X, y, self.C, self.fit_intercept, self.intercept_scaling, self.class_weight, self.penalty, self.dual, self.verbose, self.max_iter, self.tol, self.random_state, sample_weight=sample_weight) return self if solver in ['sag', 'saga']: max_squared_sum = row_norms(X, squared=True).max() else: max_squared_sum = None n_classes = len(self.classes_) classes_ = self.classes_ if n_classes < 2: raise ValueError('This solver needs samples of at least 2 classes in the data, but the data contains only one class: %r' % classes_[0]) if len(self.classes_) == 2: n_classes = 1 classes_ = classes_[1:] if self.warm_start: warm_start_coef = getattr(self, 'coef_', None) else: warm_start_coef = None if warm_start_coef is not None and self.fit_intercept: warm_start_coef = np.append(warm_start_coef, self.intercept_[:, np.newaxis], axis=1) if multi_class == 'multinomial': classes_ = [None] warm_start_coef = [warm_start_coef] if warm_start_coef is None: warm_start_coef = [None] * n_classes path_func = delayed(_logistic_regression_path) if solver in ['sag', 'saga']: prefer = 'threads' else: prefer = 'processes' if solver in ['lbfgs', 'newton-cg', 'newton-cholesky'] and len(classes_) == 1 and (effective_n_jobs(self.n_jobs) == 1): n_threads = 1 else: n_threads = 1 fold_coefs_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, prefer=prefer)((path_func(X, y, pos_class=class_, Cs=[C_], l1_ratio=self.l1_ratio, fit_intercept=self.fit_intercept, tol=self.tol, verbose=self.verbose, solver=solver, multi_class=multi_class, max_iter=self.max_iter, class_weight=self.class_weight, check_input=False, random_state=self.random_state, coef=warm_start_coef_, penalty=penalty, max_squared_sum=max_squared_sum, sample_weight=sample_weight, n_threads=n_threads) for (class_, warm_start_coef_) in zip(classes_, warm_start_coef))) (fold_coefs_, _, n_iter_) = zip(*fold_coefs_) self.n_iter_ = np.asarray(n_iter_, dtype=np.int32)[:, 0] n_features = X.shape[1] if multi_class == 'multinomial': self.coef_ = fold_coefs_[0][0] else: self.coef_ = np.asarray(fold_coefs_) self.coef_ = self.coef_.reshape(n_classes, n_features + int(self.fit_intercept)) if self.fit_intercept: self.intercept_ = self.coef_[:, -1] self.coef_ = self.coef_[:, :-1] else: self.intercept_ = np.zeros(n_classes) return self
def resample(*arrays, replace=True, n_samples=None, random_state=None, stratify=None): """Resample arrays or sparse matrices in a consistent way. The default strategy implements one step of the bootstrapping procedure. Parameters ---------- *arrays : sequence of array-like of shape (n_samples,) or (n_samples, n_outputs) Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension. replace : bool, default=True Implements resampling with replacement. If False, this will implement (sliced) random permutations. n_samples : int, default=None Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. If replace is False it should not be larger than the length of arrays. random_state : int, RandomState instance or None, default=None Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. stratify : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None If not None, data is split in a stratified fashion, using this as the class labels. Returns ------- resampled_arrays : sequence of array-like of shape (n_samples,) or (n_samples, n_outputs) Sequence of resampled copies of the collections. The original arrays are not impacted. See Also -------- shuffle : Shuffle arrays or sparse matrices in a consistent way. Examples -------- It is possible to mix sparse and dense arrays in the same run:: >>> import numpy as np >>> X = np.array([[1., 0.], [2., 1.], [0., 0.]]) >>> y = np.array([0, 1, 2]) >>> from scipy.sparse import coo_matrix >>> X_sparse = coo_matrix(X) >>> from sklearn.utils import resample >>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0) >>> X array([[1., 0.], [2., 1.], [1., 0.]]) >>> X_sparse <3x2 sparse matrix of type '<... 'numpy.float64'>' with 4 stored elements in Compressed Sparse Row format> >>> X_sparse.toarray() array([[1., 0.], [2., 1.], [1., 0.]]) >>> y array([0, 1, 0]) >>> resample(y, n_samples=2, random_state=0) array([0, 1]) Example using stratification:: >>> y = [0, 0, 1, 1, 1, 1, 1, 1, 1] >>> resample(y, n_samples=5, replace=False, stratify=y, ... random_state=0) [1, 1, 1, 0, 1] """ max_n_samples = n_samples random_state = check_random_state(random_state) if len(arrays) == 0: return None first = arrays[0] n_samples = first.shape[0] if hasattr(first, 'shape') else len(first) if max_n_samples is None: max_n_samples = n_samples elif max_n_samples > n_samples and (not replace): raise ValueError('Cannot sample %d out of arrays with dim %d when replace is False' % (max_n_samples, n_samples)) check_consistent_length(*arrays) if stratify is None: if replace: indices = random_state.randint(0, n_samples, size=(max_n_samples,)) else: indices = np.arange(n_samples) random_state.shuffle(indices) indices = indices[:max_n_samples] else: y = check_array(stratify, ensure_2d=False, dtype=None) if y.ndim == 2: y = np.array([' '.join(row.astype('str')) for row in y]) (classes, y_indices) = np.unique(y, return_inverse=True) n_classes = classes.shape[0] class_counts = np.bincount(y_indices) class_indices = np.split(np.argsort(y_indices, kind='mergesort'), np.cumsum(class_counts)[:-1]) random_state = check_random_state(random_state) continuous = class_counts / class_counts.sum() * max_n_samples floored = np.floor(continuous) need_to_add = int(max_n_samples - floored.sum()) if need_to_add > 0: remainder = continuous - floored values = np.sort(np.unique(remainder))[::-1] for value in values: (inds,) = np.where(remainder == value) add_now = min(len(inds), need_to_add) inds = random_state.choice(inds, size=add_now, replace=False) floored[inds] += 1 need_to_add -= add_now if need_to_add == 0: break n_i = floored.astype(int) indices = [] for i in range(n_classes): indices_i = random_state.choice(class_indices[i], n_i[i], replace=replace) indices.extend(indices_i) indices = random_state.permutation(indices) arrays = [a.tocsr() if issparse(a) else a for a in arrays] resampled_arrays = [_safe_indexing(a, indices) for a in arrays] if len(resampled_arrays) == 1: return resampled_arrays[0] else: return resampled_arrays
def resample(*arrays, replace=True, n_samples=None, random_state=None, stratify=None): """Resample arrays or sparse matrices in a consistent way. The default strategy implements one step of the bootstrapping procedure. Parameters ---------- *arrays : sequence of array-like of shape (n_samples,) or (n_samples, n_outputs) Indexable data-structures can be arrays, lists, dataframes or scipy sparse matrices with consistent first dimension. replace : bool, default=True Implements resampling with replacement. If False, this will implement (sliced) random permutations. n_samples : int, default=None Number of samples to generate. If left to None this is automatically set to the first dimension of the arrays. If replace is False it should not be larger than the length of arrays. random_state : int, RandomState instance or None, default=None Determines random number generation for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. stratify : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None If not None, data is split in a stratified fashion, using this as the class labels. Returns ------- resampled_arrays : sequence of array-like of shape (n_samples,) or (n_samples, n_outputs) Sequence of resampled copies of the collections. The original arrays are not impacted. See Also -------- shuffle : Shuffle arrays or sparse matrices in a consistent way. Examples -------- It is possible to mix sparse and dense arrays in the same run:: >>> import numpy as np >>> X = np.array([[1., 0.], [2., 1.], [0., 0.]]) >>> y = np.array([0, 1, 2]) >>> from scipy.sparse import coo_matrix >>> X_sparse = coo_matrix(X) >>> from sklearn.utils import resample >>> X, X_sparse, y = resample(X, X_sparse, y, random_state=0) >>> X array([[1., 0.], [2., 1.], [1., 0.]]) >>> X_sparse <3x2 sparse matrix of type '<... 'numpy.float64'>' with 4 stored elements in Compressed Sparse Row format> >>> X_sparse.toarray() array([[1., 0.], [2., 1.], [1., 0.]]) >>> y array([0, 1, 0]) >>> resample(y, n_samples=2, random_state=0) array([0, 1]) Example using stratification:: >>> y = [0, 0, 1, 1, 1, 1, 1, 1, 1] >>> resample(y, n_samples=5, replace=False, stratify=y, ... random_state=0) [1, 1, 1, 0, 1] """ max_n_samples = n_samples random_state = check_random_state(random_state) if len(arrays) == 0: return None first = arrays[0] n_samples = first.shape[0] if hasattr(first, 'shape') else len(first) if max_n_samples is None: max_n_samples = n_samples elif max_n_samples > n_samples and (not replace): raise ValueError('Cannot sample %d out of arrays with dim %d when replace is False' % (max_n_samples, n_samples)) check_consistent_length(*arrays) if stratify is None: if replace: indices = random_state.randint(0, n_samples, size=(max_n_samples,)) else: indices = np.arange(n_samples) random_state.shuffle(indices) indices = indices[:max_n_samples] else: y = check_array(stratify, ensure_2d=False, dtype=None) if y.ndim == 2: y = np.array([' '.join(row.astype('str')) for row in y]) (classes, y_indices) = np.unique(y, return_inverse=True) n_classes = classes.shape[0] class_counts = np.bincount(y_indices) class_indices = np.split(np.argsort(y_indices, kind='mergesort'), np.cumsum(class_counts)[:-1]) <DeepExtract> random_state = check_random_state(random_state) continuous = class_counts / class_counts.sum() * max_n_samples floored = np.floor(continuous) need_to_add = int(max_n_samples - floored.sum()) if need_to_add > 0: remainder = continuous - floored values = np.sort(np.unique(remainder))[::-1] for value in values: (inds,) = np.where(remainder == value) add_now = min(len(inds), need_to_add) inds = random_state.choice(inds, size=add_now, replace=False) floored[inds] += 1 need_to_add -= add_now if need_to_add == 0: break n_i = floored.astype(int) </DeepExtract> indices = [] for i in range(n_classes): indices_i = random_state.choice(class_indices[i], n_i[i], replace=replace) indices.extend(indices_i) indices = random_state.permutation(indices) arrays = [a.tocsr() if issparse(a) else a for a in arrays] resampled_arrays = [_safe_indexing(a, indices) for a in arrays] if len(resampled_arrays) == 1: return resampled_arrays[0] else: return resampled_arrays
def _get_support_mask(self): estimator = getattr(self, 'estimator_', self.estimator) max_features = getattr(self, 'max_features_', self.max_features) if self.prefit: try: check_is_fitted(self.estimator) except NotFittedError as exc: raise NotFittedError('When `prefit=True`, `estimator` is expected to be a fitted estimator.') from exc if callable(max_features): raise NotFittedError('When `prefit=True` and `max_features` is a callable, call `fit` before calling `transform`.') elif max_features is not None and (not isinstance(max_features, Integral)): raise ValueError(f'`max_features` must be an integer. Got `max_features={max_features}` instead.') scores = _get_feature_importances(estimator=estimator, getter=self.importance_getter, transform_func='norm', norm_order=self.norm_order) if self.threshold is None: est_name = estimator.__class__.__name__ is_l1_penalized = hasattr(estimator, 'penalty') and estimator.penalty == 'l1' is_lasso = 'Lasso' in est_name is_elasticnet_l1_penalized = 'ElasticNet' in est_name and (hasattr(estimator, 'l1_ratio_') and np.isclose(estimator.l1_ratio_, 1.0) or (hasattr(estimator, 'l1_ratio') and np.isclose(estimator.l1_ratio, 1.0))) if is_l1_penalized or is_lasso or is_elasticnet_l1_penalized: self.threshold = 1e-05 else: self.threshold = 'mean' if isinstance(self.threshold, str): if '*' in self.threshold: (scale, reference) = self.threshold.split('*') scale = float(scale.strip()) reference = reference.strip() if reference == 'median': reference = np.median(scores) elif reference == 'mean': reference = np.mean(scores) else: raise ValueError('Unknown reference: ' + reference) self.threshold = scale * reference elif self.threshold == 'median': self.threshold = np.median(scores) elif self.threshold == 'mean': self.threshold = np.mean(scores) else: raise ValueError("Expected threshold='mean' or threshold='median' got %s" % self.threshold) else: self.threshold = float(self.threshold) self.threshold = self.threshold if self.max_features is not None: mask = np.zeros_like(scores, dtype=bool) candidate_indices = np.argsort(-scores, kind='mergesort')[:max_features] mask[candidate_indices] = True else: mask = np.ones_like(scores, dtype=bool) mask[scores < threshold] = False return mask
def _get_support_mask(self): estimator = getattr(self, 'estimator_', self.estimator) max_features = getattr(self, 'max_features_', self.max_features) if self.prefit: try: check_is_fitted(self.estimator) except NotFittedError as exc: raise NotFittedError('When `prefit=True`, `estimator` is expected to be a fitted estimator.') from exc if callable(max_features): raise NotFittedError('When `prefit=True` and `max_features` is a callable, call `fit` before calling `transform`.') elif max_features is not None and (not isinstance(max_features, Integral)): raise ValueError(f'`max_features` must be an integer. Got `max_features={max_features}` instead.') scores = _get_feature_importances(estimator=estimator, getter=self.importance_getter, transform_func='norm', norm_order=self.norm_order) <DeepExtract> if self.threshold is None: est_name = estimator.__class__.__name__ is_l1_penalized = hasattr(estimator, 'penalty') and estimator.penalty == 'l1' is_lasso = 'Lasso' in est_name is_elasticnet_l1_penalized = 'ElasticNet' in est_name and (hasattr(estimator, 'l1_ratio_') and np.isclose(estimator.l1_ratio_, 1.0) or (hasattr(estimator, 'l1_ratio') and np.isclose(estimator.l1_ratio, 1.0))) if is_l1_penalized or is_lasso or is_elasticnet_l1_penalized: self.threshold = 1e-05 else: self.threshold = 'mean' if isinstance(self.threshold, str): if '*' in self.threshold: (scale, reference) = self.threshold.split('*') scale = float(scale.strip()) reference = reference.strip() if reference == 'median': reference = np.median(scores) elif reference == 'mean': reference = np.mean(scores) else: raise ValueError('Unknown reference: ' + reference) self.threshold = scale * reference elif self.threshold == 'median': self.threshold = np.median(scores) elif self.threshold == 'mean': self.threshold = np.mean(scores) else: raise ValueError("Expected threshold='mean' or threshold='median' got %s" % self.threshold) else: self.threshold = float(self.threshold) self.threshold = self.threshold </DeepExtract> if self.max_features is not None: mask = np.zeros_like(scores, dtype=bool) candidate_indices = np.argsort(-scores, kind='mergesort')[:max_features] mask[candidate_indices] = True else: mask = np.ones_like(scores, dtype=bool) mask[scores < threshold] = False return mask
@pytest.mark.parametrize('param, ExceptionCls, match', [({'n_subsamples': 1}, ValueError, re.escape('Invalid parameter since n_features+1 > n_subsamples (2 > 1)')), ({'n_subsamples': 101}, ValueError, re.escape('Invalid parameter since n_subsamples > n_samples (101 > 50)'))]) def test_checksubparams_invalid_input(param, ExceptionCls, match): random_state = np.random.RandomState(0) w = 3.0 if intercept: c = 2.0 n_samples = 50 else: c = 0.1 n_samples = 100 x = random_state.normal(size=n_samples) noise = 0.1 * random_state.normal(size=n_samples) y = w * x + c + noise if intercept: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[33], y[33]) = (2.5, 1) (x[49], y[49]) = (2.1, 2) else: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[53], y[53]) = (2.5, 1) (x[60], y[60]) = (2.1, 2) (x[72], y[72]) = (1.8, -7) (X, y, w, c) = (x[:, np.newaxis], y, w, c) theil_sen = TheilSenRegressor(**param, random_state=0) with pytest.raises(ExceptionCls, match=match): theil_sen.fit(X, y)
@pytest.mark.parametrize('param, ExceptionCls, match', [({'n_subsamples': 1}, ValueError, re.escape('Invalid parameter since n_features+1 > n_subsamples (2 > 1)')), ({'n_subsamples': 101}, ValueError, re.escape('Invalid parameter since n_subsamples > n_samples (101 > 50)'))]) def test_checksubparams_invalid_input(param, ExceptionCls, match): <DeepExtract> random_state = np.random.RandomState(0) w = 3.0 if intercept: c = 2.0 n_samples = 50 else: c = 0.1 n_samples = 100 x = random_state.normal(size=n_samples) noise = 0.1 * random_state.normal(size=n_samples) y = w * x + c + noise if intercept: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[33], y[33]) = (2.5, 1) (x[49], y[49]) = (2.1, 2) else: (x[42], y[42]) = (-2, 4) (x[43], y[43]) = (-2.5, 8) (x[53], y[53]) = (2.5, 1) (x[60], y[60]) = (2.1, 2) (x[72], y[72]) = (1.8, -7) (X, y, w, c) = (x[:, np.newaxis], y, w, c) </DeepExtract> theil_sen = TheilSenRegressor(**param, random_state=0) with pytest.raises(ExceptionCls, match=match): theil_sen.fit(X, y)
@validate_params({'y_true': ['array-like'], 'y_pred': ['array-like'], 'sample_weight': ['array-like', None]}) def matthews_corrcoef(y_true, y_pred, *, sample_weight=None): """Compute the Matthews correlation coefficient (MCC). The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] Binary and multiclass labels are supported. Only in the binary case does this relate to information about true and false positives and negatives. See references below. Read more in the :ref:`User Guide <matthews_corrcoef>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 Returns ------- mcc : float The Matthews correlation coefficient (+1 represents a perfect prediction, 0 an average random prediction and -1 and inverse prediction). References ---------- .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the accuracy of prediction algorithms for classification: an overview. <10.1093/bioinformatics/16.5.412>` .. [2] `Wikipedia entry for the Matthews Correlation Coefficient <https://en.wikipedia.org/wiki/Matthews_correlation_coefficient>`_. .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a K-category correlation coefficient <https://www.sciencedirect.com/science/article/pii/S1476927104000799>`_. .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN Error Measures in MultiClass Prediction <https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0041882>`_. Examples -------- >>> from sklearn.metrics import matthews_corrcoef >>> y_true = [+1, +1, +1, -1] >>> y_pred = [+1, -1, +1, +1] >>> matthews_corrcoef(y_true, y_pred) -0.33... """ check_consistent_length(y_true, y_pred) type_true = type_of_target(y_true, input_name='y_true') type_pred = type_of_target(y_pred, input_name='y_pred') y_type = {type_true, type_pred} if y_type == {'binary', 'multiclass'}: y_type = {'multiclass'} if len(y_type) > 1: raise ValueError("Classification metrics can't handle a mix of {0} and {1} targets".format(type_true, type_pred)) y_type = y_type.pop() if y_type not in ['binary', 'multiclass', 'multilabel-indicator']: raise ValueError('{0} is not supported'.format(y_type)) if y_type in ['binary', 'multiclass']: y_true = column_or_1d(y_true) y_pred = column_or_1d(y_pred) if y_type == 'binary': try: unique_values = np.union1d(y_true, y_pred) except TypeError as e: raise TypeError(f'Labels in y_true and y_pred should be of the same type. Got y_true={np.unique(y_true)} and y_pred={np.unique(y_pred)}. Make sure that the predictions provided by the classifier coincides with the true labels.') from e if len(unique_values) > 2: y_type = 'multiclass' if y_type.startswith('multilabel'): y_true = csr_matrix(y_true) y_pred = csr_matrix(y_pred) y_type = 'multilabel-indicator' (y_type, y_true, y_pred) = (y_type, y_true, y_pred) check_consistent_length(y_true, y_pred, sample_weight) if y_type not in {'binary', 'multiclass'}: raise ValueError('%s is not supported' % y_type) lb = LabelEncoder() lb.fit(np.hstack([y_true, y_pred])) y_true = lb.transform(y_true) y_pred = lb.transform(y_pred) (y_type, y_true, y_pred) = _check_targets(y_true, y_pred) if y_type not in ('binary', 'multiclass'): raise ValueError('%s is not supported' % y_type) if labels is None: labels = unique_labels(y_true, y_pred) else: labels = np.asarray(labels) n_labels = labels.size if n_labels == 0: raise ValueError("'labels' should contains at least one label.") elif y_true.size == 0: C = np.zeros((n_labels, n_labels), dtype=int) elif len(np.intersect1d(y_true, labels)) == 0: raise ValueError('At least one label specified must be in y_true') if sample_weight is None: sample_weight = np.ones(y_true.shape[0], dtype=np.int64) else: sample_weight = np.asarray(sample_weight) check_consistent_length(y_true, y_pred, sample_weight) n_labels = labels.size need_index_conversion = not (labels.dtype.kind in {'i', 'u', 'b'} and np.all(labels == np.arange(n_labels)) and (y_true.min() >= 0) and (y_pred.min() >= 0)) if need_index_conversion: label_to_ind = {y: x for (x, y) in enumerate(labels)} y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred]) y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true]) ind = np.logical_and(y_pred < n_labels, y_true < n_labels) if not np.all(ind): y_pred = y_pred[ind] y_true = y_true[ind] sample_weight = sample_weight[ind] if sample_weight.dtype.kind in {'i', 'u', 'b'}: dtype = np.int64 else: dtype = np.float64 cm = coo_matrix((sample_weight, (y_true, y_pred)), shape=(n_labels, n_labels), dtype=dtype).toarray() with np.errstate(all='ignore'): if normalize == 'true': cm = cm / cm.sum(axis=1, keepdims=True) elif normalize == 'pred': cm = cm / cm.sum(axis=0, keepdims=True) elif normalize == 'all': cm = cm / cm.sum() cm = np.nan_to_num(cm) C = cm t_sum = C.sum(axis=1, dtype=np.float64) p_sum = C.sum(axis=0, dtype=np.float64) n_correct = np.trace(C, dtype=np.float64) n_samples = p_sum.sum() cov_ytyp = n_correct * n_samples - np.dot(t_sum, p_sum) cov_ypyp = n_samples ** 2 - np.dot(p_sum, p_sum) cov_ytyt = n_samples ** 2 - np.dot(t_sum, t_sum) if cov_ypyp * cov_ytyt == 0: return 0.0 else: return cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp)
@validate_params({'y_true': ['array-like'], 'y_pred': ['array-like'], 'sample_weight': ['array-like', None]}) def matthews_corrcoef(y_true, y_pred, *, sample_weight=None): """Compute the Matthews correlation coefficient (MCC). The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] Binary and multiclass labels are supported. Only in the binary case does this relate to information about true and false positives and negatives. See references below. Read more in the :ref:`User Guide <matthews_corrcoef>`. Parameters ---------- y_true : array-like of shape (n_samples,) Ground truth (correct) target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a classifier. sample_weight : array-like of shape (n_samples,), default=None Sample weights. .. versionadded:: 0.18 Returns ------- mcc : float The Matthews correlation coefficient (+1 represents a perfect prediction, 0 an average random prediction and -1 and inverse prediction). References ---------- .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the accuracy of prediction algorithms for classification: an overview. <10.1093/bioinformatics/16.5.412>` .. [2] `Wikipedia entry for the Matthews Correlation Coefficient <https://en.wikipedia.org/wiki/Matthews_correlation_coefficient>`_. .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a K-category correlation coefficient <https://www.sciencedirect.com/science/article/pii/S1476927104000799>`_. .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN Error Measures in MultiClass Prediction <https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0041882>`_. Examples -------- >>> from sklearn.metrics import matthews_corrcoef >>> y_true = [+1, +1, +1, -1] >>> y_pred = [+1, -1, +1, +1] >>> matthews_corrcoef(y_true, y_pred) -0.33... """ <DeepExtract> check_consistent_length(y_true, y_pred) type_true = type_of_target(y_true, input_name='y_true') type_pred = type_of_target(y_pred, input_name='y_pred') y_type = {type_true, type_pred} if y_type == {'binary', 'multiclass'}: y_type = {'multiclass'} if len(y_type) > 1: raise ValueError("Classification metrics can't handle a mix of {0} and {1} targets".format(type_true, type_pred)) y_type = y_type.pop() if y_type not in ['binary', 'multiclass', 'multilabel-indicator']: raise ValueError('{0} is not supported'.format(y_type)) if y_type in ['binary', 'multiclass']: y_true = column_or_1d(y_true) y_pred = column_or_1d(y_pred) if y_type == 'binary': try: unique_values = np.union1d(y_true, y_pred) except TypeError as e: raise TypeError(f'Labels in y_true and y_pred should be of the same type. Got y_true={np.unique(y_true)} and y_pred={np.unique(y_pred)}. Make sure that the predictions provided by the classifier coincides with the true labels.') from e if len(unique_values) > 2: y_type = 'multiclass' if y_type.startswith('multilabel'): y_true = csr_matrix(y_true) y_pred = csr_matrix(y_pred) y_type = 'multilabel-indicator' (y_type, y_true, y_pred) = (y_type, y_true, y_pred) </DeepExtract> check_consistent_length(y_true, y_pred, sample_weight) if y_type not in {'binary', 'multiclass'}: raise ValueError('%s is not supported' % y_type) lb = LabelEncoder() lb.fit(np.hstack([y_true, y_pred])) y_true = lb.transform(y_true) y_pred = lb.transform(y_pred) <DeepExtract> (y_type, y_true, y_pred) = _check_targets(y_true, y_pred) if y_type not in ('binary', 'multiclass'): raise ValueError('%s is not supported' % y_type) if labels is None: labels = unique_labels(y_true, y_pred) else: labels = np.asarray(labels) n_labels = labels.size if n_labels == 0: raise ValueError("'labels' should contains at least one label.") elif y_true.size == 0: C = np.zeros((n_labels, n_labels), dtype=int) elif len(np.intersect1d(y_true, labels)) == 0: raise ValueError('At least one label specified must be in y_true') if sample_weight is None: sample_weight = np.ones(y_true.shape[0], dtype=np.int64) else: sample_weight = np.asarray(sample_weight) check_consistent_length(y_true, y_pred, sample_weight) n_labels = labels.size need_index_conversion = not (labels.dtype.kind in {'i', 'u', 'b'} and np.all(labels == np.arange(n_labels)) and (y_true.min() >= 0) and (y_pred.min() >= 0)) if need_index_conversion: label_to_ind = {y: x for (x, y) in enumerate(labels)} y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred]) y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true]) ind = np.logical_and(y_pred < n_labels, y_true < n_labels) if not np.all(ind): y_pred = y_pred[ind] y_true = y_true[ind] sample_weight = sample_weight[ind] if sample_weight.dtype.kind in {'i', 'u', 'b'}: dtype = np.int64 else: dtype = np.float64 cm = coo_matrix((sample_weight, (y_true, y_pred)), shape=(n_labels, n_labels), dtype=dtype).toarray() with np.errstate(all='ignore'): if normalize == 'true': cm = cm / cm.sum(axis=1, keepdims=True) elif normalize == 'pred': cm = cm / cm.sum(axis=0, keepdims=True) elif normalize == 'all': cm = cm / cm.sum() cm = np.nan_to_num(cm) C = cm </DeepExtract> t_sum = C.sum(axis=1, dtype=np.float64) p_sum = C.sum(axis=0, dtype=np.float64) n_correct = np.trace(C, dtype=np.float64) n_samples = p_sum.sum() cov_ytyp = n_correct * n_samples - np.dot(t_sum, p_sum) cov_ypyp = n_samples ** 2 - np.dot(p_sum, p_sum) cov_ytyt = n_samples ** 2 - np.dot(t_sum, t_sum) if cov_ypyp * cov_ytyt == 0: return 0.0 else: return cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp)
def predict(self, X, check_input=True): """Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. 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 ------- y : array-like of shape (n_samples,) or (n_samples, n_outputs) The predicted classes, or the predict values. """ 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 proba = self.tree_.predict(X) n_samples = X.shape[0] if is_classifier(self): if self.n_outputs_ == 1: return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: class_type = self.classes_[0].dtype predictions = np.zeros((n_samples, self.n_outputs_), dtype=class_type) for k in range(self.n_outputs_): predictions[:, k] = self.classes_[k].take(np.argmax(proba[:, k], axis=1), axis=0) return predictions elif self.n_outputs_ == 1: return proba[:, 0] else: return proba[:, :, 0]
def predict(self, X, check_input=True): """Predict class or regression value for X. For a classification model, the predicted class for each sample in X is returned. For a regression model, the predicted value based on X is returned. 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 ------- y : array-like of shape (n_samples,) or (n_samples, n_outputs) The predicted classes, or the predict values. """ 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> proba = self.tree_.predict(X) n_samples = X.shape[0] if is_classifier(self): if self.n_outputs_ == 1: return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: class_type = self.classes_[0].dtype predictions = np.zeros((n_samples, self.n_outputs_), dtype=class_type) for k in range(self.n_outputs_): predictions[:, k] = self.classes_[k].take(np.argmax(proba[:, k], axis=1), axis=0) return predictions elif self.n_outputs_ == 1: return proba[:, 0] else: return proba[:, :, 0]
def relate_point(X, i, ax): pt_i = X[i] for (j, pt_j) in enumerate(X): diff_embedded = X[i] - X dist_embedded = np.einsum('ij,ij->i', diff_embedded, diff_embedded) dist_embedded[i] = np.inf exp_dist_embedded = np.exp(-dist_embedded - logsumexp(-dist_embedded)) thickness = exp_dist_embedded if i != j: line = ([pt_i[0], pt_j[0]], [pt_i[1], pt_j[1]]) ax.plot(*line, c=cm.Set1(y[j]), linewidth=5 * thickness[j])
def relate_point(X, i, ax): pt_i = X[i] for (j, pt_j) in enumerate(X): <DeepExtract> diff_embedded = X[i] - X dist_embedded = np.einsum('ij,ij->i', diff_embedded, diff_embedded) dist_embedded[i] = np.inf exp_dist_embedded = np.exp(-dist_embedded - logsumexp(-dist_embedded)) thickness = exp_dist_embedded </DeepExtract> if i != j: line = ([pt_i[0], pt_j[0]], [pt_i[1], pt_j[1]]) ax.plot(*line, c=cm.Set1(y[j]), linewidth=5 * thickness[j])
def _partial_roc_auc_score(y_true, y_predict, max_fpr): """Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set. """ def _partial_roc(y_true, y_predict, max_fpr): (fpr, tpr, _) = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fpr = np.append(new_fpr, max_fpr) new_tpr = tpr[fpr <= max_fpr] idx_out = np.argmax(fpr > max_fpr) idx_in = idx_out - 1 x_interp = [fpr[idx_in], fpr[idx_out]] y_interp = [tpr[idx_in], tpr[idx_out]] new_tpr = np.append(new_tpr, np.interp(max_fpr, x_interp, y_interp)) return (new_fpr, new_tpr) (fpr, tpr, _) = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fpr = np.append(new_fpr, max_fpr) new_tpr = tpr[fpr <= max_fpr] idx_out = np.argmax(fpr > max_fpr) idx_in = idx_out - 1 x_interp = [fpr[idx_in], fpr[idx_out]] y_interp = [tpr[idx_in], tpr[idx_out]] new_tpr = np.append(new_tpr, np.interp(max_fpr, x_interp, y_interp)) (new_fpr, new_tpr) = (new_fpr, new_tpr) partial_auc = auc(new_fpr, new_tpr) fpr1 = 0 fpr2 = max_fpr min_area = 0.5 * (fpr2 - fpr1) * (fpr2 + fpr1) max_area = fpr2 - fpr1 return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area))
def _partial_roc_auc_score(y_true, y_predict, max_fpr): """Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set. """ def _partial_roc(y_true, y_predict, max_fpr): (fpr, tpr, _) = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fpr = np.append(new_fpr, max_fpr) new_tpr = tpr[fpr <= max_fpr] idx_out = np.argmax(fpr > max_fpr) idx_in = idx_out - 1 x_interp = [fpr[idx_in], fpr[idx_out]] y_interp = [tpr[idx_in], tpr[idx_out]] new_tpr = np.append(new_tpr, np.interp(max_fpr, x_interp, y_interp)) return (new_fpr, new_tpr) <DeepExtract> (fpr, tpr, _) = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fpr = np.append(new_fpr, max_fpr) new_tpr = tpr[fpr <= max_fpr] idx_out = np.argmax(fpr > max_fpr) idx_in = idx_out - 1 x_interp = [fpr[idx_in], fpr[idx_out]] y_interp = [tpr[idx_in], tpr[idx_out]] new_tpr = np.append(new_tpr, np.interp(max_fpr, x_interp, y_interp)) (new_fpr, new_tpr) = (new_fpr, new_tpr) </DeepExtract> partial_auc = auc(new_fpr, new_tpr) fpr1 = 0 fpr2 = max_fpr min_area = 0.5 * (fpr2 - fpr1) * (fpr2 + fpr1) max_area = fpr2 - fpr1 return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area))
def score(self, X_test, y=None): """Compute the log-likelihood of `X_test` under the estimated Gaussian model. The Gaussian model is defined by its mean and covariance matrix which are represented respectively by `self.location_` and `self.covariance_`. Parameters ---------- X_test : array-like of shape (n_samples, n_features) Test data of which we compute the likelihood, where `n_samples` is the number of samples and `n_features` is the number of features. `X_test` is assumed to be drawn from the same distribution than the data used in fit (including centering). y : Ignored Not used, present for API consistency by convention. Returns ------- res : float The log-likelihood of `X_test` with `self.location_` and `self.covariance_` as estimators of the Gaussian model mean and covariance matrix respectively. """ X_test = self._validate_data(X_test, reset=False) X_test - self.location_ = np.asarray(X_test - self.location_) if X_test - self.location_.ndim == 1: X_test - self.location_ = np.reshape(X_test - self.location_, (1, -1)) if X_test - self.location_.shape[0] == 1: warnings.warn('Only one sample available. You may want to reshape your data array') if True: covariance = np.dot(X_test - self.location_.T, X_test - self.location_) / X_test - self.location_.shape[0] else: covariance = np.cov(X_test - self.location_.T, bias=1) if covariance.ndim == 0: covariance = np.array([[covariance]]) test_cov = covariance p = self.get_precision().shape[0] log_likelihood_ = -np.sum(test_cov * self.get_precision()) + fast_logdet(self.get_precision()) log_likelihood_ -= p * np.log(2 * np.pi) log_likelihood_ /= 2.0 res = log_likelihood_ return res
def score(self, X_test, y=None): """Compute the log-likelihood of `X_test` under the estimated Gaussian model. The Gaussian model is defined by its mean and covariance matrix which are represented respectively by `self.location_` and `self.covariance_`. Parameters ---------- X_test : array-like of shape (n_samples, n_features) Test data of which we compute the likelihood, where `n_samples` is the number of samples and `n_features` is the number of features. `X_test` is assumed to be drawn from the same distribution than the data used in fit (including centering). y : Ignored Not used, present for API consistency by convention. Returns ------- res : float The log-likelihood of `X_test` with `self.location_` and `self.covariance_` as estimators of the Gaussian model mean and covariance matrix respectively. """ X_test = self._validate_data(X_test, reset=False) <DeepExtract> X_test - self.location_ = np.asarray(X_test - self.location_) if X_test - self.location_.ndim == 1: X_test - self.location_ = np.reshape(X_test - self.location_, (1, -1)) if X_test - self.location_.shape[0] == 1: warnings.warn('Only one sample available. You may want to reshape your data array') if True: covariance = np.dot(X_test - self.location_.T, X_test - self.location_) / X_test - self.location_.shape[0] else: covariance = np.cov(X_test - self.location_.T, bias=1) if covariance.ndim == 0: covariance = np.array([[covariance]]) test_cov = covariance </DeepExtract> <DeepExtract> p = self.get_precision().shape[0] log_likelihood_ = -np.sum(test_cov * self.get_precision()) + fast_logdet(self.get_precision()) log_likelihood_ -= p * np.log(2 * np.pi) log_likelihood_ /= 2.0 res = log_likelihood_ </DeepExtract> return res
def rand_score(labels_true, labels_pred): """Rand index. The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings [1]_ [2]_. The raw RI score [3]_ is: RI = (number of agreeing pairs) / (number of pairs) Read more in the :ref:`User Guide <rand_score>`. Parameters ---------- labels_true : array-like of shape (n_samples,), dtype=integral Ground truth class labels to be used as a reference. labels_pred : array-like of shape (n_samples,), dtype=integral Cluster labels to evaluate. Returns ------- RI : float Similarity score between 0.0 and 1.0, inclusive, 1.0 stands for perfect match. See Also -------- adjusted_rand_score: Adjusted Rand Score. adjusted_mutual_info_score: Adjusted Mutual Information. References ---------- .. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions." Journal of Classification 2, 193–218 (1985). <10.1007/BF01908075>`. .. [2] `Wikipedia: Simple Matching Coefficient <https://en.wikipedia.org/wiki/Simple_matching_coefficient>`_ .. [3] `Wikipedia: Rand Index <https://en.wikipedia.org/wiki/Rand_index>`_ Examples -------- Perfectly matching labelings have a score of 1 even >>> from sklearn.metrics.cluster import rand_score >>> rand_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Labelings that assign all classes members to the same clusters are complete but may not always be pure, hence penalized: >>> rand_score([0, 0, 1, 2], [0, 0, 1, 1]) 0.83... """ (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) n_samples = np.int64(labels_true.shape[0]) contingency = contingency_matrix(labels_true, labels_pred, sparse=True, dtype=np.int64) n_c = np.ravel(contingency.sum(axis=1)) n_k = np.ravel(contingency.sum(axis=0)) sum_squares = (contingency.data ** 2).sum() C = np.empty((2, 2), dtype=np.int64) C[1, 1] = sum_squares - n_samples C[0, 1] = contingency.dot(n_k).sum() - sum_squares C[1, 0] = contingency.transpose().dot(n_c).sum() - sum_squares C[0, 0] = n_samples ** 2 - C[0, 1] - C[1, 0] - sum_squares contingency = C numerator = contingency.diagonal().sum() denominator = contingency.sum() if numerator == denominator or denominator == 0: return 1.0 return numerator / denominator
def rand_score(labels_true, labels_pred): """Rand index. The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings [1]_ [2]_. The raw RI score [3]_ is: RI = (number of agreeing pairs) / (number of pairs) Read more in the :ref:`User Guide <rand_score>`. Parameters ---------- labels_true : array-like of shape (n_samples,), dtype=integral Ground truth class labels to be used as a reference. labels_pred : array-like of shape (n_samples,), dtype=integral Cluster labels to evaluate. Returns ------- RI : float Similarity score between 0.0 and 1.0, inclusive, 1.0 stands for perfect match. See Also -------- adjusted_rand_score: Adjusted Rand Score. adjusted_mutual_info_score: Adjusted Mutual Information. References ---------- .. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions." Journal of Classification 2, 193–218 (1985). <10.1007/BF01908075>`. .. [2] `Wikipedia: Simple Matching Coefficient <https://en.wikipedia.org/wiki/Simple_matching_coefficient>`_ .. [3] `Wikipedia: Rand Index <https://en.wikipedia.org/wiki/Rand_index>`_ Examples -------- Perfectly matching labelings have a score of 1 even >>> from sklearn.metrics.cluster import rand_score >>> rand_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0 Labelings that assign all classes members to the same clusters are complete but may not always be pure, hence penalized: >>> rand_score([0, 0, 1, 2], [0, 0, 1, 1]) 0.83... """ <DeepExtract> (labels_true, labels_pred) = check_clusterings(labels_true, labels_pred) n_samples = np.int64(labels_true.shape[0]) contingency = contingency_matrix(labels_true, labels_pred, sparse=True, dtype=np.int64) n_c = np.ravel(contingency.sum(axis=1)) n_k = np.ravel(contingency.sum(axis=0)) sum_squares = (contingency.data ** 2).sum() C = np.empty((2, 2), dtype=np.int64) C[1, 1] = sum_squares - n_samples C[0, 1] = contingency.dot(n_k).sum() - sum_squares C[1, 0] = contingency.transpose().dot(n_c).sum() - sum_squares C[0, 0] = n_samples ** 2 - C[0, 1] - C[1, 0] - sum_squares contingency = C </DeepExtract> numerator = contingency.diagonal().sum() denominator = contingency.sum() if numerator == denominator or denominator == 0: return 1.0 return numerator / denominator
def fit(self, raw_documents, y=None): """Learn a vocabulary dictionary of all tokens in the raw documents. Parameters ---------- raw_documents : iterable An iterable which generates either str, unicode or file objects. y : None This parameter is ignored. Returns ------- self : object Fitted vectorizer. """ return self.fit(raw_documents, y).transform(raw_documents) return self
def fit(self, raw_documents, y=None): """Learn a vocabulary dictionary of all tokens in the raw documents. Parameters ---------- raw_documents : iterable An iterable which generates either str, unicode or file objects. y : None This parameter is ignored. Returns ------- self : object Fitted vectorizer. """ <DeepExtract> return self.fit(raw_documents, y).transform(raw_documents) </DeepExtract> return self
def _solve_eigen_covariance_intercept(self, alpha, y, sqrt_sw, X_mean, eigvals, V, X): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X^T.X (n_samples > n_features and X is sparse), and we are fitting an intercept. """ intercept_sv = np.zeros(V.shape[0]) intercept_sv[-1] = 1 abs_cosine = np.abs(intercept_sv.dot(V)) index = np.argmax(abs_cosine) intercept_dim = index w = 1 / (eigvals + alpha) w[intercept_dim] = 1 / eigvals[intercept_dim] A = (V * w).dot(V.T) X_op = _X_CenterStackOp(X, X_mean, sqrt_sw) AXy = A.dot(X_op.T.dot(y)) y_hat = X_op.dot(AXy) intercept_col = scale = sqrt_sw batch_size = X.shape[1] diag = np.empty(X.shape[0], dtype=X.dtype) for start in range(0, X.shape[0], batch_size): batch = slice(start, min(X.shape[0], start + batch_size), 1) X_batch = np.empty((X[batch].shape[0], X.shape[1] + self.fit_intercept), dtype=X.dtype) if self.fit_intercept: X_batch[:, :-1] = X[batch].A - X_mean * scale[batch][:, None] X_batch[:, -1] = intercept_col[batch] else: X_batch = X[batch].A diag[batch] = (X_batch.dot(A) * X_batch).sum(axis=1) hat_diag = diag if len(y.shape) != 1: hat_diag = hat_diag[:, np.newaxis] return ((1 - hat_diag) / alpha, (y - y_hat) / alpha)
def _solve_eigen_covariance_intercept(self, alpha, y, sqrt_sw, X_mean, eigvals, V, X): """Compute dual coefficients and diagonal of G^-1. Used when we have a decomposition of X^T.X (n_samples > n_features and X is sparse), and we are fitting an intercept. """ intercept_sv = np.zeros(V.shape[0]) intercept_sv[-1] = 1 <DeepExtract> abs_cosine = np.abs(intercept_sv.dot(V)) index = np.argmax(abs_cosine) intercept_dim = index </DeepExtract> w = 1 / (eigvals + alpha) w[intercept_dim] = 1 / eigvals[intercept_dim] A = (V * w).dot(V.T) X_op = _X_CenterStackOp(X, X_mean, sqrt_sw) AXy = A.dot(X_op.T.dot(y)) y_hat = X_op.dot(AXy) <DeepExtract> intercept_col = scale = sqrt_sw batch_size = X.shape[1] diag = np.empty(X.shape[0], dtype=X.dtype) for start in range(0, X.shape[0], batch_size): batch = slice(start, min(X.shape[0], start + batch_size), 1) X_batch = np.empty((X[batch].shape[0], X.shape[1] + self.fit_intercept), dtype=X.dtype) if self.fit_intercept: X_batch[:, :-1] = X[batch].A - X_mean * scale[batch][:, None] X_batch[:, -1] = intercept_col[batch] else: X_batch = X[batch].A diag[batch] = (X_batch.dot(A) * X_batch).sum(axis=1) hat_diag = diag </DeepExtract> if len(y.shape) != 1: hat_diag = hat_diag[:, np.newaxis] return ((1 - hat_diag) / alpha, (y - y_hat) / alpha)
def check_sparse_parameters(tree, dataset): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]['X'] X_sparse = DATASETS[dataset]['X_sparse'] y = DATASETS[dataset]['y'] d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, max_depth=2).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') assert_array_almost_equal(s.predict(X), d.predict(X)) d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).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') assert_array_almost_equal(s.predict(X), d.predict(X)) d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).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') assert_array_almost_equal(s.predict(X), d.predict(X)) d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) s = TreeEstimator(random_state=0, max_leaf_nodes=3).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') assert_array_almost_equal(s.predict(X), d.predict(X))
def check_sparse_parameters(tree, dataset): TreeEstimator = ALL_TREES[tree] X = DATASETS[dataset]['X'] X_sparse = DATASETS[dataset]['X_sparse'] y = DATASETS[dataset]['y'] d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, max_depth=2).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> assert_array_almost_equal(s.predict(X), d.predict(X)) d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y) s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).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> assert_array_almost_equal(s.predict(X), d.predict(X)) d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).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> assert_array_almost_equal(s.predict(X), d.predict(X)) d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) s = TreeEstimator(random_state=0, max_leaf_nodes=3).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> assert_array_almost_equal(s.predict(X), d.predict(X))
def predict(self, X): """ Perform classification on an array of test vectors X. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Returns ------- C : ndarray of shape (n_samples,) Predicted target values for X. """ check_is_fitted(self) return self.classes_[np.argmax(jll, axis=1)]
def predict(self, X): """ Perform classification on an array of test vectors X. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. Returns ------- C : ndarray of shape (n_samples,) Predicted target values for X. """ check_is_fitted(self) <DeepExtract> </DeepExtract> <DeepExtract> </DeepExtract> return self.classes_[np.argmax(jll, axis=1)]
def permutation_test_score(estimator, X, y, *, groups=None, cv=None, n_permutations=100, n_jobs=None, random_state=0, verbose=0, scoring=None, fit_params=None): """Evaluate the significance of a cross-validated score with permutations. Permutes targets to generate 'randomized data' and compute the empirical p-value against the null hypothesis that features and targets are independent. The p-value represents the fraction of randomized data sets where the estimator performed as well or better than in the original data. A small p-value suggests that there is a real dependency between features and targets which has been used by the estimator to give good predictions. A large p-value may be due to lack of real dependency between features and targets or the estimator was not able to use the dependency to give good predictions. Read more in the :ref:`User Guide <permutation_test_score>`. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape at least 2D 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. groups : array-like of shape (n_samples,), default=None Labels to constrain permutation within groups, i.e. ``y`` values are permuted among samples with the same group identifier. When not specified, ``y`` values are permuted among all samples. When a grouped cross-validator is used, the group labels are also passed on to the ``split`` method of the cross-validator. The cross-validator uses them for grouping the samples while splitting the dataset into train/test set. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - `None`, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For `int`/`None` inputs, if the estimator is a classifier and `y` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 `cv` default value if `None` changed from 3-fold to 5-fold. n_permutations : int, default=100 Number of times to permute ``y``. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the cross-validated score are parallelized over the permutations. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=0 Pass an int for reproducible output for permutation of ``y`` values among samples. See :term:`Glossary <random_state>`. verbose : int, default=0 The verbosity level. scoring : str or callable, default=None A single str (see :ref:`scoring_parameter`) or a callable (see :ref:`scoring`) to evaluate the predictions on the test set. If `None` the estimator's score method is used. fit_params : dict, default=None Parameters to pass to the fit method of the estimator. .. versionadded:: 0.24 Returns ------- score : float The true score without permuting targets. permutation_scores : array of shape (n_permutations,) The scores obtained for each permutations. pvalue : float The p-value, which approximates the probability that the score would be obtained by chance. This is calculated as: `(C + 1) / (n_permutations + 1)` Where C is the number of permutations whose score >= the true score. The best possible p-value is 1/(n_permutations + 1), the worst is 1.0. Notes ----- This function implements Test 1 in: Ojala and Garriga. `Permutation Tests for Studying Classifier Performance <http://www.jmlr.org/papers/volume11/ojala10a/ojala10a.pdf>`_. The Journal of Machine Learning Research (2010) vol. 11 """ (X, y, groups) = indexable(X, y, groups) cv = check_cv(cv, y, classifier=is_classifier(estimator)) scorer = check_scoring(estimator, scoring=scoring) random_state = check_random_state(random_state) fit_params = fit_params if fit_params is not None else {} avg_score = [] for (train, test) in cv.split(X, y, groups): (X_train, y_train) = _safe_split(clone(estimator), X, y, train) (X_test, y_test) = _safe_split(clone(estimator), X, y, test, train) fit_params = _check_fit_params(X, fit_params, train) clone(estimator).fit(X_train, y_train, **fit_params) avg_score.append(scorer(clone(estimator), X_test, y_test)) score = np.mean(avg_score) permutation_scores = Parallel(n_jobs=n_jobs, verbose=verbose)((delayed(_permutation_test_score)(clone(estimator), X, _shuffle(y, groups, random_state), groups, cv, scorer, fit_params=fit_params) for _ in range(n_permutations))) permutation_scores = np.array(permutation_scores) pvalue = (np.sum(permutation_scores >= score) + 1.0) / (n_permutations + 1) return (score, permutation_scores, pvalue)
def permutation_test_score(estimator, X, y, *, groups=None, cv=None, n_permutations=100, n_jobs=None, random_state=0, verbose=0, scoring=None, fit_params=None): """Evaluate the significance of a cross-validated score with permutations. Permutes targets to generate 'randomized data' and compute the empirical p-value against the null hypothesis that features and targets are independent. The p-value represents the fraction of randomized data sets where the estimator performed as well or better than in the original data. A small p-value suggests that there is a real dependency between features and targets which has been used by the estimator to give good predictions. A large p-value may be due to lack of real dependency between features and targets or the estimator was not able to use the dependency to give good predictions. Read more in the :ref:`User Guide <permutation_test_score>`. Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. X : array-like of shape at least 2D 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. groups : array-like of shape (n_samples,), default=None Labels to constrain permutation within groups, i.e. ``y`` values are permuted among samples with the same group identifier. When not specified, ``y`` values are permuted among all samples. When a grouped cross-validator is used, the group labels are also passed on to the ``split`` method of the cross-validator. The cross-validator uses them for grouping the samples while splitting the dataset into train/test set. cv : int, cross-validation generator or an iterable, default=None Determines the cross-validation splitting strategy. Possible inputs for cv are: - `None`, to use the default 5-fold cross validation, - int, to specify the number of folds in a `(Stratified)KFold`, - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For `int`/`None` inputs, if the estimator is a classifier and `y` is either binary or multiclass, :class:`StratifiedKFold` is used. In all other cases, :class:`KFold` is used. These splitters are instantiated with `shuffle=False` so the splits will be the same across calls. Refer :ref:`User Guide <cross_validation>` for the various cross-validation strategies that can be used here. .. versionchanged:: 0.22 `cv` default value if `None` changed from 3-fold to 5-fold. n_permutations : int, default=100 Number of times to permute ``y``. n_jobs : int, default=None Number of jobs to run in parallel. Training the estimator and computing the cross-validated score are parallelized over the permutations. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=0 Pass an int for reproducible output for permutation of ``y`` values among samples. See :term:`Glossary <random_state>`. verbose : int, default=0 The verbosity level. scoring : str or callable, default=None A single str (see :ref:`scoring_parameter`) or a callable (see :ref:`scoring`) to evaluate the predictions on the test set. If `None` the estimator's score method is used. fit_params : dict, default=None Parameters to pass to the fit method of the estimator. .. versionadded:: 0.24 Returns ------- score : float The true score without permuting targets. permutation_scores : array of shape (n_permutations,) The scores obtained for each permutations. pvalue : float The p-value, which approximates the probability that the score would be obtained by chance. This is calculated as: `(C + 1) / (n_permutations + 1)` Where C is the number of permutations whose score >= the true score. The best possible p-value is 1/(n_permutations + 1), the worst is 1.0. Notes ----- This function implements Test 1 in: Ojala and Garriga. `Permutation Tests for Studying Classifier Performance <http://www.jmlr.org/papers/volume11/ojala10a/ojala10a.pdf>`_. The Journal of Machine Learning Research (2010) vol. 11 """ (X, y, groups) = indexable(X, y, groups) cv = check_cv(cv, y, classifier=is_classifier(estimator)) scorer = check_scoring(estimator, scoring=scoring) random_state = check_random_state(random_state) <DeepExtract> fit_params = fit_params if fit_params is not None else {} avg_score = [] for (train, test) in cv.split(X, y, groups): (X_train, y_train) = _safe_split(clone(estimator), X, y, train) (X_test, y_test) = _safe_split(clone(estimator), X, y, test, train) fit_params = _check_fit_params(X, fit_params, train) clone(estimator).fit(X_train, y_train, **fit_params) avg_score.append(scorer(clone(estimator), X_test, y_test)) score = np.mean(avg_score) </DeepExtract> permutation_scores = Parallel(n_jobs=n_jobs, verbose=verbose)((delayed(_permutation_test_score)(clone(estimator), X, _shuffle(y, groups, random_state), groups, cv, scorer, fit_params=fit_params) for _ in range(n_permutations))) permutation_scores = np.array(permutation_scores) pvalue = (np.sum(permutation_scores >= score) + 1.0) / (n_permutations + 1) return (score, permutation_scores, pvalue)
def test_precision_recall_f1_score_binary(): 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) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if True: 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) (p, r, f, s) = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.73, 0.85], 2) assert_array_almost_equal(r, [0.88, 0.68], 2) assert_array_almost_equal(f, [0.8, 0.76], 2) assert_array_equal(s, [25, 25]) for (kwargs, my_assert) in [({}, assert_no_warnings), ({'average': 'binary'}, assert_no_warnings)]: ps = my_assert(precision_score, y_true, y_pred, **kwargs) assert_array_almost_equal(ps, 0.85, 2) rs = my_assert(recall_score, y_true, y_pred, **kwargs) assert_array_almost_equal(rs, 0.68, 2) fs = my_assert(f1_score, y_true, y_pred, **kwargs) assert_array_almost_equal(fs, 0.76, 2) assert_almost_equal(my_assert(fbeta_score, y_true, y_pred, beta=2, **kwargs), (1 + 2 ** 2) * ps * rs / (2 ** 2 * ps + rs), 2)
def test_precision_recall_f1_score_binary(): <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) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) if True: 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> (p, r, f, s) = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.73, 0.85], 2) assert_array_almost_equal(r, [0.88, 0.68], 2) assert_array_almost_equal(f, [0.8, 0.76], 2) assert_array_equal(s, [25, 25]) for (kwargs, my_assert) in [({}, assert_no_warnings), ({'average': 'binary'}, assert_no_warnings)]: ps = my_assert(precision_score, y_true, y_pred, **kwargs) assert_array_almost_equal(ps, 0.85, 2) rs = my_assert(recall_score, y_true, y_pred, **kwargs) assert_array_almost_equal(rs, 0.68, 2) fs = my_assert(f1_score, y_true, y_pred, **kwargs) assert_array_almost_equal(fs, 0.76, 2) assert_almost_equal(my_assert(fbeta_score, y_true, y_pred, beta=2, **kwargs), (1 + 2 ** 2) * ps * rs / (2 ** 2 * ps + rs), 2)
def test_ovr_binary(): X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) y = ['eggs', 'spam', 'spam', 'eggs', 'spam'] Y = np.array([[0, 1, 1, 0, 1]]).T classes = set('eggs spam'.split()) def conduct_test(base_clf, test_predict_proba=False): clf = OneVsRestClassifier(base_clf).fit(X, y) assert set(clf.classes_) == classes y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_array_equal(y_pred, ['eggs']) if hasattr(base_clf, 'decision_function'): dec = clf.decision_function(X) assert dec.shape == (5,) if test_predict_proba: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert 2 == len(probabilities[0]) assert clf.classes_[np.argmax(probabilities, axis=1)] == clf.predict(X_test) clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert y_pred == 1 for base_clf in (LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet()): clf = OneVsRestClassifier(base_clf).fit(X, y) assert set(clf.classes_) == classes y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_array_equal(y_pred, ['eggs']) if hasattr(base_clf, 'decision_function'): dec = clf.decision_function(X) assert dec.shape == (5,) if test_predict_proba: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert 2 == len(probabilities[0]) assert clf.classes_[np.argmax(probabilities, axis=1)] == clf.predict(X_test) clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert y_pred == 1 for base_clf in (MultinomialNB(), SVC(probability=True), LogisticRegression()): clf = OneVsRestClassifier(base_clf).fit(X, y) assert set(clf.classes_) == classes y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_array_equal(y_pred, ['eggs']) if hasattr(base_clf, 'decision_function'): dec = clf.decision_function(X) assert dec.shape == (5,) if True: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert 2 == len(probabilities[0]) assert clf.classes_[np.argmax(probabilities, axis=1)] == clf.predict(X_test) clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert y_pred == 1 </DeepExtract>
def test_ovr_binary(): X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]]) y = ['eggs', 'spam', 'spam', 'eggs', 'spam'] Y = np.array([[0, 1, 1, 0, 1]]).T classes = set('eggs spam'.split()) def conduct_test(base_clf, test_predict_proba=False): clf = OneVsRestClassifier(base_clf).fit(X, y) assert set(clf.classes_) == classes y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_array_equal(y_pred, ['eggs']) if hasattr(base_clf, 'decision_function'): dec = clf.decision_function(X) assert dec.shape == (5,) if test_predict_proba: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert 2 == len(probabilities[0]) assert clf.classes_[np.argmax(probabilities, axis=1)] == clf.predict(X_test) clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert y_pred == 1 for base_clf in (LinearSVC(random_state=0), LinearRegression(), Ridge(), ElasticNet()): <DeepExtract> clf = OneVsRestClassifier(base_clf).fit(X, y) assert set(clf.classes_) == classes y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_array_equal(y_pred, ['eggs']) if hasattr(base_clf, 'decision_function'): dec = clf.decision_function(X) assert dec.shape == (5,) if test_predict_proba: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert 2 == len(probabilities[0]) assert clf.classes_[np.argmax(probabilities, axis=1)] == clf.predict(X_test) clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert y_pred == 1 </DeepExtract> for base_clf in (MultinomialNB(), SVC(probability=True), LogisticRegression()): <DeepExtract> clf = OneVsRestClassifier(base_clf).fit(X, y) assert set(clf.classes_) == classes y_pred = clf.predict(np.array([[0, 0, 4]]))[0] assert_array_equal(y_pred, ['eggs']) if hasattr(base_clf, 'decision_function'): dec = clf.decision_function(X) assert dec.shape == (5,) if True: X_test = np.array([[0, 0, 4]]) probabilities = clf.predict_proba(X_test) assert 2 == len(probabilities[0]) assert clf.classes_[np.argmax(probabilities, axis=1)] == clf.predict(X_test) clf = OneVsRestClassifier(base_clf).fit(X, Y) y_pred = clf.predict([[3, 0, 0]])[0] assert y_pred == 1 </DeepExtract>
def ricker_matrix(width, resolution, n_components): """Dictionary of Ricker (Mexican hat) wavelets""" centers = np.linspace(0, resolution - 1, n_components) D = np.empty((n_components, resolution)) for (i, center) in enumerate(centers): x = np.linspace(0, resolution - 1, resolution) x = 2 / (np.sqrt(3 * width) * np.pi ** 0.25) * (1 - (x - center) ** 2 / width ** 2) * np.exp(-(x - center) ** 2 / (2 * width ** 2)) D[i] = x D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis] return D
def ricker_matrix(width, resolution, n_components): """Dictionary of Ricker (Mexican hat) wavelets""" centers = np.linspace(0, resolution - 1, n_components) D = np.empty((n_components, resolution)) for (i, center) in enumerate(centers): <DeepExtract> x = np.linspace(0, resolution - 1, resolution) x = 2 / (np.sqrt(3 * width) * np.pi ** 0.25) * (1 - (x - center) ** 2 / width ** 2) * np.exp(-(x - center) ** 2 / (2 * width ** 2)) D[i] = x </DeepExtract> D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis] return D
def estimator_html_repr(estimator): """Build a HTML representation of an estimator. Read more in the :ref:`User Guide <visualizing_composite_estimators>`. Parameters ---------- estimator : estimator object The estimator to visualize. Returns ------- html: str HTML representation of estimator. """ with closing(StringIO()) as out: container_id = _CONTAINER_ID_COUNTER.get_id() style_template = Template(_STYLE) style_with_id = style_template.substitute(id=container_id) estimator_str = str(estimator) fallback_msg = 'In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.' out.write(f'<style>{style_with_id}</style><div id="{container_id}" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>{html.escape(estimator_str)}</pre><b>{fallback_msg}</b></div><div class="sk-container" hidden>') if True: est_block = _get_visual_block(estimator) else: with config_context(print_changed_only=True): est_block = _get_visual_block(estimator) if est_block.kind in ('serial', 'parallel'): dashed_wrapped = True or est_block.dash_wrapped dash_cls = ' sk-dashed-wrapped' if dashed_wrapped else '' out.write(f'<div class="sk-item{dash_cls}">') if estimator.__class__.__name__: _write_label_html(out, estimator.__class__.__name__, estimator_str) kind = est_block.kind out.write(f'<div class="sk-{kind}">') est_infos = zip(est_block.estimators, est_block.names, est_block.name_details) for (est, name, name_details) in est_infos: if kind == 'serial': _write_estimator_html(out, est, name, name_details) else: out.write('<div class="sk-parallel-item">') serial_block = _VisualBlock('serial', [est], dash_wrapped=False) _write_estimator_html(out, serial_block, name, name_details) out.write('</div>') out.write('</div></div>') elif est_block.kind == 'single': _write_label_html(out, est_block.names, est_block.name_details, outer_class='sk-item', inner_class='sk-estimator', checked=True) out.write('</div></div>') html_output = out.getvalue() return html_output
def estimator_html_repr(estimator): """Build a HTML representation of an estimator. Read more in the :ref:`User Guide <visualizing_composite_estimators>`. Parameters ---------- estimator : estimator object The estimator to visualize. Returns ------- html: str HTML representation of estimator. """ with closing(StringIO()) as out: container_id = _CONTAINER_ID_COUNTER.get_id() style_template = Template(_STYLE) style_with_id = style_template.substitute(id=container_id) estimator_str = str(estimator) fallback_msg = 'In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.' out.write(f'<style>{style_with_id}</style><div id="{container_id}" class="sk-top-container"><div class="sk-text-repr-fallback"><pre>{html.escape(estimator_str)}</pre><b>{fallback_msg}</b></div><div class="sk-container" hidden>') <DeepExtract> if True: est_block = _get_visual_block(estimator) else: with config_context(print_changed_only=True): est_block = _get_visual_block(estimator) if est_block.kind in ('serial', 'parallel'): dashed_wrapped = True or est_block.dash_wrapped dash_cls = ' sk-dashed-wrapped' if dashed_wrapped else '' out.write(f'<div class="sk-item{dash_cls}">') if estimator.__class__.__name__: _write_label_html(out, estimator.__class__.__name__, estimator_str) kind = est_block.kind out.write(f'<div class="sk-{kind}">') est_infos = zip(est_block.estimators, est_block.names, est_block.name_details) for (est, name, name_details) in est_infos: if kind == 'serial': _write_estimator_html(out, est, name, name_details) else: out.write('<div class="sk-parallel-item">') serial_block = _VisualBlock('serial', [est], dash_wrapped=False) _write_estimator_html(out, serial_block, name, name_details) out.write('</div>') out.write('</div></div>') elif est_block.kind == 'single': _write_label_html(out, est_block.names, est_block.name_details, outer_class='sk-item', inner_class='sk-estimator', checked=True) </DeepExtract> out.write('</div></div>') html_output = out.getvalue() return html_output
def test_numerical_stability_large_gradient(): _update_kwargs(kwargs) model = linear_model.SGDClassifier(**kwargs) with np.errstate(all='raise'): model.fit(iris.data, iris.target) assert np.isfinite(model.coef_).all()
def test_numerical_stability_large_gradient(): <DeepExtract> _update_kwargs(kwargs) model = linear_model.SGDClassifier(**kwargs) </DeepExtract> with np.errstate(all='raise'): model.fit(iris.data, iris.target) assert np.isfinite(model.coef_).all()
def recursively_check_children_node_values(node, right_sibling=None): if node.is_leaf: return if right_sibling is not None: middle = (node.value + right_sibling.value) / 2 if monotonic_cst == MonotonicConstraint.POS: assert node.left_child.value <= node.right_child.value <= middle if not right_sibling.is_leaf: assert middle <= right_sibling.left_child.value <= right_sibling.right_child.value else: assert node.left_child.value >= node.right_child.value >= middle if not right_sibling.is_leaf: assert middle >= right_sibling.left_child.value >= right_sibling.right_child.value if node.left_child.is_leaf: return if node.right_child is not None: middle = (node.left_child.value + node.right_child.value) / 2 if monotonic_cst == MonotonicConstraint.POS: assert node.left_child.left_child.value <= node.left_child.right_child.value <= middle if not node.right_child.is_leaf: assert middle <= node.right_child.left_child.value <= node.right_child.right_child.value else: assert node.left_child.left_child.value >= node.left_child.right_child.value >= middle if not node.right_child.is_leaf: assert middle >= node.right_child.left_child.value >= node.right_child.right_child.value recursively_check_children_node_values(node.left_child.left_child, right_sibling=node.left_child.right_child) recursively_check_children_node_values(node.left_child.right_child) if node.right_child.is_leaf: return if right_sibling is not None: middle = (node.right_child.value + right_sibling.value) / 2 if monotonic_cst == MonotonicConstraint.POS: assert node.right_child.left_child.value <= node.right_child.right_child.value <= middle if not right_sibling.is_leaf: assert middle <= right_sibling.left_child.value <= right_sibling.right_child.value else: assert node.right_child.left_child.value >= node.right_child.right_child.value >= middle if not right_sibling.is_leaf: assert middle >= right_sibling.left_child.value >= right_sibling.right_child.value recursively_check_children_node_values(node.right_child.left_child, right_sibling=node.right_child.right_child) recursively_check_children_node_values(node.right_child.right_child) </DeepExtract>
def recursively_check_children_node_values(node, right_sibling=None): if node.is_leaf: return if right_sibling is not None: middle = (node.value + right_sibling.value) / 2 if monotonic_cst == MonotonicConstraint.POS: assert node.left_child.value <= node.right_child.value <= middle if not right_sibling.is_leaf: assert middle <= right_sibling.left_child.value <= right_sibling.right_child.value else: assert node.left_child.value >= node.right_child.value >= middle if not right_sibling.is_leaf: assert middle >= right_sibling.left_child.value >= right_sibling.right_child.value <DeepExtract> if node.left_child.is_leaf: return if node.right_child is not None: middle = (node.left_child.value + node.right_child.value) / 2 if monotonic_cst == MonotonicConstraint.POS: assert node.left_child.left_child.value <= node.left_child.right_child.value <= middle if not node.right_child.is_leaf: assert middle <= node.right_child.left_child.value <= node.right_child.right_child.value else: assert node.left_child.left_child.value >= node.left_child.right_child.value >= middle if not node.right_child.is_leaf: assert middle >= node.right_child.left_child.value >= node.right_child.right_child.value recursively_check_children_node_values(node.left_child.left_child, right_sibling=node.left_child.right_child) recursively_check_children_node_values(node.left_child.right_child) </DeepExtract> <DeepExtract> if node.right_child.is_leaf: return if right_sibling is not None: middle = (node.right_child.value + right_sibling.value) / 2 if monotonic_cst == MonotonicConstraint.POS: assert node.right_child.left_child.value <= node.right_child.right_child.value <= middle if not right_sibling.is_leaf: assert middle <= right_sibling.left_child.value <= right_sibling.right_child.value else: assert node.right_child.left_child.value >= node.right_child.right_child.value >= middle if not right_sibling.is_leaf: assert middle >= right_sibling.left_child.value >= right_sibling.right_child.value recursively_check_children_node_values(node.right_child.left_child, right_sibling=node.right_child.right_child) recursively_check_children_node_values(node.right_child.right_child) </DeepExtract>
def fixed_batch_size_comparison(data): all_features = [i.astype(int) for i in np.linspace(data.shape[1] // 10, data.shape[1], num=5)] batch_size = 1000 all_times = defaultdict(list) all_errors = defaultdict(list) for n_components in all_features: pca = PCA(n_components=n_components) ipca = IncrementalPCA(n_components=n_components, batch_size=batch_size) results_dict = {k: benchmark(est, data) for (k, est) in [('pca', pca), ('ipca', ipca)]} for k in sorted(results_dict.keys()): all_times[k].append(results_dict[k]['time']) all_errors[k].append(results_dict[k]['error']) plt.figure() plot_results(all_features, all_times['pca'], label='PCA') plot_results(all_features, all_times['ipca'], label='IncrementalPCA, bsize=%i' % batch_size) plt.legend(loc='upper left') plt.suptitle('Algorithm runtime vs. n_components\n LFW, size %i x %i' % data.shape) plt.xlabel('Number of components (out of max %i)' % data.shape[1]) plt.ylabel('Time (seconds)') plt.figure() plot_results(all_features, all_errors['pca'], label='PCA') plot_results(all_features, all_errors['ipca'], label='IncrementalPCA, bsize=%i' % batch_size) plt.legend(loc='lower left') plt.suptitle('Algorithm error vs. n_components\nLFW, size %i x %i' % data.shape) plt.xlabel('Number of components (out of max %i)' % data.shape[1]) plt.ylabel('Mean absolute error') </DeepExtract>
def fixed_batch_size_comparison(data): all_features = [i.astype(int) for i in np.linspace(data.shape[1] // 10, data.shape[1], num=5)] batch_size = 1000 all_times = defaultdict(list) all_errors = defaultdict(list) for n_components in all_features: pca = PCA(n_components=n_components) ipca = IncrementalPCA(n_components=n_components, batch_size=batch_size) results_dict = {k: benchmark(est, data) for (k, est) in [('pca', pca), ('ipca', ipca)]} for k in sorted(results_dict.keys()): all_times[k].append(results_dict[k]['time']) all_errors[k].append(results_dict[k]['error']) <DeepExtract> plt.figure() plot_results(all_features, all_times['pca'], label='PCA') plot_results(all_features, all_times['ipca'], label='IncrementalPCA, bsize=%i' % batch_size) plt.legend(loc='upper left') plt.suptitle('Algorithm runtime vs. n_components\n LFW, size %i x %i' % data.shape) plt.xlabel('Number of components (out of max %i)' % data.shape[1]) plt.ylabel('Time (seconds)') </DeepExtract> <DeepExtract> plt.figure() plot_results(all_features, all_errors['pca'], label='PCA') plot_results(all_features, all_errors['ipca'], label='IncrementalPCA, bsize=%i' % batch_size) plt.legend(loc='lower left') plt.suptitle('Algorithm error vs. n_components\nLFW, size %i x %i' % data.shape) plt.xlabel('Number of components (out of max %i)' % data.shape[1]) plt.ylabel('Mean absolute error') </DeepExtract>
def _predict(self, X, check_input=True): """Private predict method with optional input validation""" if check_input: X = self._validate_data(X, accept_sparse=['csr', 'csc'], reset=False) activation = X hidden_activation = ACTIVATIONS[self.activation] for i in range(self.n_layers_ - 1): activation = safe_sparse_dot(activation, self.coefs_[i]) activation += self.intercepts_[i] if i != self.n_layers_ - 2: hidden_activation(activation) output_activation = ACTIVATIONS[self.out_activation_] output_activation(activation) y_pred = activation if self.n_outputs_ == 1: y_pred = y_pred.ravel() return self._label_binarizer.inverse_transform(y_pred)
def _predict(self, X, check_input=True): """Private predict method with optional input validation""" <DeepExtract> if check_input: X = self._validate_data(X, accept_sparse=['csr', 'csc'], reset=False) activation = X hidden_activation = ACTIVATIONS[self.activation] for i in range(self.n_layers_ - 1): activation = safe_sparse_dot(activation, self.coefs_[i]) activation += self.intercepts_[i] if i != self.n_layers_ - 2: hidden_activation(activation) output_activation = ACTIVATIONS[self.out_activation_] output_activation(activation) y_pred = activation </DeepExtract> if self.n_outputs_ == 1: y_pred = y_pred.ravel() return self._label_binarizer.inverse_transform(y_pred)
def test_cross_val_predict_class_subset(): X = np.arange(200).reshape(100, 2) y = np.array([x // 10 for x in range(100)]) classes = 10 kfold3 = KFold(n_splits=3) kfold4 = KFold(n_splits=4) le = LabelEncoder() methods = ['decision_function', 'predict_proba', 'predict_log_proba'] for method in methods: est = LogisticRegression(solver='liblinear') predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for (train, test) in kfold3.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) if method == 'predict_proba': exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full((len(test), classes), np.finfo(expected_predictions.dtype).min) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test expected_predictions = expected_predictions assert_array_almost_equal(expected_predictions, predictions) predictions = cross_val_predict(est, X, y, method=method, cv=kfold4) expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for (train, test) in kfold4.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) if method == 'predict_proba': exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full((len(test), classes), np.finfo(expected_predictions.dtype).min) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test expected_predictions = expected_predictions assert_array_almost_equal(expected_predictions, predictions) y = shuffle(np.repeat(range(10), 10), random_state=0) predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) y = le.fit_transform(y) expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for (train, test) in kfold3.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) if method == 'predict_proba': exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full((len(test), classes), np.finfo(expected_predictions.dtype).min) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test expected_predictions = expected_predictions assert_array_almost_equal(expected_predictions, predictions)
def test_cross_val_predict_class_subset(): X = np.arange(200).reshape(100, 2) y = np.array([x // 10 for x in range(100)]) classes = 10 kfold3 = KFold(n_splits=3) kfold4 = KFold(n_splits=4) le = LabelEncoder() methods = ['decision_function', 'predict_proba', 'predict_log_proba'] for method in methods: est = LogisticRegression(solver='liblinear') predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) <DeepExtract> expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for (train, test) in kfold3.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) if method == 'predict_proba': exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full((len(test), classes), np.finfo(expected_predictions.dtype).min) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test expected_predictions = expected_predictions </DeepExtract> assert_array_almost_equal(expected_predictions, predictions) predictions = cross_val_predict(est, X, y, method=method, cv=kfold4) <DeepExtract> expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for (train, test) in kfold4.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) if method == 'predict_proba': exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full((len(test), classes), np.finfo(expected_predictions.dtype).min) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test expected_predictions = expected_predictions </DeepExtract> assert_array_almost_equal(expected_predictions, predictions) y = shuffle(np.repeat(range(10), 10), random_state=0) predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) y = le.fit_transform(y) <DeepExtract> expected_predictions = np.zeros([len(y), classes]) func = getattr(est, method) for (train, test) in kfold3.split(X, y): est.fit(X[train], y[train]) expected_predictions_ = func(X[test]) if method == 'predict_proba': exp_pred_test = np.zeros((len(test), classes)) else: exp_pred_test = np.full((len(test), classes), np.finfo(expected_predictions.dtype).min) exp_pred_test[:, est.classes_] = expected_predictions_ expected_predictions[test] = exp_pred_test expected_predictions = expected_predictions </DeepExtract> assert_array_almost_equal(expected_predictions, predictions)
def get_file_size(version): api_url = ROOT_URL + '%s/_downloads' % version for path_details in json_urlread(api_url): if 'dev' in version: file_extension = 'zip' current_version = parse_version(version) min_zip_version = parse_version('0.24') file_extension = 'zip' if current_version >= min_zip_version else 'pdf' file_path = f'scikit-learn-docs.{file_extension}' if path_details['name'] == file_path: return human_readable_data_quantity(path_details['size'], 1000)
def get_file_size(version): api_url = ROOT_URL + '%s/_downloads' % version for path_details in json_urlread(api_url): <DeepExtract> if 'dev' in version: file_extension = 'zip' current_version = parse_version(version) min_zip_version = parse_version('0.24') file_extension = 'zip' if current_version >= min_zip_version else 'pdf' </DeepExtract> file_path = f'scikit-learn-docs.{file_extension}' if path_details['name'] == file_path: return human_readable_data_quantity(path_details['size'], 1000)
def fit(self, X, y=None): """Fit the clustering from features, or affinity matrix. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples) Training instances to cluster, or similarities / affinities between instances if ``affinity='precomputed'``. If a sparse feature matrix is provided, it will be converted into a sparse ``csr_matrix``. y : Ignored Not used, present here for API consistency by convention. Returns ------- self Returns the instance itself. """ self._validate_params() if self.affinity == 'precomputed': accept_sparse = False else: accept_sparse = 'csr' X = self._validate_data(X, accept_sparse=accept_sparse) if self.affinity == 'precomputed': self.affinity_matrix_ = X.copy() if self.copy else X else: self.affinity_matrix_ = -euclidean_distances(X, squared=True) if self.affinity_matrix_.shape[0] != self.affinity_matrix_.shape[1]: raise ValueError(f'The matrix of similarities must be a square array. Got {self.affinity_matrix_.shape} instead.') if self.preference is None: preference = np.median(self.affinity_matrix_) else: preference = self.preference preference = np.array(preference, copy=False) random_state = check_random_state(self.random_state) n_samples = self.affinity_matrix_.shape[0] if n_samples == 1 or _equal_similarities_and_preferences(self.affinity_matrix_, preference): warnings.warn('All samples have mutually equal similarities. Returning arbitrary cluster center(s).') if preference.flat[0] >= self.affinity_matrix_.flat[n_samples - 1]: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (np.arange(n_samples), np.arange(n_samples), 0) if True else (np.arange(n_samples), np.arange(n_samples)) else: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (np.array([0]), np.array([0] * n_samples), 0) if True else (np.array([0]), np.array([0] * n_samples)) self.affinity_matrix_.flat[::n_samples + 1] = preference A = np.zeros((n_samples, n_samples)) R = np.zeros((n_samples, n_samples)) tmp = np.zeros((n_samples, n_samples)) self.affinity_matrix_ += (np.finfo(self.affinity_matrix_.dtype).eps * self.affinity_matrix_ + np.finfo(self.affinity_matrix_.dtype).tiny * 100) * random_state.standard_normal(size=(n_samples, n_samples)) e = np.zeros((n_samples, self.convergence_iter)) ind = np.arange(n_samples) for it in range(self.max_iter): np.add(A, self.affinity_matrix_, tmp) I = np.argmax(tmp, axis=1) Y = tmp[ind, I] tmp[ind, I] = -np.inf Y2 = np.max(tmp, axis=1) np.subtract(self.affinity_matrix_, Y[:, None], tmp) tmp[ind, I] = self.affinity_matrix_[ind, I] - Y2 tmp *= 1 - self.damping R *= self.damping R += tmp np.maximum(R, 0, tmp) tmp.flat[::n_samples + 1] = R.flat[::n_samples + 1] tmp -= np.sum(tmp, axis=0) dA = np.diag(tmp).copy() tmp.clip(0, np.inf, tmp) tmp.flat[::n_samples + 1] = dA tmp *= 1 - self.damping A *= self.damping A -= tmp E = np.diag(A) + np.diag(R) > 0 e[:, it % self.convergence_iter] = E K = np.sum(E, axis=0) if it >= self.convergence_iter: se = np.sum(e, axis=1) unconverged = np.sum((se == self.convergence_iter) + (se == 0)) != n_samples if not unconverged and K > 0 or it == self.max_iter: never_converged = False if self.verbose: print('Converged after %d iterations.' % it) break else: never_converged = True if self.verbose: print('Did not converge') I = np.flatnonzero(E) K = I.size if K > 0: if never_converged: warnings.warn('Affinity propagation did not converge, this model may return degenerate cluster centers and labels.', ConvergenceWarning) c = np.argmax(self.affinity_matrix_[:, I], axis=1) c[I] = np.arange(K) for k in range(K): ii = np.where(c == k)[0] j = np.argmax(np.sum(self.affinity_matrix_[ii[:, np.newaxis], ii], axis=0)) I[k] = ii[j] c = np.argmax(self.affinity_matrix_[:, I], axis=1) c[I] = np.arange(K) labels = I[c] cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) else: warnings.warn('Affinity propagation did not converge and this model will not have any cluster centers.', ConvergenceWarning) labels = np.array([-1] * n_samples) cluster_centers_indices = [] if True: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (cluster_centers_indices, labels, it + 1) else: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (cluster_centers_indices, labels) if self.affinity != 'precomputed': self.cluster_centers_ = X[self.cluster_centers_indices_].copy() return self
def fit(self, X, y=None): """Fit the clustering from features, or affinity matrix. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features), or array-like of shape (n_samples, n_samples) Training instances to cluster, or similarities / affinities between instances if ``affinity='precomputed'``. If a sparse feature matrix is provided, it will be converted into a sparse ``csr_matrix``. y : Ignored Not used, present here for API consistency by convention. Returns ------- self Returns the instance itself. """ self._validate_params() if self.affinity == 'precomputed': accept_sparse = False else: accept_sparse = 'csr' X = self._validate_data(X, accept_sparse=accept_sparse) if self.affinity == 'precomputed': self.affinity_matrix_ = X.copy() if self.copy else X else: self.affinity_matrix_ = -euclidean_distances(X, squared=True) if self.affinity_matrix_.shape[0] != self.affinity_matrix_.shape[1]: raise ValueError(f'The matrix of similarities must be a square array. Got {self.affinity_matrix_.shape} instead.') if self.preference is None: preference = np.median(self.affinity_matrix_) else: preference = self.preference preference = np.array(preference, copy=False) random_state = check_random_state(self.random_state) <DeepExtract> n_samples = self.affinity_matrix_.shape[0] if n_samples == 1 or _equal_similarities_and_preferences(self.affinity_matrix_, preference): warnings.warn('All samples have mutually equal similarities. Returning arbitrary cluster center(s).') if preference.flat[0] >= self.affinity_matrix_.flat[n_samples - 1]: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (np.arange(n_samples), np.arange(n_samples), 0) if True else (np.arange(n_samples), np.arange(n_samples)) else: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (np.array([0]), np.array([0] * n_samples), 0) if True else (np.array([0]), np.array([0] * n_samples)) self.affinity_matrix_.flat[::n_samples + 1] = preference A = np.zeros((n_samples, n_samples)) R = np.zeros((n_samples, n_samples)) tmp = np.zeros((n_samples, n_samples)) self.affinity_matrix_ += (np.finfo(self.affinity_matrix_.dtype).eps * self.affinity_matrix_ + np.finfo(self.affinity_matrix_.dtype).tiny * 100) * random_state.standard_normal(size=(n_samples, n_samples)) e = np.zeros((n_samples, self.convergence_iter)) ind = np.arange(n_samples) for it in range(self.max_iter): np.add(A, self.affinity_matrix_, tmp) I = np.argmax(tmp, axis=1) Y = tmp[ind, I] tmp[ind, I] = -np.inf Y2 = np.max(tmp, axis=1) np.subtract(self.affinity_matrix_, Y[:, None], tmp) tmp[ind, I] = self.affinity_matrix_[ind, I] - Y2 tmp *= 1 - self.damping R *= self.damping R += tmp np.maximum(R, 0, tmp) tmp.flat[::n_samples + 1] = R.flat[::n_samples + 1] tmp -= np.sum(tmp, axis=0) dA = np.diag(tmp).copy() tmp.clip(0, np.inf, tmp) tmp.flat[::n_samples + 1] = dA tmp *= 1 - self.damping A *= self.damping A -= tmp E = np.diag(A) + np.diag(R) > 0 e[:, it % self.convergence_iter] = E K = np.sum(E, axis=0) if it >= self.convergence_iter: se = np.sum(e, axis=1) unconverged = np.sum((se == self.convergence_iter) + (se == 0)) != n_samples if not unconverged and K > 0 or it == self.max_iter: never_converged = False if self.verbose: print('Converged after %d iterations.' % it) break else: never_converged = True if self.verbose: print('Did not converge') I = np.flatnonzero(E) K = I.size if K > 0: if never_converged: warnings.warn('Affinity propagation did not converge, this model may return degenerate cluster centers and labels.', ConvergenceWarning) c = np.argmax(self.affinity_matrix_[:, I], axis=1) c[I] = np.arange(K) for k in range(K): ii = np.where(c == k)[0] j = np.argmax(np.sum(self.affinity_matrix_[ii[:, np.newaxis], ii], axis=0)) I[k] = ii[j] c = np.argmax(self.affinity_matrix_[:, I], axis=1) c[I] = np.arange(K) labels = I[c] cluster_centers_indices = np.unique(labels) labels = np.searchsorted(cluster_centers_indices, labels) else: warnings.warn('Affinity propagation did not converge and this model will not have any cluster centers.', ConvergenceWarning) labels = np.array([-1] * n_samples) cluster_centers_indices = [] if True: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (cluster_centers_indices, labels, it + 1) else: (self.cluster_centers_indices_, self.labels_, self.n_iter_) = (cluster_centers_indices, labels) </DeepExtract> if self.affinity != 'precomputed': self.cluster_centers_ = X[self.cluster_centers_indices_].copy() return self
@ignore_warnings(category=FutureWarning) def check_sample_weights_shape(name, estimator_orig): estimator = clone(estimator_orig) X = np.array([[1, 3], [1, 3], [1, 3], [1, 3], [2, 1], [2, 1], [2, 1], [2, 1], [3, 3], [3, 3], [3, 3], [3, 3], [4, 1], [4, 1], [4, 1], [4, 1]]) y = np.array([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2]) 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 estimator.fit(X, y, sample_weight=np.ones(len(y))) with raises(ValueError): estimator.fit(X, y, sample_weight=np.ones(2 * len(y))) with raises(ValueError): estimator.fit(X, y, sample_weight=np.ones((len(y), 2)))
@ignore_warnings(category=FutureWarning) def check_sample_weights_shape(name, estimator_orig): estimator = clone(estimator_orig) X = np.array([[1, 3], [1, 3], [1, 3], [1, 3], [2, 1], [2, 1], [2, 1], [2, 1], [3, 3], [3, 3], [3, 3], [3, 3], [4, 1], [4, 1], [4, 1], [4, 1]]) y = np.array([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2]) <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> estimator.fit(X, y, sample_weight=np.ones(len(y))) with raises(ValueError): estimator.fit(X, y, sample_weight=np.ones(2 * len(y))) with raises(ValueError): estimator.fit(X, y, sample_weight=np.ones((len(y), 2)))
def test_ridge_loo_cv_asym_scoring(): scoring = 'explained_variance' (n_samples, n_features) = (10, 5) n_targets = 1 (X, y, c) = make_regression(n_samples=n_samples, n_features=n_features, n_informative=5, n_targets=n_targets, bias=bias, noise=1, shuffle=False, coef=True, random_state=0) if n_features == 1: c = np.asarray([c]) X += X_offset mask = np.random.RandomState(0).binomial(1, proportion_nonzero, X.shape) > 0 removed_X = X.copy() X[~mask] = 0.0 removed_X[mask] = 0.0 y -= removed_X.dot(c) if positive: y += X.dot(np.abs(c) + 1 - c) c = np.abs(c) + 1 if n_features == 1: c = c[0] if coef: (X, y) = (X, y, c) (X, y) = (X, y) alphas = [0.001, 0.1, 1.0, 10.0, 1000.0] loo_ridge = RidgeCV(cv=n_samples, fit_intercept=True, alphas=alphas, scoring=scoring) gcv_ridge = RidgeCV(fit_intercept=True, alphas=alphas, scoring=scoring) loo_ridge.fit(X, y) gcv_ridge.fit(X, y) assert gcv_ridge.alpha_ == pytest.approx(loo_ridge.alpha_) assert_allclose(gcv_ridge.coef_, loo_ridge.coef_, rtol=0.001) assert_allclose(gcv_ridge.intercept_, loo_ridge.intercept_, rtol=0.001)
def test_ridge_loo_cv_asym_scoring(): scoring = 'explained_variance' (n_samples, n_features) = (10, 5) n_targets = 1 <DeepExtract> (X, y, c) = make_regression(n_samples=n_samples, n_features=n_features, n_informative=5, n_targets=n_targets, bias=bias, noise=1, shuffle=False, coef=True, random_state=0) if n_features == 1: c = np.asarray([c]) X += X_offset mask = np.random.RandomState(0).binomial(1, proportion_nonzero, X.shape) > 0 removed_X = X.copy() X[~mask] = 0.0 removed_X[mask] = 0.0 y -= removed_X.dot(c) if positive: y += X.dot(np.abs(c) + 1 - c) c = np.abs(c) + 1 if n_features == 1: c = c[0] if coef: (X, y) = (X, y, c) (X, y) = (X, y) </DeepExtract> alphas = [0.001, 0.1, 1.0, 10.0, 1000.0] loo_ridge = RidgeCV(cv=n_samples, fit_intercept=True, alphas=alphas, scoring=scoring) gcv_ridge = RidgeCV(fit_intercept=True, alphas=alphas, scoring=scoring) loo_ridge.fit(X, y) gcv_ridge.fit(X, y) assert gcv_ridge.alpha_ == pytest.approx(loo_ridge.alpha_) assert_allclose(gcv_ridge.coef_, loo_ridge.coef_, rtol=0.001) assert_allclose(gcv_ridge.intercept_, loo_ridge.intercept_, rtol=0.001)
def fit(self, X, y=None): """Fit the model to X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training 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 Returns the instance itself. """ self._validate_params() self._whiten = self.whiten if self._whiten == 'warn': warnings.warn("Starting in v1.3, whiten='unit-variance' will be used by default.", FutureWarning) self._whiten = 'arbitrary-variance' if self._whiten is True: warnings.warn("Starting in v1.3, whiten=True should be specified as whiten='arbitrary-variance' (its current behaviour). This behavior is deprecated in 1.1 and will raise ValueError in 1.3.", FutureWarning, stacklevel=2) self._whiten = 'arbitrary-variance' XT = self._validate_data(X, copy=self._whiten, dtype=[np.float64, np.float32], ensure_min_samples=2).T fun_args = {} if self.fun_args is None else self.fun_args random_state = check_random_state(self.random_state) alpha = fun_args.get('alpha', 1.0) if not 1 <= alpha <= 2: raise ValueError('alpha must be in [1,2]') if self.fun == 'logcosh': g = _logcosh elif self.fun == 'exp': g = _exp elif self.fun == 'cube': g = _cube elif callable(self.fun): def g(x, fun_args): return self.fun(x, **fun_args) (n_features, n_samples) = XT.shape n_components = self.n_components if not self._whiten and n_components is not None: n_components = None warnings.warn('Ignoring n_components with whiten=False.') if n_components is None: n_components = min(n_samples, n_features) if n_components > min(n_samples, n_features): n_components = min(n_samples, n_features) warnings.warn('n_components is too large: it will be set to %s' % n_components) if self._whiten: X_mean = XT.mean(axis=-1) XT -= X_mean[:, np.newaxis] if self.whiten_solver == 'eigh': (d, u) = linalg.eigh(XT.dot(X)) sort_indices = np.argsort(d)[::-1] eps = np.finfo(d.dtype).eps degenerate_idx = d < eps if np.any(degenerate_idx): warnings.warn("There are some small singular values, using whiten_solver = 'svd' might lead to more accurate results.") d[degenerate_idx] = eps np.sqrt(d, out=d) (d, u) = (d[sort_indices], u[:, sort_indices]) elif self.whiten_solver == 'svd': (u, d) = linalg.svd(XT, full_matrices=False, check_finite=False)[:2] u *= np.sign(u[0]) K = (u / d).T[:n_components] del u, d X1 = np.dot(K, XT) X1 *= np.sqrt(n_samples) else: X1 = as_float_array(XT, copy=False) w_init = self.w_init if w_init is None: w_init = np.asarray(random_state.normal(size=(n_components, n_components)), dtype=X1.dtype) else: w_init = np.asarray(w_init) if w_init.shape != (n_components, n_components): raise ValueError('w_init has invalid shape -- should be %(shape)s' % {'shape': (n_components, n_components)}) kwargs = {'tol': self.tol, 'g': g, 'fun_args': fun_args, 'max_iter': self.max_iter, 'w_init': w_init} if self.algorithm == 'parallel': (W, n_iter) = _ica_par(X1, **kwargs) elif self.algorithm == 'deflation': (W, n_iter) = _ica_def(X1, **kwargs) del X1 self.n_iter_ = n_iter if False: if self._whiten: S = np.linalg.multi_dot([W, K, XT]).T else: S = np.dot(W, XT).T else: S = None if self._whiten: if self._whiten == 'unit-variance': if not False: S = np.linalg.multi_dot([W, K, XT]).T S_std = np.std(S, axis=0, keepdims=True) S /= S_std W /= S_std.T self.components_ = np.dot(W, K) self.mean_ = X_mean self.whitening_ = K else: self.components_ = W self.mixing_ = linalg.pinv(self.components_, check_finite=False) self._unmixing = W return S return self
def fit(self, X, y=None): """Fit the model to X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training 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 Returns the instance itself. """ self._validate_params() <DeepExtract> self._whiten = self.whiten if self._whiten == 'warn': warnings.warn("Starting in v1.3, whiten='unit-variance' will be used by default.", FutureWarning) self._whiten = 'arbitrary-variance' if self._whiten is True: warnings.warn("Starting in v1.3, whiten=True should be specified as whiten='arbitrary-variance' (its current behaviour). This behavior is deprecated in 1.1 and will raise ValueError in 1.3.", FutureWarning, stacklevel=2) self._whiten = 'arbitrary-variance' XT = self._validate_data(X, copy=self._whiten, dtype=[np.float64, np.float32], ensure_min_samples=2).T fun_args = {} if self.fun_args is None else self.fun_args random_state = check_random_state(self.random_state) alpha = fun_args.get('alpha', 1.0) if not 1 <= alpha <= 2: raise ValueError('alpha must be in [1,2]') if self.fun == 'logcosh': g = _logcosh elif self.fun == 'exp': g = _exp elif self.fun == 'cube': g = _cube elif callable(self.fun): def g(x, fun_args): return self.fun(x, **fun_args) (n_features, n_samples) = XT.shape n_components = self.n_components if not self._whiten and n_components is not None: n_components = None warnings.warn('Ignoring n_components with whiten=False.') if n_components is None: n_components = min(n_samples, n_features) if n_components > min(n_samples, n_features): n_components = min(n_samples, n_features) warnings.warn('n_components is too large: it will be set to %s' % n_components) if self._whiten: X_mean = XT.mean(axis=-1) XT -= X_mean[:, np.newaxis] if self.whiten_solver == 'eigh': (d, u) = linalg.eigh(XT.dot(X)) sort_indices = np.argsort(d)[::-1] eps = np.finfo(d.dtype).eps degenerate_idx = d < eps if np.any(degenerate_idx): warnings.warn("There are some small singular values, using whiten_solver = 'svd' might lead to more accurate results.") d[degenerate_idx] = eps np.sqrt(d, out=d) (d, u) = (d[sort_indices], u[:, sort_indices]) elif self.whiten_solver == 'svd': (u, d) = linalg.svd(XT, full_matrices=False, check_finite=False)[:2] u *= np.sign(u[0]) K = (u / d).T[:n_components] del u, d X1 = np.dot(K, XT) X1 *= np.sqrt(n_samples) else: X1 = as_float_array(XT, copy=False) w_init = self.w_init if w_init is None: w_init = np.asarray(random_state.normal(size=(n_components, n_components)), dtype=X1.dtype) else: w_init = np.asarray(w_init) if w_init.shape != (n_components, n_components): raise ValueError('w_init has invalid shape -- should be %(shape)s' % {'shape': (n_components, n_components)}) kwargs = {'tol': self.tol, 'g': g, 'fun_args': fun_args, 'max_iter': self.max_iter, 'w_init': w_init} if self.algorithm == 'parallel': (W, n_iter) = _ica_par(X1, **kwargs) elif self.algorithm == 'deflation': (W, n_iter) = _ica_def(X1, **kwargs) del X1 self.n_iter_ = n_iter if False: if self._whiten: S = np.linalg.multi_dot([W, K, XT]).T else: S = np.dot(W, XT).T else: S = None if self._whiten: if self._whiten == 'unit-variance': if not False: S = np.linalg.multi_dot([W, K, XT]).T S_std = np.std(S, axis=0, keepdims=True) S /= S_std W /= S_std.T self.components_ = np.dot(W, K) self.mean_ = X_mean self.whitening_ = K else: self.components_ = W self.mixing_ = linalg.pinv(self.components_, check_finite=False) self._unmixing = W return S </DeepExtract> return self
def _score(self, X, y): """Private score method without input validation""" y_pred = self._forward_pass_fast(X, check_input=False) if self.n_outputs_ == 1: y_pred = y_pred.ravel() y_pred = self._label_binarizer.inverse_transform(y_pred) return r2_score(y, y_pred)
def _score(self, X, y): """Private score method without input validation""" <DeepExtract> y_pred = self._forward_pass_fast(X, check_input=False) if self.n_outputs_ == 1: y_pred = y_pred.ravel() y_pred = self._label_binarizer.inverse_transform(y_pred) </DeepExtract> return r2_score(y, y_pred)
def test_multi_core_gridsearch_and_early_stopping(): param_grid = {'alpha': np.logspace(-4, 4, 9), 'n_iter_no_change': [5, 10, 50]} _update_kwargs(kwargs) clf = linear_model.SGDClassifier(**kwargs) search = RandomizedSearchCV(clf, param_grid, n_iter=5, n_jobs=2, random_state=0) search.fit(iris.data, iris.target) assert search.best_score_ > 0.8
def test_multi_core_gridsearch_and_early_stopping(): param_grid = {'alpha': np.logspace(-4, 4, 9), 'n_iter_no_change': [5, 10, 50]} <DeepExtract> _update_kwargs(kwargs) clf = linear_model.SGDClassifier(**kwargs) </DeepExtract> search = RandomizedSearchCV(clf, param_grid, n_iter=5, n_jobs=2, random_state=0) search.fit(iris.data, iris.target) assert search.best_score_ > 0.8
def _partial_fit(self, X, alpha, C, loss, learning_rate, max_iter, sample_weight, coef_init, offset_init): first_call = getattr(self, 'coef_', None) is None X = self._validate_data(X, None, accept_sparse='csr', dtype=[np.float64, np.float32], order='C', accept_large_sparse=False, reset=first_call) n_features = X.shape[1] sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) if getattr(self, 'coef_', None) is None or coef_init is not None: if 1 > 2: if coef_init is not None: coef_init = np.asarray(coef_init, dtype=X.dtype, order='C') if coef_init.shape != (1, n_features): raise ValueError('Provided ``coef_`` does not match dataset. ') self.coef_ = coef_init else: self.coef_ = np.zeros((1, n_features), dtype=X.dtype, order='C') if offset_init is not None: offset_init = np.asarray(offset_init, order='C', dtype=X.dtype) if offset_init.shape != (1,): raise ValueError('Provided intercept_init does not match dataset.') self.intercept_ = offset_init else: self.intercept_ = np.zeros(1, dtype=X.dtype, order='C') else: if coef_init is not None: coef_init = np.asarray(coef_init, dtype=X.dtype, order='C') coef_init = coef_init.ravel() if coef_init.shape != (n_features,): raise ValueError('Provided coef_init does not match dataset.') self.coef_ = coef_init else: self.coef_ = np.zeros(n_features, dtype=X.dtype, order='C') if offset_init is not None: offset_init = np.asarray(offset_init, dtype=X.dtype) if offset_init.shape != (1,) and offset_init.shape != (): raise ValueError('Provided intercept_init does not match dataset.') if 1: self.offset_ = offset_init.reshape(1) else: self.intercept_ = offset_init.reshape(1) elif 1: self.offset_ = np.zeros(1, dtype=X.dtype, order='C') else: self.intercept_ = np.zeros(1, dtype=X.dtype, order='C') if self.average > 0: self._standard_coef = self.coef_ self._average_coef = np.zeros(self.coef_.shape, dtype=X.dtype, order='C') if 1: self._standard_intercept = 1 - self.offset_ else: self._standard_intercept = self.intercept_ self._average_intercept = np.zeros(self._standard_intercept.shape, dtype=X.dtype, order='C') 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])) if self.average and getattr(self, '_average_coef', None) is None: self._average_coef = np.zeros(n_features, dtype=X.dtype, order='C') self._average_intercept = np.zeros(1, dtype=X.dtype, order='C') loss_ = self.loss_functions[loss] (loss_class, args) = (loss_[0], loss_[1:]) if loss in ('huber', 'epsilon_insensitive', 'squared_epsilon_insensitive'): args = (self.epsilon,) self.loss_function_ = loss_class(*args) if not hasattr(self, 't_'): self.t_ = 1.0 n_samples = X.shape[0] y = np.ones(n_samples, dtype=X.dtype, order='C') (dataset, offset_decay) = make_dataset(X, y, sample_weight) penalty_type = self._get_penalty_type(self.penalty) learning_rate_type = self._get_learning_rate_type(learning_rate) validation_mask = self._make_validation_split(y, sample_mask=sample_weight > 0) validation_score_cb = self._make_validation_score_cb(validation_mask, X, y, sample_weight) random_state = check_random_state(self.random_state) seed = random_state.randint(0, np.iinfo(np.int32).max) tol = self.tol if self.tol is not None else -np.inf one_class = 1 pos_weight = 1 neg_weight = 1 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 = 1 - self.offset_ average_coef = None average_intercept = [0] _plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype) (coef, intercept, average_coef, average_intercept, self.n_iter_) = _plain_sgd(coef, intercept[0], average_coef, average_intercept[0], self.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, neg_weight, pos_weight, learning_rate_type, self.eta0, self.power_t, one_class, self.t_, offset_decay, self.average) self.t_ += self.n_iter_ * n_samples 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.offset_ = 1 - np.atleast_1d(average_intercept) else: self.coef_ = coef self.offset_ = 1 - np.atleast_1d(intercept) else: self.offset_ = 1 - np.atleast_1d(intercept) return self
def _partial_fit(self, X, alpha, C, loss, learning_rate, max_iter, sample_weight, coef_init, offset_init): first_call = getattr(self, 'coef_', None) is None X = self._validate_data(X, None, accept_sparse='csr', dtype=[np.float64, np.float32], order='C', accept_large_sparse=False, reset=first_call) n_features = X.shape[1] sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) if getattr(self, 'coef_', None) is None or coef_init is not None: <DeepExtract> if 1 > 2: if coef_init is not None: coef_init = np.asarray(coef_init, dtype=X.dtype, order='C') if coef_init.shape != (1, n_features): raise ValueError('Provided ``coef_`` does not match dataset. ') self.coef_ = coef_init else: self.coef_ = np.zeros((1, n_features), dtype=X.dtype, order='C') if offset_init is not None: offset_init = np.asarray(offset_init, order='C', dtype=X.dtype) if offset_init.shape != (1,): raise ValueError('Provided intercept_init does not match dataset.') self.intercept_ = offset_init else: self.intercept_ = np.zeros(1, dtype=X.dtype, order='C') else: if coef_init is not None: coef_init = np.asarray(coef_init, dtype=X.dtype, order='C') coef_init = coef_init.ravel() if coef_init.shape != (n_features,): raise ValueError('Provided coef_init does not match dataset.') self.coef_ = coef_init else: self.coef_ = np.zeros(n_features, dtype=X.dtype, order='C') if offset_init is not None: offset_init = np.asarray(offset_init, dtype=X.dtype) if offset_init.shape != (1,) and offset_init.shape != (): raise ValueError('Provided intercept_init does not match dataset.') if 1: self.offset_ = offset_init.reshape(1) else: self.intercept_ = offset_init.reshape(1) elif 1: self.offset_ = np.zeros(1, dtype=X.dtype, order='C') else: self.intercept_ = np.zeros(1, dtype=X.dtype, order='C') if self.average > 0: self._standard_coef = self.coef_ self._average_coef = np.zeros(self.coef_.shape, dtype=X.dtype, order='C') if 1: self._standard_intercept = 1 - self.offset_ else: self._standard_intercept = self.intercept_ self._average_intercept = np.zeros(self._standard_intercept.shape, dtype=X.dtype, order='C') </DeepExtract> 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])) if self.average and getattr(self, '_average_coef', None) is None: self._average_coef = np.zeros(n_features, dtype=X.dtype, order='C') self._average_intercept = np.zeros(1, dtype=X.dtype, order='C') <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,) self.loss_function_ = loss_class(*args) </DeepExtract> if not hasattr(self, 't_'): self.t_ = 1.0 <DeepExtract> n_samples = X.shape[0] y = np.ones(n_samples, dtype=X.dtype, order='C') (dataset, offset_decay) = make_dataset(X, y, sample_weight) penalty_type = self._get_penalty_type(self.penalty) learning_rate_type = self._get_learning_rate_type(learning_rate) validation_mask = self._make_validation_split(y, sample_mask=sample_weight > 0) validation_score_cb = self._make_validation_score_cb(validation_mask, X, y, sample_weight) random_state = check_random_state(self.random_state) seed = random_state.randint(0, np.iinfo(np.int32).max) tol = self.tol if self.tol is not None else -np.inf one_class = 1 pos_weight = 1 neg_weight = 1 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 = 1 - self.offset_ average_coef = None average_intercept = [0] _plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype) (coef, intercept, average_coef, average_intercept, self.n_iter_) = _plain_sgd(coef, intercept[0], average_coef, average_intercept[0], self.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, neg_weight, pos_weight, learning_rate_type, self.eta0, self.power_t, one_class, self.t_, offset_decay, self.average) self.t_ += self.n_iter_ * n_samples 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.offset_ = 1 - np.atleast_1d(average_intercept) else: self.coef_ = coef self.offset_ = 1 - np.atleast_1d(intercept) else: self.offset_ = 1 - np.atleast_1d(intercept) </DeepExtract> return self
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 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')
@pytest.mark.filterwarnings('ignore:WMinkowskiDistance:FutureWarning:sklearn') @pytest.mark.parametrize('Cls, metric', itertools.chain([(KDTree, metric) for metric in KD_TREE_METRICS], [(BallTree, metric) for metric in BALL_TREE_METRICS])) @pytest.mark.parametrize('k', (1, 3, 5)) @pytest.mark.parametrize('dualtree', (True, False)) @pytest.mark.parametrize('breadth_first', (True, False)) def test_nn_tree_query(Cls, metric, k, dualtree, breadth_first): rng = check_random_state(0) X = rng.random_sample((40, DIMENSION)) Y = rng.random_sample((10, DIMENSION)) kwargs = METRICS[metric] kdt = Cls(X, leaf_size=1, metric=metric, **kwargs) (dist1, ind1) = kdt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first) D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) ind = np.argsort(D, axis=1)[:, :k] dist = D[np.arange(Y.shape[0])[:, None], ind] (dist2, ind2) = (dist, ind) assert_array_almost_equal(dist1, dist2)
@pytest.mark.filterwarnings('ignore:WMinkowskiDistance:FutureWarning:sklearn') @pytest.mark.parametrize('Cls, metric', itertools.chain([(KDTree, metric) for metric in KD_TREE_METRICS], [(BallTree, metric) for metric in BALL_TREE_METRICS])) @pytest.mark.parametrize('k', (1, 3, 5)) @pytest.mark.parametrize('dualtree', (True, False)) @pytest.mark.parametrize('breadth_first', (True, False)) def test_nn_tree_query(Cls, metric, k, dualtree, breadth_first): rng = check_random_state(0) X = rng.random_sample((40, DIMENSION)) Y = rng.random_sample((10, DIMENSION)) kwargs = METRICS[metric] kdt = Cls(X, leaf_size=1, metric=metric, **kwargs) (dist1, ind1) = kdt.query(Y, k, dualtree=dualtree, breadth_first=breadth_first) <DeepExtract> D = DistanceMetric.get_metric(metric, **kwargs).pairwise(Y, X) ind = np.argsort(D, axis=1)[:, :k] dist = D[np.arange(Y.shape[0])[:, None], ind] (dist2, ind2) = (dist, ind) </DeepExtract> assert_array_almost_equal(dist1, dist2)
def decision_function(self, X): probs = X msg = 'This helper should only be used on multioutput-multiclass tasks' assert isinstance(probs, list), msg probs = [p[:, -1] if p.shape[1] == 2 else p for p in probs] return probs
def decision_function(self, X): <DeepExtract> probs = X </DeepExtract> msg = 'This helper should only be used on multioutput-multiclass tasks' assert isinstance(probs, list), msg probs = [p[:, -1] if p.shape[1] == 2 else p for p in probs] return probs
@if_safe_multiprocessing_with_blas def test_lda_partial_fit_multi_jobs(): 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, n_jobs=2, learning_offset=5.0, total_samples=30, random_state=rng) for i in range(2): lda.partial_fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert tuple(sorted(top_idx)) in correct_idx_grps
@if_safe_multiprocessing_with_blas def test_lda_partial_fit_multi_jobs(): 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, n_jobs=2, learning_offset=5.0, total_samples=30, random_state=rng) for i in range(2): lda.partial_fit(X) correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)] for c in lda.components_: top_idx = set(c.argsort()[-3:][::-1]) assert tuple(sorted(top_idx)) in correct_idx_grps
@hides def inverse_transform(self, X, *args, **kwargs): check_is_fitted(self) return X
@hides def inverse_transform(self, X, *args, **kwargs): <DeepExtract> check_is_fitted(self) </DeepExtract> return X
def __init__(self, expr, savelist=False): super(ParseElementEnhance, self).__init__(savelist) if isinstance(expr, basestring): if issubclass(ParserElement._literalStringClass, Token): expr = ParserElement._literalStringClass(expr) else: expr = ParserElement._literalStringClass(Literal(expr)) self.expr = expr self.strRepr = None if expr is not None: self.mayIndexError = expr.mayIndexError self.mayReturnEmpty = expr.mayReturnEmpty self.skipWhitespace = True self.whiteChars = expr.whiteChars self.copyDefaultWhiteChars = False return self self.skipWhitespace = expr.skipWhitespace self.saveAsList = expr.saveAsList self.callPreparse = expr.callPreparse self.ignoreExprs.extend(expr.ignoreExprs)
def __init__(self, expr, savelist=False): super(ParseElementEnhance, self).__init__(savelist) if isinstance(expr, basestring): if issubclass(ParserElement._literalStringClass, Token): expr = ParserElement._literalStringClass(expr) else: expr = ParserElement._literalStringClass(Literal(expr)) self.expr = expr self.strRepr = None if expr is not None: self.mayIndexError = expr.mayIndexError self.mayReturnEmpty = expr.mayReturnEmpty <DeepExtract> self.skipWhitespace = True self.whiteChars = expr.whiteChars self.copyDefaultWhiteChars = False return self </DeepExtract> self.skipWhitespace = expr.skipWhitespace self.saveAsList = expr.saveAsList self.callPreparse = expr.callPreparse self.ignoreExprs.extend(expr.ignoreExprs)
def _count_vocab(self, raw_documents, fixed_vocab): """Create sparse feature matrix, and vocabulary where fixed_vocab=False""" if fixed_vocab: vocabulary = self.vocabulary_ else: vocabulary = defaultdict() vocabulary.default_factory = vocabulary.__len__ if callable(self.analyzer): analyze = partial(_analyze, analyzer=self.analyzer, decoder=self.decode) preprocess = self.build_preprocessor() if self.analyzer == 'char': analyze = partial(_analyze, ngrams=self._char_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'char_wb': analyze = partial(_analyze, ngrams=self._char_wb_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'word': stop_words = self.get_stop_words() tokenize = self.build_tokenizer() self._check_stop_words_consistency(stop_words, preprocess, tokenize) analyze = partial(_analyze, ngrams=self._word_ngrams, tokenizer=tokenize, preprocessor=preprocess, decoder=self.decode, stop_words=stop_words) else: raise ValueError('%s is not a valid tokenization scheme/analyzer' % self.analyzer) j_indices = [] indptr = [] values = array.array(str('i')) 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 fixed_vocab: 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() return (vocabulary, X)
def _count_vocab(self, raw_documents, fixed_vocab): """Create sparse feature matrix, and vocabulary where fixed_vocab=False""" if fixed_vocab: vocabulary = self.vocabulary_ else: vocabulary = defaultdict() vocabulary.default_factory = vocabulary.__len__ <DeepExtract> if callable(self.analyzer): analyze = partial(_analyze, analyzer=self.analyzer, decoder=self.decode) preprocess = self.build_preprocessor() if self.analyzer == 'char': analyze = partial(_analyze, ngrams=self._char_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'char_wb': analyze = partial(_analyze, ngrams=self._char_wb_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'word': stop_words = self.get_stop_words() tokenize = self.build_tokenizer() self._check_stop_words_consistency(stop_words, preprocess, tokenize) analyze = partial(_analyze, ngrams=self._word_ngrams, tokenizer=tokenize, preprocessor=preprocess, decoder=self.decode, stop_words=stop_words) else: raise ValueError('%s is not a valid tokenization scheme/analyzer' % self.analyzer) </DeepExtract> j_indices = [] indptr = [] <DeepExtract> values = array.array(str('i')) </DeepExtract> 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 fixed_vocab: 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() return (vocabulary, X)
def _intilialize_root(gradients, hessians, hessians_are_constant): """Initialize root node and finalize it if needed.""" n_samples = self.X_binned.shape[0] depth = 0 sum_gradients = sum_parallel(gradients, self.n_threads) if self.histogram_builder.hessians_are_constant: sum_hessians = hessians[0] * n_samples else: sum_hessians = sum_parallel(hessians, self.n_threads) self.root = TreeNode(depth=depth, sample_indices=self.splitter.partition, sum_gradients=sum_gradients, sum_hessians=sum_hessians, value=0) self.root.partition_start = 0 self.root.partition_stop = n_samples if self.root.n_samples < 2 * self.min_samples_leaf: self.root.is_leaf = True self.finalized_leaves.append(self.root) return if sum_hessians < self.splitter.min_hessian_to_split: self.root.is_leaf = True self.finalized_leaves.append(self.root) return if self.interaction_cst is not None: self.root.interaction_cst_indices = range(len(self.interaction_cst)) allowed_features = set().union(*self.interaction_cst) self.root.allowed_features = np.fromiter(allowed_features, dtype=np.uint32, count=len(allowed_features)) tic = time() self.root.histograms = self.histogram_builder.compute_histograms_brute(self.root.sample_indices, self.root.allowed_features) self.total_compute_hist_time += time() - tic tic = time() self.root.split_info = self.splitter.find_node_split(n_samples=self.root.n_samples, histograms=self.root.histograms, sum_gradients=self.root.sum_gradients, sum_hessians=self.root.sum_hessians, value=self.root.value, lower_bound=self.root.children_lower_bound, upper_bound=self.root.children_upper_bound, allowed_features=self.root.allowed_features) if self.root.split_info.gain <= 0: self._finalize_leaf(self.root) else: heappush(self.splittable_nodes, self.root) self.total_find_split_time += time() - tic
def _intilialize_root(gradients, hessians, hessians_are_constant): """Initialize root node and finalize it if needed.""" n_samples = self.X_binned.shape[0] depth = 0 sum_gradients = sum_parallel(gradients, self.n_threads) if self.histogram_builder.hessians_are_constant: sum_hessians = hessians[0] * n_samples else: sum_hessians = sum_parallel(hessians, self.n_threads) self.root = TreeNode(depth=depth, sample_indices=self.splitter.partition, sum_gradients=sum_gradients, sum_hessians=sum_hessians, value=0) self.root.partition_start = 0 self.root.partition_stop = n_samples if self.root.n_samples < 2 * self.min_samples_leaf: <DeepExtract> self.root.is_leaf = True self.finalized_leaves.append(self.root) </DeepExtract> return if sum_hessians < self.splitter.min_hessian_to_split: <DeepExtract> self.root.is_leaf = True self.finalized_leaves.append(self.root) </DeepExtract> return if self.interaction_cst is not None: self.root.interaction_cst_indices = range(len(self.interaction_cst)) allowed_features = set().union(*self.interaction_cst) self.root.allowed_features = np.fromiter(allowed_features, dtype=np.uint32, count=len(allowed_features)) tic = time() self.root.histograms = self.histogram_builder.compute_histograms_brute(self.root.sample_indices, self.root.allowed_features) self.total_compute_hist_time += time() - tic tic = time() <DeepExtract> self.root.split_info = self.splitter.find_node_split(n_samples=self.root.n_samples, histograms=self.root.histograms, sum_gradients=self.root.sum_gradients, sum_hessians=self.root.sum_hessians, value=self.root.value, lower_bound=self.root.children_lower_bound, upper_bound=self.root.children_upper_bound, allowed_features=self.root.allowed_features) if self.root.split_info.gain <= 0: self._finalize_leaf(self.root) else: heappush(self.splittable_nodes, self.root) </DeepExtract> self.total_find_split_time += time() - tic
def test_predict_3_classes(): n_samples = len(Y2) classes = np.unique(Y2) n_classes = classes.shape[0] predicted = LogisticRegression(C=10).fit(X, Y2).predict(X) assert_array_equal(LogisticRegression(C=10).classes_, classes) assert predicted.shape == (n_samples,) assert_array_equal(predicted, Y2) probabilities = LogisticRegression(C=10).predict_proba(X) assert probabilities.shape == (n_samples, n_classes) assert_array_almost_equal(probabilities.sum(axis=1), np.ones(n_samples)) assert_array_equal(probabilities.argmax(axis=1), Y2) n_samples = len(Y2) classes = np.unique(Y2) n_classes = classes.shape[0] predicted = LogisticRegression(C=10).fit(X_sp, Y2).predict(X_sp) assert_array_equal(LogisticRegression(C=10).classes_, classes) assert predicted.shape == (n_samples,) assert_array_equal(predicted, Y2) probabilities = LogisticRegression(C=10).predict_proba(X_sp) assert probabilities.shape == (n_samples, n_classes) assert_array_almost_equal(probabilities.sum(axis=1), np.ones(n_samples)) assert_array_equal(probabilities.argmax(axis=1), Y2) </DeepExtract>
def test_predict_3_classes(): <DeepExtract> n_samples = len(Y2) classes = np.unique(Y2) n_classes = classes.shape[0] predicted = LogisticRegression(C=10).fit(X, Y2).predict(X) assert_array_equal(LogisticRegression(C=10).classes_, classes) assert predicted.shape == (n_samples,) assert_array_equal(predicted, Y2) probabilities = LogisticRegression(C=10).predict_proba(X) assert probabilities.shape == (n_samples, n_classes) assert_array_almost_equal(probabilities.sum(axis=1), np.ones(n_samples)) assert_array_equal(probabilities.argmax(axis=1), Y2) </DeepExtract> <DeepExtract> n_samples = len(Y2) classes = np.unique(Y2) n_classes = classes.shape[0] predicted = LogisticRegression(C=10).fit(X_sp, Y2).predict(X_sp) assert_array_equal(LogisticRegression(C=10).classes_, classes) assert predicted.shape == (n_samples,) assert_array_equal(predicted, Y2) probabilities = LogisticRegression(C=10).predict_proba(X_sp) assert probabilities.shape == (n_samples, n_classes) assert_array_almost_equal(probabilities.sum(axis=1), np.ones(n_samples)) assert_array_equal(probabilities.argmax(axis=1), Y2) </DeepExtract>
@ignore_warnings def check_dict_unchanged(name, estimator_orig): if name in ['SpectralCoclustering']: return rnd = np.random.RandomState(0) if name in ['RANSACRegressor']: X = 3 * rnd.uniform(size=(20, 3)) else: X = 2 * rnd.uniform(size=(20, 3)) 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 y = X[:, 0].astype(int) 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 hasattr(estimator, 'n_components'): estimator.n_components = 1 if hasattr(estimator, 'n_clusters'): estimator.n_clusters = 1 if hasattr(estimator, 'n_best'): estimator.n_best = 1 set_random_state(estimator, 1) estimator.fit(X, y) for method in ['predict', 'transform', 'decision_function', 'predict_proba']: if hasattr(estimator, method): dict_before = estimator.__dict__.copy() getattr(estimator, method)(X) assert estimator.__dict__ == dict_before, 'Estimator changes __dict__ during %s' % method
@ignore_warnings def check_dict_unchanged(name, estimator_orig): if name in ['SpectralCoclustering']: return rnd = np.random.RandomState(0) if name in ['RANSACRegressor']: X = 3 * rnd.uniform(size=(20, 3)) else: X = 2 * rnd.uniform(size=(20, 3)) <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> y = X[:, 0].astype(int) 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 hasattr(estimator, 'n_components'): estimator.n_components = 1 if hasattr(estimator, 'n_clusters'): estimator.n_clusters = 1 if hasattr(estimator, 'n_best'): estimator.n_best = 1 set_random_state(estimator, 1) estimator.fit(X, y) for method in ['predict', 'transform', 'decision_function', 'predict_proba']: if hasattr(estimator, method): dict_before = estimator.__dict__.copy() getattr(estimator, method)(X) assert estimator.__dict__ == dict_before, 'Estimator changes __dict__ during %s' % method
def check_pairwise_arrays(X, Y, *, precomputed=False, dtype=None, accept_sparse='csr', force_all_finite=True, copy=False): """Set X and Y appropriately and checks inputs. If Y is None, it is set as a pointer to X (i.e. not a copy). If Y is given, this does not happen. All 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 (or dtype if provided). Finally, the function checks that the size of the second dimension of the two arrays is equal, or the equivalent check for a precomputed distance matrix. 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) precomputed : bool, default=False True if X is to be treated as precomputed distances to the samples in Y. dtype : str, type, list of type, default=None Data type required for X and Y. If None, the dtype will be an appropriate float type selected by _return_float_dtype. .. versionadded:: 0.18 accept_sparse : str, bool or list/tuple of str, default='csr' String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 0.22 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan`. copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. .. versionadded:: 0.22 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. """ if not issparse(X) and (not isinstance(X, np.ndarray)): X = np.asarray(X) if Y is None: Y_dtype = X.dtype elif not issparse(Y) and (not isinstance(Y, np.ndarray)): Y = np.asarray(Y) Y_dtype = Y.dtype else: Y_dtype = Y.dtype if X.dtype == Y_dtype == np.float32: dtype = np.float32 else: dtype = float (X, Y, dtype_float) = (X, Y, dtype) 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])) return (X, Y)
def check_pairwise_arrays(X, Y, *, precomputed=False, dtype=None, accept_sparse='csr', force_all_finite=True, copy=False): """Set X and Y appropriately and checks inputs. If Y is None, it is set as a pointer to X (i.e. not a copy). If Y is given, this does not happen. All 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 (or dtype if provided). Finally, the function checks that the size of the second dimension of the two arrays is equal, or the equivalent check for a precomputed distance matrix. 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) precomputed : bool, default=False True if X is to be treated as precomputed distances to the samples in Y. dtype : str, type, list of type, default=None Data type required for X and Y. If None, the dtype will be an appropriate float type selected by _return_float_dtype. .. versionadded:: 0.18 accept_sparse : str, bool or list/tuple of str, default='csr' String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. If the input is sparse but not in the allowed format, it will be converted to the first listed format. True allows the input to be any format. False means that a sparse matrix input will raise an error. force_all_finite : bool or 'allow-nan', default=True Whether to raise an error on np.inf, np.nan, pd.NA in array. The possibilities are: - True: Force all values of array to be finite. - False: accepts np.inf, np.nan, pd.NA in array. - 'allow-nan': accepts only np.nan and pd.NA values in array. Values cannot be infinite. .. versionadded:: 0.22 ``force_all_finite`` accepts the string ``'allow-nan'``. .. versionchanged:: 0.23 Accepts `pd.NA` and converts it into `np.nan`. copy : bool, default=False Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. .. versionadded:: 0.22 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> if not issparse(X) and (not isinstance(X, np.ndarray)): X = np.asarray(X) if Y is None: Y_dtype = X.dtype elif not issparse(Y) and (not isinstance(Y, np.ndarray)): Y = np.asarray(Y) Y_dtype = Y.dtype else: Y_dtype = Y.dtype if X.dtype == Y_dtype == np.float32: dtype = np.float32 else: dtype = float (X, Y, dtype_float) = (X, Y, dtype) </DeepExtract> 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])) return (X, Y)
def _path_residuals(X, y, sample_weight, train, test, fit_intercept, path, path_params, alphas=None, l1_ratio=1, X_order=None, dtype=None): """Returns the MSE for the models computed by 'path'. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. sample_weight : None or array-like of shape (n_samples,) Sample weights. train : list of indices The indices of the train set. test : list of indices The indices of the test set. path : callable Function returning a list of models on the path. See enet_path for an example of signature. path_params : dictionary Parameters passed to the path function. alphas : array-like, default=None Array of float that is used for cross-validation. If not provided, computed using 'path'. l1_ratio : float, default=1 float between 0 and 1 passed to ElasticNet (scaling between l1 and l2 penalties). For ``l1_ratio = 0`` the penalty is an L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. For ``0 < l1_ratio < 1``, the penalty is a combination of L1 and L2. X_order : {'F', 'C'}, default=None The order of the arrays expected by the path function to avoid memory copies. dtype : a numpy dtype, default=None The dtype of the arrays expected by the path function to avoid memory copies. """ X_train = X[train] y_train = y[train] X_test = X[test] y_test = y[test] if sample_weight is None: (sw_train, sw_test) = (None, None) else: sw_train = sample_weight[train] sw_test = sample_weight[test] n_samples = X_train.shape[0] sw_train *= n_samples / np.sum(sw_train) if not sparse.issparse(X): for (array, array_input) in ((X_train, X), (y_train, y), (X_test, X), (y_test, y)): if array.base is not array_input and (not array.flags['WRITEABLE']): array.setflags(write=True) if y.ndim == 1: precompute = path_params['precompute'] else: precompute = False (X_train, y_train, X_offset, y_offset, X_scale, precompute, Xy) = _pre_fit(X_train, y_train, None, precompute, normalize=False, fit_intercept=fit_intercept, copy=False, sample_weight=sw_train) path_params = path_params.copy() path_params['Xy'] = Xy path_params['X_offset'] = X_offset path_params['X_scale'] = X_scale path_params['precompute'] = precompute path_params['copy_X'] = False path_params['alphas'] = alphas path_params['sample_weight'] = sw_train if 'l1_ratio' in path_params: path_params['l1_ratio'] = l1_ratio X_train = check_array(X_train, accept_sparse='csc', dtype=dtype, order=X_order) del X_train, y_train if y.ndim == 1: coefs = coefs[np.newaxis, :, :] y_offset = np.atleast_1d(y_offset) y_test = y_test[:, np.newaxis] intercepts = y_offset[:, np.newaxis] - np.dot(X_offset, coefs) X_test_coefs = safe_sparse_dot(X_test, coefs) residues = X_test_coefs - y_test[:, :, np.newaxis] residues += intercepts if sample_weight is None: this_mse = (residues ** 2).mean(axis=0) else: this_mse = np.average(residues ** 2, weights=sw_test, axis=0) return this_mse.mean(axis=0)
def _path_residuals(X, y, sample_weight, train, test, fit_intercept, path, path_params, alphas=None, l1_ratio=1, X_order=None, dtype=None): """Returns the MSE for the models computed by 'path'. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. sample_weight : None or array-like of shape (n_samples,) Sample weights. train : list of indices The indices of the train set. test : list of indices The indices of the test set. path : callable Function returning a list of models on the path. See enet_path for an example of signature. path_params : dictionary Parameters passed to the path function. alphas : array-like, default=None Array of float that is used for cross-validation. If not provided, computed using 'path'. l1_ratio : float, default=1 float between 0 and 1 passed to ElasticNet (scaling between l1 and l2 penalties). For ``l1_ratio = 0`` the penalty is an L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. For ``0 < l1_ratio < 1``, the penalty is a combination of L1 and L2. X_order : {'F', 'C'}, default=None The order of the arrays expected by the path function to avoid memory copies. dtype : a numpy dtype, default=None The dtype of the arrays expected by the path function to avoid memory copies. """ X_train = X[train] y_train = y[train] X_test = X[test] y_test = y[test] if sample_weight is None: (sw_train, sw_test) = (None, None) else: sw_train = sample_weight[train] sw_test = sample_weight[test] n_samples = X_train.shape[0] sw_train *= n_samples / np.sum(sw_train) if not sparse.issparse(X): for (array, array_input) in ((X_train, X), (y_train, y), (X_test, X), (y_test, y)): if array.base is not array_input and (not array.flags['WRITEABLE']): array.setflags(write=True) if y.ndim == 1: precompute = path_params['precompute'] else: precompute = False (X_train, y_train, X_offset, y_offset, X_scale, precompute, Xy) = _pre_fit(X_train, y_train, None, precompute, normalize=False, fit_intercept=fit_intercept, copy=False, sample_weight=sw_train) path_params = path_params.copy() path_params['Xy'] = Xy path_params['X_offset'] = X_offset path_params['X_scale'] = X_scale path_params['precompute'] = precompute path_params['copy_X'] = False path_params['alphas'] = alphas path_params['sample_weight'] = sw_train if 'l1_ratio' in path_params: path_params['l1_ratio'] = l1_ratio X_train = check_array(X_train, accept_sparse='csc', dtype=dtype, order=X_order) <DeepExtract> </DeepExtract> del X_train, y_train if y.ndim == 1: coefs = coefs[np.newaxis, :, :] y_offset = np.atleast_1d(y_offset) y_test = y_test[:, np.newaxis] intercepts = y_offset[:, np.newaxis] - np.dot(X_offset, coefs) X_test_coefs = safe_sparse_dot(X_test, coefs) residues = X_test_coefs - y_test[:, :, np.newaxis] residues += intercepts if sample_weight is None: this_mse = (residues ** 2).mean(axis=0) else: this_mse = np.average(residues ** 2, weights=sw_test, axis=0) return this_mse.mean(axis=0)
def test_check_input_false(): random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(10, n_targets) else: w = random_state.randn(10) w[n_informative_features:] = 0.0 X = random_state.randn(20, 10) y = np.dot(X, w) X_test = random_state.randn(20, 10) y_test = np.dot(X_test, w) (X, y, _, _) = (X, y, X_test, y_test) X = check_array(X, order='F', dtype='float64') y = check_array(X, order='F', dtype='float64') clf = ElasticNet(selection='cyclic', tol=1e-08) clf.fit(X, y, check_input=False) X = check_array(X, order='F', dtype='float32') clf.fit(X, y, check_input=False) X = check_array(X, order='C', dtype='float64') with pytest.raises(ValueError): clf.fit(X, y, check_input=False)
def test_check_input_false(): <DeepExtract> random_state = np.random.RandomState(0) if n_targets > 1: w = random_state.randn(10, n_targets) else: w = random_state.randn(10) w[n_informative_features:] = 0.0 X = random_state.randn(20, 10) y = np.dot(X, w) X_test = random_state.randn(20, 10) y_test = np.dot(X_test, w) (X, y, _, _) = (X, y, X_test, y_test) </DeepExtract> X = check_array(X, order='F', dtype='float64') y = check_array(X, order='F', dtype='float64') clf = ElasticNet(selection='cyclic', tol=1e-08) clf.fit(X, y, check_input=False) X = check_array(X, order='F', dtype='float32') clf.fit(X, y, check_input=False) X = check_array(X, order='C', dtype='float64') with pytest.raises(ValueError): clf.fit(X, y, check_input=False)
def transform(self, X): """Feature-wise transformation of the data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. Additionally, the sparse matrix needs to be nonnegative if `ignore_implicit_zeros` is False. Returns ------- Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) The projected data. """ check_is_fitted(self) X = self._validate_data(X, reset=False, accept_sparse='csc', copy=self.copy, dtype=FLOAT_DTYPES, force_all_finite='allow-nan') with np.errstate(invalid='ignore'): if not accept_sparse_negative and (not self.ignore_implicit_zeros) and (sparse.issparse(X) and np.any(X.data < 0)): raise ValueError('QuantileTransformer only accepts non-negative sparse matrices.') X = X return self._transform(X, inverse=False)
def transform(self, X): """Feature-wise transformation of the data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The data used to scale along the features axis. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. Additionally, the sparse matrix needs to be nonnegative if `ignore_implicit_zeros` is False. Returns ------- Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) The projected data. """ check_is_fitted(self) <DeepExtract> X = self._validate_data(X, reset=False, accept_sparse='csc', copy=self.copy, dtype=FLOAT_DTYPES, force_all_finite='allow-nan') with np.errstate(invalid='ignore'): if not accept_sparse_negative and (not self.ignore_implicit_zeros) and (sparse.issparse(X) and np.any(X.data < 0)): raise ValueError('QuantileTransformer only accepts non-negative sparse matrices.') X = X </DeepExtract> return self._transform(X, inverse=False)
@validate_params({'y_true': ['array-like'], 'y_score': ['array-like'], 'average': [StrOptions({'micro', 'samples', 'weighted', 'macro'}), None], 'pos_label': [Real, str, 'boolean'], 'sample_weight': ['array-like', None]}) def average_precision_score(y_true, y_score, *, average='macro', pos_label=1, sample_weight=None): """Compute average precision (AP) from prediction scores. AP summarizes a precision-recall curve as the weighted mean of precisions achieved at each threshold, with the increase in recall from the previous threshold used as the weight: .. math:: \\text{AP} = \\sum_n (R_n - R_{n-1}) P_n where :math:`P_n` and :math:`R_n` are the precision and recall at the nth threshold [1]_. This implementation is not interpolated and is different from computing the area under the precision-recall curve with the trapezoidal rule, which uses linear interpolation and can be too optimistic. Note: this implementation is restricted to the binary classification task or multilabel classification task. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_classes) True binary labels or binary label indicators. y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by :term:`decision_function` on some classifiers). average : {'micro', 'samples', 'weighted', 'macro'} or None, default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'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). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. pos_label : int, float, bool or str, default=1 The label of the positive class. Only applied to binary ``y_true``. For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- average_precision : float Average precision score. See Also -------- roc_auc_score : Compute the area under the ROC curve. precision_recall_curve : Compute precision-recall pairs for different probability thresholds. Notes ----- .. versionchanged:: 0.19 Instead of linearly interpolating between operating points, precisions are weighted by the change in recall since the last operating point. References ---------- .. [1] `Wikipedia entry for the Average precision <https://en.wikipedia.org/w/index.php?title=Information_retrieval& oldid=793358396#Average_precision>`_ Examples -------- >>> import numpy as np >>> from sklearn.metrics import average_precision_score >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> average_precision_score(y_true, y_scores) 0.83... """ def _binary_uninterpolated_average_precision(y_true, y_score, pos_label=1, sample_weight=None): (fps, tps, thresholds) = _binary_clf_curve(y_true, y_score, pos_label=pos_label, sample_weight=sample_weight) 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) (precision, recall, _) = (np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl]) return -np.sum(np.diff(recall) * np.array(precision)[:-1]) y_type = type_of_target(y_true, input_name='y_true') if y_type == 'multilabel-indicator' and pos_label != 1: raise ValueError('Parameter pos_label is fixed to 1 for multilabel-indicator y_true. Do not set pos_label or set pos_label to 1.') elif y_type == 'binary': present_labels = np.unique(y_true).tolist() if len(present_labels) == 2 and pos_label not in present_labels: raise ValueError(f'pos_label={pos_label} is not a valid label. It should be one of {present_labels}') average_precision = partial(_binary_uninterpolated_average_precision, pos_label=pos_label) return _average_binary_score(average_precision, y_true, y_score, average, sample_weight=sample_weight)
@validate_params({'y_true': ['array-like'], 'y_score': ['array-like'], 'average': [StrOptions({'micro', 'samples', 'weighted', 'macro'}), None], 'pos_label': [Real, str, 'boolean'], 'sample_weight': ['array-like', None]}) def average_precision_score(y_true, y_score, *, average='macro', pos_label=1, sample_weight=None): """Compute average precision (AP) from prediction scores. AP summarizes a precision-recall curve as the weighted mean of precisions achieved at each threshold, with the increase in recall from the previous threshold used as the weight: .. math:: \\text{AP} = \\sum_n (R_n - R_{n-1}) P_n where :math:`P_n` and :math:`R_n` are the precision and recall at the nth threshold [1]_. This implementation is not interpolated and is different from computing the area under the precision-recall curve with the trapezoidal rule, which uses linear interpolation and can be too optimistic. Note: this implementation is restricted to the binary classification task or multilabel classification task. Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) or (n_samples, n_classes) True binary labels or binary label indicators. y_score : array-like of shape (n_samples,) or (n_samples, n_classes) Target scores, can either be probability estimates of the positive class, confidence values, or non-thresholded measure of decisions (as returned by :term:`decision_function` on some classifiers). average : {'micro', 'samples', 'weighted', 'macro'} or None, default='macro' If ``None``, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data: ``'micro'``: Calculate metrics globally by considering each element of the label indicator matrix as a label. ``'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). ``'samples'``: Calculate metrics for each instance, and find their average. Will be ignored when ``y_true`` is binary. pos_label : int, float, bool or str, default=1 The label of the positive class. Only applied to binary ``y_true``. For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1. sample_weight : array-like of shape (n_samples,), default=None Sample weights. Returns ------- average_precision : float Average precision score. See Also -------- roc_auc_score : Compute the area under the ROC curve. precision_recall_curve : Compute precision-recall pairs for different probability thresholds. Notes ----- .. versionchanged:: 0.19 Instead of linearly interpolating between operating points, precisions are weighted by the change in recall since the last operating point. References ---------- .. [1] `Wikipedia entry for the Average precision <https://en.wikipedia.org/w/index.php?title=Information_retrieval& oldid=793358396#Average_precision>`_ Examples -------- >>> import numpy as np >>> from sklearn.metrics import average_precision_score >>> y_true = np.array([0, 0, 1, 1]) >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) >>> average_precision_score(y_true, y_scores) 0.83... """ def _binary_uninterpolated_average_precision(y_true, y_score, pos_label=1, sample_weight=None): <DeepExtract> (fps, tps, thresholds) = _binary_clf_curve(y_true, y_score, pos_label=pos_label, sample_weight=sample_weight) 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) (precision, recall, _) = (np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl]) </DeepExtract> return -np.sum(np.diff(recall) * np.array(precision)[:-1]) y_type = type_of_target(y_true, input_name='y_true') if y_type == 'multilabel-indicator' and pos_label != 1: raise ValueError('Parameter pos_label is fixed to 1 for multilabel-indicator y_true. Do not set pos_label or set pos_label to 1.') elif y_type == 'binary': present_labels = np.unique(y_true).tolist() if len(present_labels) == 2 and pos_label not in present_labels: raise ValueError(f'pos_label={pos_label} is not a valid label. It should be one of {present_labels}') average_precision = partial(_binary_uninterpolated_average_precision, pos_label=pos_label) return _average_binary_score(average_precision, y_true, y_score, average, sample_weight=sample_weight)
def copyTokenToRepeater(s, l, t): if t: if len(t) == 1: rep << t[0] else: ret = [] for i in t.asList(): if isinstance(i, list): ret.extend(_flatten(i)) else: ret.append(i) tflat = ret rep << And((Literal(tt) for tt in tflat)) else: rep << Empty()
def copyTokenToRepeater(s, l, t): if t: if len(t) == 1: rep << t[0] else: <DeepExtract> ret = [] for i in t.asList(): if isinstance(i, list): ret.extend(_flatten(i)) else: ret.append(i) tflat = ret </DeepExtract> rep << And((Literal(tt) for tt in tflat)) else: rep << Empty()
def test_max_iter(): def ricker_function(resolution, center, width): """Discrete sub-sampled Ricker (Mexican hat) wavelet""" x = np.linspace(0, resolution - 1, resolution) x = 2 / (np.sqrt(3 * width) * np.pi ** 0.25) * (1 - (x - center) ** 2 / width ** 2) * np.exp(-(x - center) ** 2 / (2 * width ** 2)) return x def ricker_matrix(width, resolution, n_components): """Dictionary of Ricker (Mexican hat) wavelets""" centers = np.linspace(0, resolution - 1, n_components) D = np.empty((n_components, resolution)) for (i, center) in enumerate(centers): x = np.linspace(0, resolution - 1, resolution) x = 2 / (np.sqrt(3 * width) * np.pi ** 0.25) * (1 - (x - center) ** 2 / width ** 2) * np.exp(-(x - center) ** 2 / (2 * width ** 2)) D[i] = x D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis] return D transform_algorithm = 'lasso_cd' resolution = 1024 subsampling = 3 n_components = resolution // subsampling D_multi = np.r_[tuple((ricker_matrix(width=w, resolution=resolution, n_components=n_components // 5) for w in (10, 50, 100, 500, 1000)))] X = np.linspace(0, resolution - 1, resolution) first_quarter = X < resolution / 4 X[first_quarter] = 3.0 X[np.logical_not(first_quarter)] = -1.0 X = X.reshape(1, -1) with pytest.warns(ConvergenceWarning): model = SparseCoder(D_multi, transform_algorithm=transform_algorithm, transform_max_iter=1) model.fit_transform(X) with warnings.catch_warnings(): warnings.simplefilter('error', ConvergenceWarning) model = SparseCoder(D_multi, transform_algorithm=transform_algorithm, transform_max_iter=2000) model.fit_transform(X)
def test_max_iter(): def ricker_function(resolution, center, width): """Discrete sub-sampled Ricker (Mexican hat) wavelet""" x = np.linspace(0, resolution - 1, resolution) x = 2 / (np.sqrt(3 * width) * np.pi ** 0.25) * (1 - (x - center) ** 2 / width ** 2) * np.exp(-(x - center) ** 2 / (2 * width ** 2)) return x def ricker_matrix(width, resolution, n_components): """Dictionary of Ricker (Mexican hat) wavelets""" centers = np.linspace(0, resolution - 1, n_components) D = np.empty((n_components, resolution)) for (i, center) in enumerate(centers): <DeepExtract> x = np.linspace(0, resolution - 1, resolution) x = 2 / (np.sqrt(3 * width) * np.pi ** 0.25) * (1 - (x - center) ** 2 / width ** 2) * np.exp(-(x - center) ** 2 / (2 * width ** 2)) D[i] = x </DeepExtract> D /= np.sqrt(np.sum(D ** 2, axis=1))[:, np.newaxis] return D transform_algorithm = 'lasso_cd' resolution = 1024 subsampling = 3 n_components = resolution // subsampling D_multi = np.r_[tuple((ricker_matrix(width=w, resolution=resolution, n_components=n_components // 5) for w in (10, 50, 100, 500, 1000)))] X = np.linspace(0, resolution - 1, resolution) first_quarter = X < resolution / 4 X[first_quarter] = 3.0 X[np.logical_not(first_quarter)] = -1.0 X = X.reshape(1, -1) with pytest.warns(ConvergenceWarning): model = SparseCoder(D_multi, transform_algorithm=transform_algorithm, transform_max_iter=1) model.fit_transform(X) with warnings.catch_warnings(): warnings.simplefilter('error', ConvergenceWarning) model = SparseCoder(D_multi, transform_algorithm=transform_algorithm, transform_max_iter=2000) model.fit_transform(X)
def transform(self, X): """Transform a sequence of documents to a document-term matrix. Parameters ---------- X : iterable over raw text documents, length = n_samples Samples. Each sample must be a text document (either bytes or unicode strings, file name or file object depending on the constructor argument) which will be tokenized and hashed. Returns ------- X : sparse matrix of shape (n_samples, n_features) Document-term matrix. """ if isinstance(X, str): raise ValueError('Iterable over raw text documents expected, string object received.') (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 callable(self.analyzer): analyzer = partial(_analyze, analyzer=self.analyzer, decoder=self.decode) preprocess = self.build_preprocessor() if self.analyzer == 'char': analyzer = partial(_analyze, ngrams=self._char_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'char_wb': analyzer = partial(_analyze, ngrams=self._char_wb_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'word': stop_words = self.get_stop_words() tokenize = self.build_tokenizer() self._check_stop_words_consistency(stop_words, preprocess, tokenize) analyzer = partial(_analyze, ngrams=self._word_ngrams, tokenizer=tokenize, preprocessor=preprocess, decoder=self.decode, stop_words=stop_words) else: raise ValueError('%s is not a valid tokenization scheme/analyzer' % self.analyzer) X = self._get_hasher().transform((analyzer(doc) for doc in X)) if self.binary: X.data.fill(1) if self.norm is not None: X = normalize(X, norm=self.norm, copy=False) return X
def transform(self, X): """Transform a sequence of documents to a document-term matrix. Parameters ---------- X : iterable over raw text documents, length = n_samples Samples. Each sample must be a text document (either bytes or unicode strings, file name or file object depending on the constructor argument) which will be tokenized and hashed. Returns ------- X : sparse matrix of shape (n_samples, n_features) Document-term matrix. """ if isinstance(X, str): raise ValueError('Iterable over raw text documents expected, string object received.') <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 callable(self.analyzer): analyzer = partial(_analyze, analyzer=self.analyzer, decoder=self.decode) preprocess = self.build_preprocessor() if self.analyzer == 'char': analyzer = partial(_analyze, ngrams=self._char_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'char_wb': analyzer = partial(_analyze, ngrams=self._char_wb_ngrams, preprocessor=preprocess, decoder=self.decode) elif self.analyzer == 'word': stop_words = self.get_stop_words() tokenize = self.build_tokenizer() self._check_stop_words_consistency(stop_words, preprocess, tokenize) analyzer = partial(_analyze, ngrams=self._word_ngrams, tokenizer=tokenize, preprocessor=preprocess, decoder=self.decode, stop_words=stop_words) else: raise ValueError('%s is not a valid tokenization scheme/analyzer' % self.analyzer) </DeepExtract> X = self._get_hasher().transform((analyzer(doc) for doc in X)) if self.binary: X.data.fill(1) if self.norm is not None: X = normalize(X, norm=self.norm, copy=False) return X
@fails_if_pypy @pytest.mark.parametrize('data_id, dataset_params, n_samples, n_features, n_targets', [(61, {'data_id': 61}, 150, 4, 1), (61, {'name': 'iris', 'version': 1}, 150, 4, 1), (2, {'data_id': 2}, 11, 38, 1), (2, {'name': 'anneal', 'version': 1}, 11, 38, 1), (561, {'data_id': 561}, 209, 7, 1), (561, {'name': 'cpu', 'version': 1}, 209, 7, 1), (40589, {'data_id': 40589}, 13, 72, 6), (1119, {'data_id': 1119}, 10, 14, 1), (1119, {'name': 'adult-census'}, 10, 14, 1), (40966, {'data_id': 40966}, 7, 77, 1), (40966, {'name': 'MiceProtein'}, 7, 77, 1)]) @pytest.mark.parametrize('parser', ['liac-arff', 'pandas']) def test_fetch_openml_as_frame_false(monkeypatch, data_id, dataset_params, n_samples, n_features, n_targets, parser): """Check the behaviour of `fetch_openml` with `as_frame=False`. Fetch both by ID and/or name + version. """ pytest.importorskip('pandas') 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 True: 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) bunch = fetch_openml(as_frame=False, cache=False, parser=parser, **dataset_params) assert int(bunch.details['id']) == data_id assert isinstance(bunch, Bunch) assert bunch.frame is None assert isinstance(bunch.data, np.ndarray) assert bunch.data.shape == (n_samples, n_features) assert isinstance(bunch.target, np.ndarray) if n_targets == 1: assert bunch.target.shape == (n_samples,) else: assert bunch.target.shape == (n_samples, n_targets) assert isinstance(bunch.categories, dict)
@fails_if_pypy @pytest.mark.parametrize('data_id, dataset_params, n_samples, n_features, n_targets', [(61, {'data_id': 61}, 150, 4, 1), (61, {'name': 'iris', 'version': 1}, 150, 4, 1), (2, {'data_id': 2}, 11, 38, 1), (2, {'name': 'anneal', 'version': 1}, 11, 38, 1), (561, {'data_id': 561}, 209, 7, 1), (561, {'name': 'cpu', 'version': 1}, 209, 7, 1), (40589, {'data_id': 40589}, 13, 72, 6), (1119, {'data_id': 1119}, 10, 14, 1), (1119, {'name': 'adult-census'}, 10, 14, 1), (40966, {'data_id': 40966}, 7, 77, 1), (40966, {'name': 'MiceProtein'}, 7, 77, 1)]) @pytest.mark.parametrize('parser', ['liac-arff', 'pandas']) def test_fetch_openml_as_frame_false(monkeypatch, data_id, dataset_params, n_samples, n_features, n_targets, parser): """Check the behaviour of `fetch_openml` with `as_frame=False`. Fetch both by ID and/or name + version. """ pytest.importorskip('pandas') <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 True: 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> bunch = fetch_openml(as_frame=False, cache=False, parser=parser, **dataset_params) assert int(bunch.details['id']) == data_id assert isinstance(bunch, Bunch) assert bunch.frame is None assert isinstance(bunch.data, np.ndarray) assert bunch.data.shape == (n_samples, n_features) assert isinstance(bunch.target, np.ndarray) if n_targets == 1: assert bunch.target.shape == (n_samples,) else: assert bunch.target.shape == (n_samples, n_targets) assert isinstance(bunch.categories, dict)