code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def pytest_collection_modifyitems(config, items): """Called after collect is completed. Parameters ---------- config : pytest config items : list of collected items """ skip_doctests = False if np_base_version < parse_version("2"): # TODO: configure numpy to output scalar arrays...
Called after collect is completed. Parameters ---------- config : pytest config items : list of collected items
pytest_collection_modifyitems
python
scikit-learn/scikit-learn
doc/conftest.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/conftest.py
BSD-3-Clause
def add_content(self, more_content): """Override default behavior to add only the first line of the docstring. Modified based on the part of processing docstrings in the original implementation of this method. https://github.com/sphinx-doc/sphinx/blob/faa33a53a389f6f8bc1f6ae97d6015fa92...
Override default behavior to add only the first line of the docstring. Modified based on the part of processing docstrings in the original implementation of this method. https://github.com/sphinx-doc/sphinx/blob/faa33a53a389f6f8bc1f6ae97d6015fa92393c4a/sphinx/ext/autodoc/__init__.py#L609-L622 ...
add_content
python
scikit-learn/scikit-learn
doc/sphinxext/autoshortsummary.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/autoshortsummary.py
BSD-3-Clause
def _linkcode_resolve(domain, info, package, url_fmt, revision): """Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... ...
Determine a link to online source for a class/method/function This is called by sphinx.ext.linkcode An example with a long-untouched module that everyone has >>> _linkcode_resolve('py', {'module': 'tty', ... 'fullname': 'setraw'}, ... package='tty', ....
_linkcode_resolve
python
scikit-learn/scikit-learn
doc/sphinxext/github_link.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/github_link.py
BSD-3-Clause
def override_pst_pagetoc(app, pagename, templatename, context, doctree): """Overrides the `generate_toc_html` function of pydata-sphinx-theme for API.""" @cache def generate_api_toc_html(kind="html"): """Generate the in-page toc for an API page. This relies on the `generate_toc_html` funct...
Overrides the `generate_toc_html` function of pydata-sphinx-theme for API.
override_pst_pagetoc
python
scikit-learn/scikit-learn
doc/sphinxext/override_pst_pagetoc.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/override_pst_pagetoc.py
BSD-3-Clause
def generate_api_toc_html(kind="html"): """Generate the in-page toc for an API page. This relies on the `generate_toc_html` function added by pydata-sphinx-theme into the context. We save the original function into `pst_generate_toc_html` and override `generate_toc_html` with this funct...
Generate the in-page toc for an API page. This relies on the `generate_toc_html` function added by pydata-sphinx-theme into the context. We save the original function into `pst_generate_toc_html` and override `generate_toc_html` with this function for generated API pages. The pagetoc o...
generate_api_toc_html
python
scikit-learn/scikit-learn
doc/sphinxext/override_pst_pagetoc.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/override_pst_pagetoc.py
BSD-3-Clause
def user_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text also...
Sphinx role for linking to a user profile. Defaults to linking to Github profiles, but the profile URIS can be configured via the ``issues_user_uri`` config value. Examples: :: :user:`sloria` Anchor text also works: :: :user:`Steven Loria <sloria>`
user_role
python
scikit-learn/scikit-learn
doc/sphinxext/sphinx_issues.py
https://github.com/scikit-learn/scikit-learn/blob/master/doc/sphinxext/sphinx_issues.py
BSD-3-Clause
def plot_digits(X, title): """Small helper function to plot 100 digits.""" fig, axs = plt.subplots(nrows=10, ncols=10, figsize=(8, 8)) for img, ax in zip(X, axs.ravel()): ax.imshow(img.reshape((16, 16)), cmap="Greys") ax.axis("off") fig.suptitle(title, fontsize=24)
Small helper function to plot 100 digits.
plot_digits
python
scikit-learn/scikit-learn
examples/applications/plot_digits_denoising.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_digits_denoising.py
BSD-3-Clause
def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=0.01, right=0.99, top=0.90, hspace=0.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1...
Helper function to plot a gallery of portraits
plot_gallery
python
scikit-learn/scikit-learn
examples/applications/plot_face_recognition.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_face_recognition.py
BSD-3-Clause
def benchmark_influence(conf): """ Benchmark influence of `changing_param` on both MSE and latency. """ prediction_times = [] prediction_powers = [] complexities = [] for param_value in conf["changing_param_values"]: conf["tuned_params"][conf["changing_param"]] = param_value ...
Benchmark influence of `changing_param` on both MSE and latency.
benchmark_influence
python
scikit-learn/scikit-learn
examples/applications/plot_model_complexity_influence.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_model_complexity_influence.py
BSD-3-Clause
def plot_influence(conf, mse_values, prediction_times, complexities): """ Plot influence of model complexity on both accuracy and latency. """ fig = plt.figure() fig.subplots_adjust(right=0.75) # first axes (prediction error) ax1 = fig.add_subplot(111) line1 = ax1.plot(complexities, ms...
Plot influence of model complexity on both accuracy and latency.
plot_influence
python
scikit-learn/scikit-learn
examples/applications/plot_model_complexity_influence.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_model_complexity_influence.py
BSD-3-Clause
def stream_reuters_documents(data_path=None): """Iterate over documents of the Reuters dataset. The Reuters archive will automatically be downloaded and uncompressed if the `data_path` directory does not exist. Documents are represented as dictionaries with 'body' (str), 'title' (str), 'topics' (l...
Iterate over documents of the Reuters dataset. The Reuters archive will automatically be downloaded and uncompressed if the `data_path` directory does not exist. Documents are represented as dictionaries with 'body' (str), 'title' (str), 'topics' (list(str)) keys.
stream_reuters_documents
python
scikit-learn/scikit-learn
examples/applications/plot_out_of_core_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_out_of_core_classification.py
BSD-3-Clause
def get_minibatch(doc_iter, size, pos_class=positive_class): """Extract a minibatch of examples, return a tuple X_text, y. Note: size is before excluding invalid docs with no topics assigned. """ data = [ ("{title}\n\n{body}".format(**doc), pos_class in doc["topics"]) for doc in iterto...
Extract a minibatch of examples, return a tuple X_text, y. Note: size is before excluding invalid docs with no topics assigned.
get_minibatch
python
scikit-learn/scikit-learn
examples/applications/plot_out_of_core_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_out_of_core_classification.py
BSD-3-Clause
def autolabel(rectangles): """attach some text vi autolabel on rectangles.""" for rect in rectangles: height = rect.get_height() ax.text( rect.get_x() + rect.get_width() / 2.0, 1.05 * height, "%.4f" % height, ha="center", va="bottom", ...
attach some text vi autolabel on rectangles.
autolabel
python
scikit-learn/scikit-learn
examples/applications/plot_out_of_core_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_out_of_core_classification.py
BSD-3-Clause
def atomic_benchmark_estimator(estimator, X_test, verbose=False): """Measure runtime prediction of each instance.""" n_instances = X_test.shape[0] runtimes = np.zeros(n_instances, dtype=float) for i in range(n_instances): instance = X_test[[i], :] start = time.time() estimator.pr...
Measure runtime prediction of each instance.
atomic_benchmark_estimator
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def bulk_benchmark_estimator(estimator, X_test, n_bulk_repeats, verbose): """Measure runtime prediction of the whole input.""" n_instances = X_test.shape[0] runtimes = np.zeros(n_bulk_repeats, dtype=float) for i in range(n_bulk_repeats): start = time.time() estimator.predict(X_test) ...
Measure runtime prediction of the whole input.
bulk_benchmark_estimator
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def benchmark_estimator(estimator, X_test, n_bulk_repeats=30, verbose=False): """ Measure runtimes of prediction in both atomic and bulk mode. Parameters ---------- estimator : already trained estimator supporting `predict()` X_test : test input n_bulk_repeats : how many times to repeat whe...
Measure runtimes of prediction in both atomic and bulk mode. Parameters ---------- estimator : already trained estimator supporting `predict()` X_test : test input n_bulk_repeats : how many times to repeat when evaluating bulk mode Returns ------- atomic_runtimes, bulk_runtimes : ...
benchmark_estimator
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def generate_dataset(n_train, n_test, n_features, noise=0.1, verbose=False): """Generate a regression dataset with the given parameters.""" if verbose: print("generating dataset...") X, y, coef = make_regression( n_samples=n_train + n_test, n_features=n_features, noise=noise, coef=True ...
Generate a regression dataset with the given parameters.
generate_dataset
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def boxplot_runtimes(runtimes, pred_type, configuration): """ Plot a new `Figure` with boxplots of prediction runtimes. Parameters ---------- runtimes : list of `np.array` of latencies in micro-seconds cls_names : list of estimator class names that generated the runtimes pred_type : 'bulk' ...
Plot a new `Figure` with boxplots of prediction runtimes. Parameters ---------- runtimes : list of `np.array` of latencies in micro-seconds cls_names : list of estimator class names that generated the runtimes pred_type : 'bulk' or 'atomic'
boxplot_runtimes
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def n_feature_influence(estimators, n_train, n_test, n_features, percentile): """ Estimate influence of the number of features on prediction time. Parameters ---------- estimators : dict of (name (str), estimator) to benchmark n_train : nber of training instances (int) n_test : nber of tes...
Estimate influence of the number of features on prediction time. Parameters ---------- estimators : dict of (name (str), estimator) to benchmark n_train : nber of training instances (int) n_test : nber of testing instances (int) n_features : list of feature-space dimensionality to test (i...
n_feature_influence
python
scikit-learn/scikit-learn
examples/applications/plot_prediction_latency.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_prediction_latency.py
BSD-3-Clause
def construct_grids(batch): """Construct the map grid from the batch object Parameters ---------- batch : Batch object The object returned by :func:`fetch_species_distributions` Returns ------- (xgrid, ygrid) : 1-D arrays The grid corresponding to the values in batch.covera...
Construct the map grid from the batch object Parameters ---------- batch : Batch object The object returned by :func:`fetch_species_distributions` Returns ------- (xgrid, ygrid) : 1-D arrays The grid corresponding to the values in batch.coverages
construct_grids
python
scikit-learn/scikit-learn
examples/applications/plot_species_distribution_modeling.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_species_distribution_modeling.py
BSD-3-Clause
def create_species_bunch(species_name, train, test, coverages, xgrid, ygrid): """Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name. """ bunch = Bunch(name=" ".join(species_name.split("_")[:2]...
Create a bunch with information about a particular organism This will use the test/train record arrays to extract the data specific to the given species name.
create_species_bunch
python
scikit-learn/scikit-learn
examples/applications/plot_species_distribution_modeling.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_species_distribution_modeling.py
BSD-3-Clause
def build_projection_operator(l_x, n_dir): """Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2...
Compute the tomography design matrix. Parameters ---------- l_x : int linear size of image array n_dir : int number of angles at which projections are acquired. Returns ------- p : sparse matrix of shape (n_dir l_x, l_x**2)
build_projection_operator
python
scikit-learn/scikit-learn
examples/applications/plot_tomography_l1_reconstruction.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/plot_tomography_l1_reconstruction.py
BSD-3-Clause
def index(redirects, index_map, k): """Find the index of an article name after redirect resolution""" k = redirects.get(k, k) return index_map.setdefault(k, len(index_map))
Find the index of an article name after redirect resolution
index
python
scikit-learn/scikit-learn
examples/applications/wikipedia_principal_eigenvector.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/wikipedia_principal_eigenvector.py
BSD-3-Clause
def get_redirects(redirects_filename): """Parse the redirections and build a transitively closed map out of it""" redirects = {} print("Parsing the NT redirect file") for l, line in enumerate(BZ2File(redirects_filename)): split = line.split() if len(split) != 4: print("ignori...
Parse the redirections and build a transitively closed map out of it
get_redirects
python
scikit-learn/scikit-learn
examples/applications/wikipedia_principal_eigenvector.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/wikipedia_principal_eigenvector.py
BSD-3-Clause
def get_adjacency_matrix(redirects_filename, page_links_filename, limit=None): """Extract the adjacency graph as a scipy sparse matrix Redirects are resolved first. Returns X, the scipy sparse adjacency matrix, redirects as python dict from article names to article names and index_map a python dict ...
Extract the adjacency graph as a scipy sparse matrix Redirects are resolved first. Returns X, the scipy sparse adjacency matrix, redirects as python dict from article names to article names and index_map a python dict from article names to python int (article indexes).
get_adjacency_matrix
python
scikit-learn/scikit-learn
examples/applications/wikipedia_principal_eigenvector.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/applications/wikipedia_principal_eigenvector.py
BSD-3-Clause
def predict_proba(self, X): """Min-max scale output of `decision_function` to [0, 1].""" df = self.decision_function(X) calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_) proba_pos_class = np.clip(calibrated_df, 0, 1) proba_neg_class = 1 - proba_pos_class ...
Min-max scale output of `decision_function` to [0, 1].
predict_proba
python
scikit-learn/scikit-learn
examples/calibration/plot_calibration_curve.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/calibration/plot_calibration_curve.py
BSD-3-Clause
def predict_proba(self, X): """Min-max scale output of `decision_function` to [0,1].""" df = self.decision_function(X) calibrated_df = (df - self.df_min_) / (self.df_max_ - self.df_min_) proba_pos_class = np.clip(calibrated_df, 0, 1) proba_neg_class = 1 - proba_pos_class ...
Min-max scale output of `decision_function` to [0,1].
predict_proba
python
scikit-learn/scikit-learn
examples/calibration/plot_compare_calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/calibration/plot_compare_calibration.py
BSD-3-Clause
def generate_data(n_samples, n_features): """Generate random blob-ish data with noisy features. This returns an array of input data with shape `(n_samples, n_features)` and an array of `n_samples` target labels. Only one feature contains discriminative information, the other features contain only ...
Generate random blob-ish data with noisy features. This returns an array of input data with shape `(n_samples, n_features)` and an array of `n_samples` target labels. Only one feature contains discriminative information, the other features contain only noise.
generate_data
python
scikit-learn/scikit-learn
examples/classification/plot_lda.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/classification/plot_lda.py
BSD-3-Clause
def _classifier_has(attr): """Check if we can delegate a method to the underlying classifier. First, we check the first fitted classifier if available, otherwise we check the unfitted classifier. """ return lambda estimator: ( hasattr(estimator.classifier_, attr) if hasattr(estimato...
Check if we can delegate a method to the underlying classifier. First, we check the first fitted classifier if available, otherwise we check the unfitted classifier.
_classifier_has
python
scikit-learn/scikit-learn
examples/cluster/plot_inductive_clustering.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/cluster/plot_inductive_clustering.py
BSD-3-Clause
def bench_k_means(kmeans, name, data, labels): """Benchmark to evaluate the KMeans initialization methods. Parameters ---------- kmeans : KMeans instance A :class:`~sklearn.cluster.KMeans` instance with the initialization already set. name : str Name given to the strategy. I...
Benchmark to evaluate the KMeans initialization methods. Parameters ---------- kmeans : KMeans instance A :class:`~sklearn.cluster.KMeans` instance with the initialization already set. name : str Name given to the strategy. It will be used to show the results in a table....
bench_k_means
python
scikit-learn/scikit-learn
examples/cluster/plot_kmeans_digits.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/cluster/plot_kmeans_digits.py
BSD-3-Clause
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)) ...
Discrete sub-sampled Ricker (Mexican hat) wavelet
ricker_function
python
scikit-learn/scikit-learn
examples/decomposition/plot_sparse_coding.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/decomposition/plot_sparse_coding.py
BSD-3-Clause
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): D[i] = ricker_function(resolution, center, width) D /= np...
Dictionary of Ricker (Mexican hat) wavelets
ricker_matrix
python
scikit-learn/scikit-learn
examples/decomposition/plot_sparse_coding.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/decomposition/plot_sparse_coding.py
BSD-3-Clause
def fit(self, X, y): """ Fit the estimator to the training data. """ self.classes_ = sorted(set(y)) # Custom attribute to track if the estimator is fitted self._is_fitted = True return self
Fit the estimator to the training data.
fit
python
scikit-learn/scikit-learn
examples/developing_estimators/sklearn_is_fitted.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/developing_estimators/sklearn_is_fitted.py
BSD-3-Clause
def predict(self, X): """ Perform Predictions If the estimator is not fitted, then raise NotFittedError """ check_is_fitted(self) # Perform prediction logic predictions = [self.classes_[0]] * len(X) return predictions
Perform Predictions If the estimator is not fitted, then raise NotFittedError
predict
python
scikit-learn/scikit-learn
examples/developing_estimators/sklearn_is_fitted.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/developing_estimators/sklearn_is_fitted.py
BSD-3-Clause
def score(self, X, y): """ Calculate Score If the estimator is not fitted, then raise NotFittedError """ check_is_fitted(self) # Perform scoring logic return 0.5
Calculate Score If the estimator is not fitted, then raise NotFittedError
score
python
scikit-learn/scikit-learn
examples/developing_estimators/sklearn_is_fitted.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/developing_estimators/sklearn_is_fitted.py
BSD-3-Clause
def _f(self, s1, s2): """ kernel value between a pair of sequences """ return sum( [1.0 if c1 == c2 else self.baseline_similarity for c1 in s1 for c2 in s2] )
kernel value between a pair of sequences
_f
python
scikit-learn/scikit-learn
examples/gaussian_process/plot_gpr_on_structured_data.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/gaussian_process/plot_gpr_on_structured_data.py
BSD-3-Clause
def plot_gpr_samples(gpr_model, n_samples, ax): """Plot samples drawn from the Gaussian process model. If the Gaussian process model is not trained then the drawn samples are drawn from the prior distribution. Otherwise, the samples are drawn from the posterior distribution. Be aware that a sample here...
Plot samples drawn from the Gaussian process model. If the Gaussian process model is not trained then the drawn samples are drawn from the prior distribution. Otherwise, the samples are drawn from the posterior distribution. Be aware that a sample here corresponds to a function. Parameters ---...
plot_gpr_samples
python
scikit-learn/scikit-learn
examples/gaussian_process/plot_gpr_prior_posterior.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/gaussian_process/plot_gpr_prior_posterior.py
BSD-3-Clause
def score_estimator(estimator, df_test): """Score an estimator on the test set.""" y_pred = estimator.predict(df_test) print( "MSE: %.3f" % mean_squared_error( df_test["Frequency"], y_pred, sample_weight=df_test["Exposure"] ) ) print( "MAE: %.3f" ...
Score an estimator on the test set.
score_estimator
python
scikit-learn/scikit-learn
examples/linear_model/plot_poisson_regression_non_normal_loss.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/linear_model/plot_poisson_regression_non_normal_loss.py
BSD-3-Clause
def _mean_frequency_by_risk_group(y_true, y_pred, sample_weight=None, n_bins=100): """Compare predictions and observations for bins ordered by y_pred. We order the samples by ``y_pred`` and split it in bins. In each bin the observed mean is compared with the predicted mean. Parameters ---------- ...
Compare predictions and observations for bins ordered by y_pred. We order the samples by ``y_pred`` and split it in bins. In each bin the observed mean is compared with the predicted mean. Parameters ---------- y_true: array-like of shape (n_samples,) Ground truth (correct) target values. ...
_mean_frequency_by_risk_group
python
scikit-learn/scikit-learn
examples/linear_model/plot_poisson_regression_non_normal_loss.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/linear_model/plot_poisson_regression_non_normal_loss.py
BSD-3-Clause
def load_mnist(n_samples=None, class_0="0", class_1="8"): """Load MNIST, select two classes, shuffle and return only n_samples.""" # Load data from http://openml.org/d/554 mnist = fetch_openml("mnist_784", version=1, as_frame=False) # take only two classes for binary classification mask = np.logica...
Load MNIST, select two classes, shuffle and return only n_samples.
load_mnist
python
scikit-learn/scikit-learn
examples/linear_model/plot_sgd_early_stopping.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/linear_model/plot_sgd_early_stopping.py
BSD-3-Clause
def fit_and_score(estimator, max_iter, X_train, X_test, y_train, y_test): """Fit the estimator on the train set and score it on both sets""" estimator.set_params(max_iter=max_iter) estimator.set_params(random_state=0) start = time.time() estimator.fit(X_train, y_train) fit_time = time.time() -...
Fit the estimator on the train set and score it on both sets
fit_and_score
python
scikit-learn/scikit-learn
examples/linear_model/plot_sgd_early_stopping.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/linear_model/plot_sgd_early_stopping.py
BSD-3-Clause
def load_mtpl2(n_samples=None): """Fetch the French Motor Third-Party Liability Claims dataset. Parameters ---------- n_samples: int, default=None number of samples to select (for faster run time). Full dataset has 678013 samples. """ # freMTPL2freq dataset from https://www.openml.o...
Fetch the French Motor Third-Party Liability Claims dataset. Parameters ---------- n_samples: int, default=None number of samples to select (for faster run time). Full dataset has 678013 samples.
load_mtpl2
python
scikit-learn/scikit-learn
examples/linear_model/plot_tweedie_regression_insurance_claims.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/linear_model/plot_tweedie_regression_insurance_claims.py
BSD-3-Clause
def plot_obs_pred( df, feature, weight, observed, predicted, y_label=None, title=None, ax=None, fill_legend=False, ): """Plot observed and predicted - aggregated per feature level. Parameters ---------- df : DataFrame input data feature: str a col...
Plot observed and predicted - aggregated per feature level. Parameters ---------- df : DataFrame input data feature: str a column name of df for the feature to be plotted weight : str column name of df with the values of weights or exposure observed : str a colum...
plot_obs_pred
python
scikit-learn/scikit-learn
examples/linear_model/plot_tweedie_regression_insurance_claims.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/linear_model/plot_tweedie_regression_insurance_claims.py
BSD-3-Clause
def make_estimator(name, categorical_columns=None, iforest_kw=None, lof_kw=None): """Create an outlier detection estimator based on its name.""" if name == "LOF": outlier_detector = LocalOutlierFactor(**(lof_kw or {})) if categorical_columns is None: preprocessor = RobustScaler() ...
Create an outlier detection estimator based on its name.
make_estimator
python
scikit-learn/scikit-learn
examples/miscellaneous/plot_outlier_detection_bench.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/miscellaneous/plot_outlier_detection_bench.py
BSD-3-Clause
def plot_cv_indices(cv, X, y, group, ax, n_splits, lw=10): """Create a sample plot for indices of a cross-validation object.""" use_groups = "Group" in type(cv).__name__ groups = group if use_groups else None # Generate the training/testing visualizations for each CV split for ii, (tr, tt) in enumer...
Create a sample plot for indices of a cross-validation object.
plot_cv_indices
python
scikit-learn/scikit-learn
examples/model_selection/plot_cv_indices.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/model_selection/plot_cv_indices.py
BSD-3-Clause
def refit_strategy(cv_results): """Define the strategy to select the best estimator. The strategy defined here is to filter-out all results below a precision threshold of 0.98, rank the remaining by recall and keep all models with one standard deviation of the best by recall. Once these models are sele...
Define the strategy to select the best estimator. The strategy defined here is to filter-out all results below a precision threshold of 0.98, rank the remaining by recall and keep all models with one standard deviation of the best by recall. Once these models are selected, we can select the fastest mod...
refit_strategy
python
scikit-learn/scikit-learn
examples/model_selection/plot_grid_search_digits.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/model_selection/plot_grid_search_digits.py
BSD-3-Clause
def lower_bound(cv_results): """ Calculate the lower bound within 1 standard deviation of the best `mean_test_scores`. Parameters ---------- cv_results : dict of numpy(masked) ndarrays See attribute cv_results_ of `GridSearchCV` Returns ------- float Lower bound wit...
Calculate the lower bound within 1 standard deviation of the best `mean_test_scores`. Parameters ---------- cv_results : dict of numpy(masked) ndarrays See attribute cv_results_ of `GridSearchCV` Returns ------- float Lower bound within 1 standard deviation of the ...
lower_bound
python
scikit-learn/scikit-learn
examples/model_selection/plot_grid_search_refit_callable.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/model_selection/plot_grid_search_refit_callable.py
BSD-3-Clause
def best_low_complexity(cv_results): """ Balance model complexity with cross-validated score. Parameters ---------- cv_results : dict of numpy(masked) ndarrays See attribute cv_results_ of `GridSearchCV`. Return ------ int Index of a model that has the fewest PCA compon...
Balance model complexity with cross-validated score. Parameters ---------- cv_results : dict of numpy(masked) ndarrays See attribute cv_results_ of `GridSearchCV`. Return ------ int Index of a model that has the fewest PCA components while has its test score within...
best_low_complexity
python
scikit-learn/scikit-learn
examples/model_selection/plot_grid_search_refit_callable.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/model_selection/plot_grid_search_refit_callable.py
BSD-3-Clause
def corrected_std(differences, n_train, n_test): """Corrects standard deviation using Nadeau and Bengio's approach. Parameters ---------- differences : ndarray of shape (n_samples,) Vector containing the differences in the score metrics of two models. n_train : int Number of samples...
Corrects standard deviation using Nadeau and Bengio's approach. Parameters ---------- differences : ndarray of shape (n_samples,) Vector containing the differences in the score metrics of two models. n_train : int Number of samples in the training set. n_test : int Number of...
corrected_std
python
scikit-learn/scikit-learn
examples/model_selection/plot_grid_search_stats.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/model_selection/plot_grid_search_stats.py
BSD-3-Clause
def compute_corrected_ttest(differences, df, n_train, n_test): """Computes right-tailed paired t-test with corrected variance. Parameters ---------- differences : array-like of shape (n_samples,) Vector containing the differences in the score metrics of two models. df : int Degrees ...
Computes right-tailed paired t-test with corrected variance. Parameters ---------- differences : array-like of shape (n_samples,) Vector containing the differences in the score metrics of two models. df : int Degrees of freedom. n_train : int Number of samples in the trainin...
compute_corrected_ttest
python
scikit-learn/scikit-learn
examples/model_selection/plot_grid_search_stats.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/model_selection/plot_grid_search_stats.py
BSD-3-Clause
def load_mnist(n_samples): """Load MNIST, shuffle the data, and return only n_samples.""" mnist = fetch_openml("mnist_784", as_frame=False) X, y = shuffle(mnist.data, mnist.target, random_state=2) return X[:n_samples] / 255, y[:n_samples]
Load MNIST, shuffle the data, and return only n_samples.
load_mnist
python
scikit-learn/scikit-learn
examples/neighbors/approximate_nearest_neighbors.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/neighbors/approximate_nearest_neighbors.py
BSD-3-Clause
def nudge_dataset(X, Y): """ This produces a dataset 5 times bigger than the original one, by moving the 8x8 images in X around by 1px to left, right, down, up """ direction_vectors = [ [[0, 1, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [1, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 1...
This produces a dataset 5 times bigger than the original one, by moving the 8x8 images in X around by 1px to left, right, down, up
nudge_dataset
python
scikit-learn/scikit-learn
examples/neural_networks/plot_rbm_logistic_classification.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/neural_networks/plot_rbm_logistic_classification.py
BSD-3-Clause
def levenshtein_distance(x, y): """Return the Levenshtein distance between two strings.""" if x == "" or y == "": return max(len(x), len(y)) if x[0] == y[0]: return levenshtein_distance(x[1:], y[1:]) return 1 + min( levenshtein_distance(x[1:], y), levenshtein_distance(x, ...
Return the Levenshtein distance between two strings.
levenshtein_distance
python
scikit-learn/scikit-learn
examples/release_highlights/plot_release_highlights_1_5_0.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/release_highlights/plot_release_highlights_1_5_0.py
BSD-3-Clause
def plot_decision_function(classifier, sample_weight, axis, title): """Plot the synthetic data and the classifier decision function. Points with larger sample_weight are mapped to larger circles in the scatter plot.""" axis.scatter( X_plot[:, 0], X_plot[:, 1], c=y_plot, s=100...
Plot the synthetic data and the classifier decision function. Points with larger sample_weight are mapped to larger circles in the scatter plot.
plot_decision_function
python
scikit-learn/scikit-learn
examples/svm/plot_weighted_samples.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/svm/plot_weighted_samples.py
BSD-3-Clause
def load_dataset(verbose=False, remove=()): """Load and vectorize the 20 newsgroups dataset.""" data_train = fetch_20newsgroups( subset="train", categories=categories, shuffle=True, random_state=42, remove=remove, ) data_test = fetch_20newsgroups( subset...
Load and vectorize the 20 newsgroups dataset.
load_dataset
python
scikit-learn/scikit-learn
examples/text/plot_document_classification_20newsgroups.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/text/plot_document_classification_20newsgroups.py
BSD-3-Clause
def token_freqs(doc): """Extract a dict mapping tokens from doc to their occurrences.""" freq = defaultdict(int) for tok in tokenize(doc): freq[tok] += 1 return freq
Extract a dict mapping tokens from doc to their occurrences.
token_freqs
python
scikit-learn/scikit-learn
examples/text/plot_hashing_vs_dict_vectorizer.py
https://github.com/scikit-learn/scikit-learn/blob/master/examples/text/plot_hashing_vs_dict_vectorizer.py
BSD-3-Clause
def clone(estimator, *, safe=True): """Construct a new unfitted estimator with the same parameters. Clone does a deep copy of the model in an estimator without actually copying attached data. It returns a new estimator with the same parameters that has not been fitted on any data. .. versionchange...
Construct a new unfitted estimator with the same parameters. Clone does a deep copy of the model in an estimator without actually copying attached data. It returns a new estimator with the same parameters that has not been fitted on any data. .. versionchanged:: 1.3 Delegates to `estimator.__s...
clone
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def _clone_parametrized(estimator, *, safe=True): """Default implementation of clone. See :func:`sklearn.base.clone` for details.""" estimator_type = type(estimator) if estimator_type is dict: return {k: clone(v, safe=safe) for k, v in estimator.items()} elif estimator_type in (list, tuple, set...
Default implementation of clone. See :func:`sklearn.base.clone` for details.
_clone_parametrized
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, "deprecated_original", cls.__init__) if init is object.__init__: # No explicit ...
Get parameter names for the estimator
_get_param_names
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def get_params(self, deep=True): """ Get parameters for this estimator. Parameters ---------- deep : bool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- ...
Get parameters for this estimator. Parameters ---------- deep : bool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : dict Parameter n...
get_params
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def _get_params_html(self, deep=True): """ Get parameters for this estimator with a specific HTML representation. Parameters ---------- deep : bool, default=True If True, will return the parameters for this estimator and contained subobjects that are esti...
Get parameters for this estimator with a specific HTML representation. Parameters ---------- deep : bool, default=True If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- p...
_get_params_html
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def is_non_default(param_name, param_value): """Finds the parameters that have been set by the user.""" if param_name not in init_default_params: # happens if k is part of a **kwargs return True if init_default_params[param_name] == inspect._empty: ...
Finds the parameters that have been set by the user.
is_non_default
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def set_params(self, **params): """Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as :class:`~sklearn.pipeline.Pipeline`). The latter have parameters of the form ``<component>__<parameter>`` so that it's possible to...
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as :class:`~sklearn.pipeline.Pipeline`). The latter have parameters of the form ``<component>__<parameter>`` so that it's possible to update each component of a nested object. ...
set_params
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def _validate_params(self): """Validate types and values of constructor parameters The expected type and values must be defined in the `_parameter_constraints` class attribute, which is a dictionary `param_name: list of constraints`. See the docstring of `validate_parameter_constraints`...
Validate types and values of constructor parameters The expected type and values must be defined in the `_parameter_constraints` class attribute, which is a dictionary `param_name: list of constraints`. See the docstring of `validate_parameter_constraints` for a description of the accep...
_validate_params
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def score(self, X, y, sample_weight=None): """ Return :ref:`accuracy <accuracy_score>` on provided data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. ...
Return :ref:`accuracy <accuracy_score>` on provided data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters ---------- X : array...
score
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def score(self, X, y, sample_weight=None): """Return :ref:`coefficient of determination <r2_score>` on test data. The coefficient of determination, :math:`R^2`, is defined as :math:`(1 - \\frac{u}{v})`, where :math:`u` is the residual sum of squares ``((y_true - y_pred)** 2).sum()`` and...
Return :ref:`coefficient of determination <r2_score>` on test data. The coefficient of determination, :math:`R^2`, is defined as :math:`(1 - \frac{u}{v})`, where :math:`u` is the residual sum of squares ``((y_true - y_pred)** 2).sum()`` and :math:`v` is the total sum of squares ``((y_tr...
score
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def fit_predict(self, X, y=None, **kwargs): """ Perform clustering on `X` and returns cluster labels. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : Ignored Not used, present for API consistency by conventio...
Perform clustering on `X` and returns cluster labels. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : Ignored Not used, present for API consistency by convention. **kwargs : dict Arguments to be...
fit_predict
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def get_indices(self, i): """Row and column indices of the `i`'th bicluster. Only works if ``rows_`` and ``columns_`` attributes exist. Parameters ---------- i : int The index of the cluster. Returns ------- row_ind : ndarray, dtype=np.intp ...
Row and column indices of the `i`'th bicluster. Only works if ``rows_`` and ``columns_`` attributes exist. Parameters ---------- i : int The index of the cluster. Returns ------- row_ind : ndarray, dtype=np.intp Indices of rows in the da...
get_indices
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def get_shape(self, i): """Shape of the `i`'th bicluster. Parameters ---------- i : int The index of the cluster. Returns ------- n_rows : int Number of rows in the bicluster. n_cols : int Number of columns in the bic...
Shape of the `i`'th bicluster. Parameters ---------- i : int The index of the cluster. Returns ------- n_rows : int Number of rows in the bicluster. n_cols : int Number of columns in the bicluster.
get_shape
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def get_submatrix(self, i, data): """Return the submatrix corresponding to bicluster `i`. Parameters ---------- i : int The index of the cluster. data : array-like of shape (n_samples, n_features) The data. Returns ------- submatr...
Return the submatrix corresponding to bicluster `i`. Parameters ---------- i : int The index of the cluster. data : array-like of shape (n_samples, n_features) The data. Returns ------- submatrix : ndarray of shape (n_rows, n_cols) ...
get_submatrix
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def fit_transform(self, X, y=None, **fit_params): """ Fit to data, then transform it. Fits transformer to `X` and `y` with optional parameters `fit_params` and returns a transformed version of `X`. Parameters ---------- X : array-like of shape (n_samples, n_feat...
Fit to data, then transform it. Fits transformer to `X` and `y` with optional parameters `fit_params` and returns a transformed version of `X`. Parameters ---------- X : array-like of shape (n_samples, n_features) Input samples. y : array-like of ...
fit_transform
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def get_feature_names_out(self, input_features=None): """Get output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Input features. - If `input_features` is `None`, then `feature_names_in_` is ...
Get output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Input features. - If `input_features` is `None`, then `feature_names_in_` is used as feature names in. If `feature_names_in_` is not...
get_feature_names_out
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def get_feature_names_out(self, input_features=None): """Get output feature names for transformation. The feature names out will prefixed by the lowercased class name. For example, if the transformer outputs 3 features, then the feature names out are: `["class_name0", "class_name1", "cl...
Get output feature names for transformation. The feature names out will prefixed by the lowercased class name. For example, if the transformer outputs 3 features, then the feature names out are: `["class_name0", "class_name1", "class_name2"]`. Parameters ---------- inpu...
get_feature_names_out
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def fit_predict(self, X, y=None, **kwargs): """Perform fit on X and returns labels for X. Returns -1 for outliers and 1 for inliers. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. y : Ignored ...
Perform fit on X and returns labels for X. Returns -1 for outliers and 1 for inliers. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. y : Ignored Not used, present for API consistency by conventi...
fit_predict
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def is_classifier(estimator): """Return True if the given estimator is (probably) a classifier. Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a classifier and False otherwise. Examples -------- ...
Return True if the given estimator is (probably) a classifier. Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a classifier and False otherwise. Examples -------- >>> from sklearn.base import is_cla...
is_classifier
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def is_regressor(estimator): """Return True if the given estimator is (probably) a regressor. Parameters ---------- estimator : estimator instance Estimator object to test. Returns ------- out : bool True if estimator is a regressor and False otherwise. Examples --...
Return True if the given estimator is (probably) a regressor. Parameters ---------- estimator : estimator instance Estimator object to test. Returns ------- out : bool True if estimator is a regressor and False otherwise. Examples -------- >>> from sklearn.base imp...
is_regressor
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def is_clusterer(estimator): """Return True if the given estimator is (probably) a clusterer. .. versionadded:: 1.6 Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a clusterer and False otherwise. ...
Return True if the given estimator is (probably) a clusterer. .. versionadded:: 1.6 Parameters ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a clusterer and False otherwise. Examples -------- >>> from s...
is_clusterer
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def is_outlier_detector(estimator): """Return True if the given estimator is (probably) an outlier detector. Parameters ---------- estimator : estimator instance Estimator object to test. Returns ------- out : bool True if estimator is an outlier detector and False otherwis...
Return True if the given estimator is (probably) an outlier detector. Parameters ---------- estimator : estimator instance Estimator object to test. Returns ------- out : bool True if estimator is an outlier detector and False otherwise.
is_outlier_detector
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def _fit_context(*, prefer_skip_nested_validation): """Decorator to run the fit methods of estimators within context managers. Parameters ---------- prefer_skip_nested_validation : bool If True, the validation of parameters of inner estimators or functions called during fit will be skip...
Decorator to run the fit methods of estimators within context managers. Parameters ---------- prefer_skip_nested_validation : bool If True, the validation of parameters of inner estimators or functions called during fit will be skipped. This is useful to avoid validating many times...
_fit_context
python
scikit-learn/scikit-learn
sklearn/base.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py
BSD-3-Clause
def _get_estimator(self): """Resolve which estimator to return (default is LinearSVC)""" if self.estimator is None: # we want all classifiers that don't expose a random_state # to be deterministic (and we don't want to expose this one). estimator = LinearSVC(random_st...
Resolve which estimator to return (default is LinearSVC)
_get_estimator
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None, **fit_params): """Fit the calibrated model. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) Target values. sample_weight : array-li...
Fit the calibrated model. Parameters ---------- X : array-like of shape (n_samples, n_features) Training data. y : array-like of shape (n_samples,) Target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights....
fit
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def predict_proba(self, X): """Calibrated probabilities of classification. This function returns calibrated probabilities of classification according to each class on an array of test vectors X. Parameters ---------- X : array-like of shape (n_samples, n_features) ...
Calibrated probabilities of classification. This function returns calibrated probabilities of classification according to each class on an array of test vectors X. Parameters ---------- X : array-like of shape (n_samples, n_features) The samples, as accepted by `est...
predict_proba
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def predict(self, X): """Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier. Parameters ---------- X : array-like of shape (n_samples, n_featu...
Predict the target of new samples. The predicted class is the class that has the highest probability, and can thus be different from the prediction of the uncalibrated classifier. Parameters ---------- X : array-like of shape (n_samples, n_features) The samples, as ...
predict
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def get_metadata_routing(self): """Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` e...
Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing informatio...
get_metadata_routing
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def _fit_classifier_calibrator_pair( estimator, X, y, train, test, method, classes, sample_weight=None, fit_params=None, ): """Fit a classifier/calibration pair on a given train/test split. Fit the classifier on the train set, compute its predictions on the test set and ...
Fit a classifier/calibration pair on a given train/test split. Fit the classifier on the train set, compute its predictions on the test set and use the predictions as input to fit the calibrator along with the test labels. Parameters ---------- estimator : estimator instance Cloned bas...
_fit_classifier_calibrator_pair
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def _fit_calibrator(clf, predictions, y, classes, method, sample_weight=None): """Fit calibrator(s) and return a `_CalibratedClassifier` instance. `n_classes` (i.e. `len(clf.classes_)`) calibrators are fitted. However, if `n_classes` equals 2, one calibrator is fitted. Parameters ---------- ...
Fit calibrator(s) and return a `_CalibratedClassifier` instance. `n_classes` (i.e. `len(clf.classes_)`) calibrators are fitted. However, if `n_classes` equals 2, one calibrator is fitted. Parameters ---------- clf : estimator instance Fitted classifier. predictions : array-like, s...
_fit_calibrator
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def predict_proba(self, X): """Calculate calibrated probabilities. Calculates classification calibrated probabilities for each class, in a one-vs-all manner, for `X`. Parameters ---------- X : ndarray of shape (n_samples, n_features) The sample data. ...
Calculate calibrated probabilities. Calculates classification calibrated probabilities for each class, in a one-vs-all manner, for `X`. Parameters ---------- X : ndarray of shape (n_samples, n_features) The sample data. Returns ------- proba...
predict_proba
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def _sigmoid_calibration( predictions, y, sample_weight=None, max_abs_prediction_threshold=30 ): """Probability Calibration with sigmoid method (Platt 2000) Parameters ---------- predictions : ndarray of shape (n_samples,) The decision function or predict proba for the samples. y : nda...
Probability Calibration with sigmoid method (Platt 2000) Parameters ---------- predictions : ndarray of shape (n_samples,) The decision function or predict proba for the samples. y : ndarray of shape (n_samples,) The targets. sample_weight : array-like of shape (n_samples,), defau...
_sigmoid_calibration
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def fit(self, X, y, sample_weight=None): """Fit the model using X, y as training data. Parameters ---------- X : array-like of shape (n_samples,) Training data. y : array-like of shape (n_samples,) Training target. sample_weight : array-like of ...
Fit the model using X, y as training data. Parameters ---------- X : array-like of shape (n_samples,) Training data. y : array-like of shape (n_samples,) Training target. sample_weight : array-like of shape (n_samples,), default=None Sample ...
fit
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def predict(self, T): """Predict new data by linear interpolation. Parameters ---------- T : array-like of shape (n_samples,) Data to predict from. Returns ------- T_ : ndarray of shape (n_samples,) The predicted data. """ ...
Predict new data by linear interpolation. Parameters ---------- T : array-like of shape (n_samples,) Data to predict from. Returns ------- T_ : ndarray of shape (n_samples,) The predicted data.
predict
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def calibration_curve( y_true, y_prob, *, pos_label=None, n_bins=5, strategy="uniform", ): """Compute true and predicted probabilities for a calibration curve. The method assumes the inputs come from a binary classifier, and discretize the [0, 1] interval into bins. Calibration...
Compute true and predicted probabilities for a calibration curve. The method assumes the inputs come from a binary classifier, and discretize the [0, 1] interval into bins. Calibration curves may also be referred to as reliability diagrams. Read more in the :ref:`User Guide <calibration>`. Param...
calibration_curve
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def plot(self, *, ax=None, name=None, ref_line=True, **kwargs): """Plot visualization. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Parameters ---------- ax : Matplotlib Axes, default=None Axes object to plot on. If `None`, a new...
Plot visualization. Extra keyword arguments will be passed to :func:`matplotlib.pyplot.plot`. Parameters ---------- ax : Matplotlib Axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None ...
plot
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def from_estimator( cls, estimator, X, y, *, n_bins=5, strategy="uniform", pos_label=None, name=None, ax=None, ref_line=True, **kwargs, ): """Plot calibration curve using a binary classifier and data. A ...
Plot calibration curve using a binary classifier and data. A calibration curve, also known as a reliability diagram, uses inputs from a binary classifier and plots the average predicted probability for each bin against the fraction of positive classes, on the y-axis. Extra keyw...
from_estimator
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def from_predictions( cls, y_true, y_prob, *, n_bins=5, strategy="uniform", pos_label=None, name=None, ax=None, ref_line=True, **kwargs, ): """Plot calibration curve using true labels and predicted probabilities. ...
Plot calibration curve using true labels and predicted probabilities. Calibration curve, also known as reliability diagram, uses inputs from a binary classifier and plots the average predicted probability for each bin against the fraction of positive classes, on the y-axis. Ext...
from_predictions
python
scikit-learn/scikit-learn
sklearn/calibration.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/calibration.py
BSD-3-Clause
def _fetch_fixture(f): """Fetch dataset (download if missing and requested by environment).""" download_if_missing = environ.get("SKLEARN_SKIP_NETWORK_TESTS", "1") == "0" @wraps(f) def wrapped(*args, **kwargs): kwargs["download_if_missing"] = download_if_missing try: return ...
Fetch dataset (download if missing and requested by environment).
_fetch_fixture
python
scikit-learn/scikit-learn
sklearn/conftest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/conftest.py
BSD-3-Clause
def pyplot(): """Setup and teardown fixture for matplotlib. This fixture checks if we can import matplotlib. If not, the tests will be skipped. Otherwise, we close the figures before and after running the functions. Returns ------- pyplot : module The ``matplotlib.pyplot`` module. ...
Setup and teardown fixture for matplotlib. This fixture checks if we can import matplotlib. If not, the tests will be skipped. Otherwise, we close the figures before and after running the functions. Returns ------- pyplot : module The ``matplotlib.pyplot`` module.
pyplot
python
scikit-learn/scikit-learn
sklearn/conftest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/conftest.py
BSD-3-Clause
def pytest_generate_tests(metafunc): """Parametrization of global_random_seed fixture based on the SKLEARN_TESTS_GLOBAL_RANDOM_SEED environment variable. The goal of this fixture is to prevent tests that use it to be sensitive to a specific seed value while still being deterministic by default. S...
Parametrization of global_random_seed fixture based on the SKLEARN_TESTS_GLOBAL_RANDOM_SEED environment variable. The goal of this fixture is to prevent tests that use it to be sensitive to a specific seed value while still being deterministic by default. See the documentation for the SKLEARN_TESTS_G...
pytest_generate_tests
python
scikit-learn/scikit-learn
sklearn/conftest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/conftest.py
BSD-3-Clause
def print_changed_only_false(): """Set `print_changed_only` to False for the duration of the test.""" set_config(print_changed_only=False) yield set_config(print_changed_only=True) # reset to default
Set `print_changed_only` to False for the duration of the test.
print_changed_only_false
python
scikit-learn/scikit-learn
sklearn/conftest.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/conftest.py
BSD-3-Clause
def _cov(X, shrinkage=None, covariance_estimator=None): """Estimate covariance matrix (using optional covariance_estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. shrinkage : {'empirical', 'auto'} or float, default=None Shrinkage parameter...
Estimate covariance matrix (using optional covariance_estimator). Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. shrinkage : {'empirical', 'auto'} or float, default=None Shrinkage parameter, possible values: - None or 'empirical': no shrinkag...
_cov
python
scikit-learn/scikit-learn
sklearn/discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/discriminant_analysis.py
BSD-3-Clause
def _class_means(X, y): """Compute class means. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Returns ------- means : array-like of shape (n_classes, n_fea...
Compute class means. Parameters ---------- X : array-like of shape (n_samples, n_features) Input data. y : array-like of shape (n_samples,) or (n_samples, n_targets) Target values. Returns ------- means : array-like of shape (n_classes, n_features) Class means. ...
_class_means
python
scikit-learn/scikit-learn
sklearn/discriminant_analysis.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/discriminant_analysis.py
BSD-3-Clause