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 _predict_log_proba(cls, instance, estimator, n_classes):
"""Private function used to compute log probabilities within a job."""
if not hasattr(estimator, "predict_log_proba"):
return np.log(cls._predict_proba(instance, estimator, n_classes))
n_samples = instance.shape[0]
... | Private function used to compute log probabilities within a job. | _predict_log_proba | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def fit(self, X, y=None, sample_weight=None, session=None, run_kwargs=None):
"""
Build a Bagging ensemble of estimators from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sp... |
Build a Bagging ensemble of estimators from the training set (X, y).
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.... | fit | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def predict(self, X, session=None, run_kwargs=None):
"""
Predict class for X.
The predicted class of an input sample is computed as the class with
the highest mean predicted probability. If base estimators do not
implement a ``predict_proba`` method, then it resorts to voting.
... |
Predict class for X.
The predicted class of an input sample is computed as the class with
the highest mean predicted probability. If base estimators do not
implement a ``predict_proba`` method, then it resorts to voting.
Parameters
----------
X : {array-like, s... | predict | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def predict_proba(self, X, session=None, run_kwargs=None):
"""
Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the mean predicted class probabilities of the base estimators in the
ensemble. If base estimators do not implemen... |
Predict class probabilities for X.
The predicted class probabilities of an input sample is computed as
the mean predicted class probabilities of the base estimators in the
ensemble. If base estimators do not implement a ``predict_proba``
method, then it resorts to voting and th... | predict_proba | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def predict_log_proba(self, X, session=None, run_kwargs=None):
"""
Predict class log-probabilities for X.
The predicted class log-probabilities of an input sample is computed as
the log of the mean predicted class probabilities of the base
estimators in the ensemble.
Pa... |
Predict class log-probabilities for X.
The predicted class log-probabilities of an input sample is computed as
the log of the mean predicted class probabilities of the base
estimators in the ensemble.
Parameters
----------
X : {array-like, sparse matrix} of sha... | predict_log_proba | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def decision_function(self, X, session=None, run_kwargs=None):
"""
Average of the decision functions of the base classifiers.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accept... |
Average of the decision functions of the base classifiers.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Sparse matrices are accepted only if
they are supported by the base estimator.
... | decision_function | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def predict(self, X, session=None, run_kwargs=None):
"""
Predict regression target for X.
The predicted regression target of an input sample is computed as the
mean predicted regression targets of the estimators in the ensemble.
Parameters
----------
X : {array-... |
Predict regression target for X.
The predicted regression target of an input sample is computed as the
mean predicted regression targets of the estimators in the ensemble.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
... | predict | python | mars-project/mars | mars/learn/ensemble/_bagging.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_bagging.py | Apache-2.0 |
def _average_path_length(n_samples_leaf):
"""
The average path length in a n_samples iTree, which is equal to
the average path length of an unsuccessful BST search since the
latter has the same structure as an isolation tree.
Parameters
----------
n_samples_leaf : array-like of shape (n_samp... |
The average path length in a n_samples iTree, which is equal to
the average path length of an unsuccessful BST search since the
latter has the same structure as an isolation tree.
Parameters
----------
n_samples_leaf : array-like of shape (n_samples,)
The number of training samples in e... | _average_path_length | python | mars-project/mars | mars/learn/ensemble/_iforest.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_iforest.py | Apache-2.0 |
def fit(
self, X, y=None, sample_weight=None, session=None, run_kwargs=None
) -> "IsolationForest":
"""
Fit estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Use ``dtype=np.float32`` for m... |
Fit estimator.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Use ``dtype=np.float32`` for maximum
efficiency. Sparse matrices are also supported, use sparse
``csc_matrix`` for maximum effici... | fit | python | mars-project/mars | mars/learn/ensemble/_iforest.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_iforest.py | Apache-2.0 |
def predict(self, X, session=None, run_kwargs=None):
"""
Predict if a particular sample is an outlier or not.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
``d... |
Predict if a particular sample is an outlier or not.
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
... | predict | python | mars-project/mars | mars/learn/ensemble/_iforest.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_iforest.py | Apache-2.0 |
def decision_function(self, X, session=None, run_kwargs=None):
"""
Average anomaly score of X of the base classifiers.
The anomaly score of an input sample is computed as
the mean anomaly score of the trees in the forest.
The measure of normality of an observation given a tree ... |
Average anomaly score of X of the base classifiers.
The anomaly score of an input sample is computed as
the mean anomaly score of the trees in the forest.
The measure of normality of an observation given a tree is the depth
of the leaf containing this observation, which is equ... | decision_function | python | mars-project/mars | mars/learn/ensemble/_iforest.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_iforest.py | Apache-2.0 |
def score_samples(self, X, session=None, run_kwargs=None):
"""
Opposite of the anomaly score defined in the original paper.
The anomaly score of an input sample is computed as
the mean anomaly score of the trees in the forest.
The measure of normality of an observation given a ... |
Opposite of the anomaly score defined in the original paper.
The anomaly score of an input sample is computed as
the mean anomaly score of the trees in the forest.
The measure of normality of an observation given a tree is the depth
of the leaf containing this observation, whi... | score_samples | python | mars-project/mars | mars/learn/ensemble/_iforest.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/_iforest.py | Apache-2.0 |
def test_iforest_error():
"""Test that it gives proper exception on deficient input."""
iris = load_iris()
X = iris.data
# Test max_samples
with pytest.raises(ValueError):
IsolationForest(max_samples=-1).fit(X)
with pytest.raises(ValueError):
IsolationForest(max_samples=0.0).fit... | Test that it gives proper exception on deficient input. | test_iforest_error | python | mars-project/mars | mars/learn/ensemble/tests/test_iforest.py | https://github.com/mars-project/mars/blob/master/mars/learn/ensemble/tests/test_iforest.py | Apache-2.0 |
def fit(self, X, y):
"""
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 f... |
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... | fit | python | mars-project/mars | mars/learn/glm/_logistic.py | https://github.com/mars-project/mars/blob/master/mars/learn/glm/_logistic.py | Apache-2.0 |
def predict_proba(self, X):
"""
Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
For a multi_class problem, if multi_class is set to be "multinomial"
the softmax function is used to find the predicted probability of
... |
Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
For a multi_class problem, if multi_class is set to be "multinomial"
the softmax function is used to find the predicted probability of
each class.
Else use a one-... | predict_proba | python | mars-project/mars | mars/learn/glm/_logistic.py | https://github.com/mars-project/mars/blob/master/mars/learn/glm/_logistic.py | Apache-2.0 |
def _preprocess_data(
X,
y,
fit_intercept,
normalize=False,
copy=True,
sample_weight=None,
return_mean=False,
check_input=True,
):
"""Center and scale data.
Centers data to have mean zero along axis 0. If fit_intercept=False or if
the X is a sparse matrix, no centering is do... | Center and scale data.
Centers data to have mean zero along axis 0. If fit_intercept=False or if
the X is a sparse matrix, no centering is done, but normalization can still
be applied. The function returns the statistics necessary to reconstruct
the input data, which are X_offset, y_offset, X_scale, su... | _preprocess_data | python | mars-project/mars | mars/learn/linear_model/_base.py | https://github.com/mars-project/mars/blob/master/mars/learn/linear_model/_base.py | Apache-2.0 |
def _rescale_data(X, y, sample_weight):
"""Rescale data sample-wise by square root of sample_weight.
For many linear models, this enables easy support for sample_weight.
Returns
-------
X_rescaled : {array-like, sparse matrix}
y_rescaled : {array-like, sparse matrix}
"""
n_samples = X... | Rescale data sample-wise by square root of sample_weight.
For many linear models, this enables easy support for sample_weight.
Returns
-------
X_rescaled : {array-like, sparse matrix}
y_rescaled : {array-like, sparse matrix}
| _rescale_data | python | mars-project/mars | mars/learn/linear_model/_base.py | https://github.com/mars-project/mars/blob/master/mars/learn/linear_model/_base.py | Apache-2.0 |
def fit(self, X, y, sample_weight=None):
"""
Fit linear model.
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. Wil... |
Fit linear model.
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. Will be cast to X's dtype if necessary.
sample... | fit | python | mars-project/mars | mars/learn/linear_model/_base.py | https://github.com/mars-project/mars/blob/master/mars/learn/linear_model/_base.py | Apache-2.0 |
def decision_function(self, X):
"""
Predict confidence scores for samples.
The confidence score for a sample is proportional to the signed
distance of that sample to the hyperplane.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_featu... |
Predict confidence scores for samples.
The confidence score for a sample is proportional to the signed
distance of that sample to the hyperplane.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
... | decision_function | python | mars-project/mars | mars/learn/linear_model/_base.py | https://github.com/mars-project/mars/blob/master/mars/learn/linear_model/_base.py | Apache-2.0 |
def predict(self, X):
"""
Predict class labels for samples in X.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
-------
C : array, shape [n_samples]
Predicted class label per ... |
Predict class labels for samples in X.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features)
Samples.
Returns
-------
C : array, shape [n_samples]
Predicted class label per sample.
| predict | python | mars-project/mars | mars/learn/linear_model/_base.py | https://github.com/mars-project/mars/blob/master/mars/learn/linear_model/_base.py | Apache-2.0 |
def _check_targets(y_true, y_pred):
"""Check that y_true and y_pred belong to the same classification task
This converts multiclass or binary types to a common shape, and raises a
ValueError for a mix of multilabel and multiclass targets, a mix of
multilabel formats, for the presence of continuous-valu... | Check that y_true and y_pred belong to the same classification task
This converts multiclass or binary types to a common shape, and raises a
ValueError for a mix of multilabel and multiclass targets, a mix of
multilabel formats, for the presence of continuous-valued or multioutput
targets, or for targe... | _check_targets | python | mars-project/mars | mars/learn/metrics/_check_targets.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_check_targets.py | Apache-2.0 |
def accuracy_score(
y_true, y_pred, normalize=True, sample_weight=None, session=None, run_kwargs=None
):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of lab... | Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Read more in the :ref:`User Guide <accuracy_score>`.
Parameters
----------
y_true :... | accuracy_score | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def log_loss(
y_true, y_pred, *, eps=1e-15, normalize=True, sample_weight=None, labels=None
):
r"""Log loss, aka logistic loss or cross-entropy loss.
This is the loss function used in (multinomial) logistic regression
and extensions of it such as neural networks, defined as the negative
log-likelih... | Log loss, aka logistic loss or cross-entropy loss.
This is the loss function used in (multinomial) logistic regression
and extensions of it such as neural networks, defined as the negative
log-likelihood of a logistic model that returns ``y_pred`` probabilities
for its training data ``y_true``.
The... | log_loss | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def multilabel_confusion_matrix(
y_true,
y_pred,
*,
sample_weight=None,
labels=None,
samplewise=False,
session=None,
run_kwargs=None
):
"""
Compute a confusion matrix for each class or sample.
Compute class-wise (default) or sample-wise (samplewise=True) multilabel
confu... |
Compute a confusion matrix for each class or sample.
Compute class-wise (default) or sample-wise (samplewise=True) multilabel
confusion matrix to evaluate the accuracy of a classification, and output
confusion matrices for each class or sample.
In multilabel confusion matrix :math:`MCM`, the coun... | multilabel_confusion_matrix | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def _prf_divide(
numerator, denominator, metric, modifier, average, warn_for, zero_division="warn"
): # pragma: no cover
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements equal to
0 or 1 (according to ``zero_division``). Plus, if
``zero_divis... | Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements equal to
0 or 1 (according to ``zero_division``). Plus, if
``zero_division != "warn"`` raises a warning.
The metric, modifier and average arguments are used only for determining
an appropriate wa... | _prf_divide | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def _check_set_wise_labels(
y_true, y_pred, average, labels, pos_label, session=None, run_kwargs=None
): # pragma: no cover
"""Validation associated with set-wise metrics
Returns identified labels
"""
exec_kwargs = dict(session=session, **(run_kwargs or dict()))
average_options = (None, "micro... | Validation associated with set-wise metrics
Returns identified labels
| _check_set_wise_labels | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def precision_recall_fscore_support(
y_true,
y_pred,
*,
beta=1.0,
labels=None,
pos_label=1,
average=None,
warn_for=("precision", "recall", "f-score"),
sample_weight=None,
zero_division="warn",
session=None,
run_kwargs=None
):
"""Compute precision, recall, F-measure an... | Compute precision, recall, F-measure and support for each class
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample
that is negat... | precision_recall_fscore_support | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def precision_score(
y_true,
y_pred,
*,
labels=None,
pos_label=1,
average="binary",
sample_weight=None,
zero_division="warn"
):
"""Compute the precision
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false ... | Compute the precision
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample
that is negative.
The best value is 1 and the wors... | precision_score | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def recall_score(
y_true,
y_pred,
*,
labels=None,
pos_label=1,
average="binary",
sample_weight=None,
zero_division="warn"
):
"""Compute the recall
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives... | Compute the recall
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Read more in... | recall_score | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def f1_score(
y_true,
y_pred,
*,
labels=None,
pos_label=1,
average="binary",
sample_weight=None,
zero_division="warn"
):
"""Compute the F1 score, also known as balanced F-score or F-measure
The F1 score can be interpreted as a weighted average of the precision and
recall, wh... | Compute the F1 score, also known as balanced F-score or F-measure
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formu... | f1_score | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def fbeta_score(
y_true,
y_pred,
*,
beta,
labels=None,
pos_label=1,
average="binary",
sample_weight=None,
zero_division="warn"
):
"""Compute the F-beta score
The F-beta score is the weighted harmonic mean of precision and recall,
reaching its optimal value at 1 and its w... | Compute the F-beta score
The F-beta score is the weighted harmonic mean of precision and recall,
reaching its optimal value at 1 and its worst value at 0.
The `beta` parameter determines the weight of recall in the combined
score. ``beta < 1`` lends more weight to precision, while ``beta > 1``
fav... | fbeta_score | python | mars-project/mars | mars/learn/metrics/_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_classification.py | Apache-2.0 |
def auc(x, y, session=None, run_kwargs=None):
"""Compute Area Under the Curve (AUC) using the trapezoidal rule
This is a general function, given points on a curve. For computing the
area under the ROC-curve, see :func:`roc_auc_score`. For an alternative
way to summarize a precision-recall curve, see
... | Compute Area Under the Curve (AUC) using the trapezoidal rule
This is a general function, given points on a curve. For computing the
area under the ROC-curve, see :func:`roc_auc_score`. For an alternative
way to summarize a precision-recall curve, see
:func:`average_precision_score`.
Parameters
... | auc | python | mars-project/mars | mars/learn/metrics/_ranking.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_ranking.py | Apache-2.0 |
def _binary_clf_curve(
y_true, y_score, pos_label=None, sample_weight=None, session=None, run_kwargs=None
):
"""Calculate true and false positives per binary classification threshold.
Parameters
----------
y_true : tensor, shape = [n_samples]
True targets of binary classification
y_sco... | Calculate true and false positives per binary classification threshold.
Parameters
----------
y_true : tensor, shape = [n_samples]
True targets of binary classification
y_score : tensor, shape = [n_samples]
Estimated probabilities or decision function
pos_label : int or str, defau... | _binary_clf_curve | python | mars-project/mars | mars/learn/metrics/_ranking.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_ranking.py | Apache-2.0 |
def roc_auc_score(
y_true,
y_score,
*,
average="macro",
sample_weight=None,
max_fpr=None,
multi_class="raise",
labels=None,
session=None,
run_kwargs=None,
):
"""
Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC)
from prediction scores.
Note... |
Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC)
from prediction scores.
Note: this implementation can be used with binary, multiclass and
multilabel classification, but some restrictions apply (see Parameters).
Read more in the :ref:`User Guide <roc_metrics>`.
Parame... | roc_auc_score | python | mars-project/mars | mars/learn/metrics/_ranking.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_ranking.py | Apache-2.0 |
def roc_curve(
y_true,
y_score,
pos_label=None,
sample_weight=None,
drop_intermediate=True,
session=None,
run_kwargs=None,
):
"""Compute Receiver operating characteristic (ROC)
Note: this implementation is restricted to the binary classification task.
Read more in the :ref:`Use... | Compute Receiver operating characteristic (ROC)
Note: this implementation is restricted to the binary classification task.
Read more in the :ref:`User Guide <roc_metrics>`.
Parameters
----------
y_true : tensor, shape = [n_samples]
True binary labels. If labels are not either {-1, 1} or ... | roc_curve | python | mars-project/mars | mars/learn/metrics/_ranking.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_ranking.py | Apache-2.0 |
def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"):
"""Check that y_true and y_pred belong to the same regression task.
Parameters
----------
y_true : array-like
y_pred : array-like
multioutput : array-like or string in ['raw_values', uniform_average',
'variance_weig... | Check that y_true and y_pred belong to the same regression task.
Parameters
----------
y_true : array-like
y_pred : array-like
multioutput : array-like or string in ['raw_values', uniform_average',
'variance_weighted'] or None
None is accepted due to backward compatibility of r2_s... | _check_reg_targets | python | mars-project/mars | mars/learn/metrics/_regresssion.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_regresssion.py | Apache-2.0 |
def r2_score(
y_true,
y_pred,
*,
sample_weight=None,
multioutput="uniform_average",
session=None,
run_kwargs=None
):
""":math:`R^2` (coefficient of determination) regression score function.
Best possible score is 1.0 and it can be negative (because the
model can be arbitrarily w... | :math:`R^2` (coefficient of determination) regression score function.
Best possible score is 1.0 and it can be negative (because the
model can be arbitrarily worse). A constant model that always
predicts the expected value of y, disregarding the input features,
would get a :math:`R^2` score of 0.0.
... | r2_score | python | mars-project/mars | mars/learn/metrics/_regresssion.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_regresssion.py | Apache-2.0 |
def get_scorer(score_func: Union[str, Callable], **kwargs) -> Callable:
"""
Get a scorer from string
Parameters
----------
score_func : str | callable
scoring method as string. If callable it is returned as is.
Returns
-------
scorer : callable
The scorer.
"""
i... |
Get a scorer from string
Parameters
----------
score_func : str | callable
scoring method as string. If callable it is returned as is.
Returns
-------
scorer : callable
The scorer.
| get_scorer | python | mars-project/mars | mars/learn/metrics/_scorer.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/_scorer.py | Apache-2.0 |
def _return_float_dtype(X, Y):
"""
1. If dtype of X and Y is float32, then dtype float32 is returned.
2. Else dtype float is returned.
"""
X = astensor(X)
if Y is None:
Y_dtype = X.dtype
else:
Y = astensor(Y)
Y_dtype = Y.dtype... |
1. If dtype of X and Y is float32, then dtype float32 is returned.
2. Else dtype float is returned.
| _return_float_dtype | python | mars-project/mars | mars/learn/metrics/pairwise/core.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/core.py | Apache-2.0 |
def cosine_similarity(X, Y=None, dense_output=True):
"""Compute cosine similarity between samples in X and Y.
Cosine similarity, or the cosine kernel, computes similarity as the
normalized dot product of X and Y:
K(X, Y) = <X, Y> / (||X||*||Y||)
On L2-normalized data, this function is equival... | Compute cosine similarity between samples in X and Y.
Cosine similarity, or the cosine kernel, computes similarity as the
normalized dot product of X and Y:
K(X, Y) = <X, Y> / (||X||*||Y||)
On L2-normalized data, this function is equivalent to linear_kernel.
Read more in the :ref:`User Guide... | cosine_similarity | python | mars-project/mars | mars/learn/metrics/pairwise/cosine.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/cosine.py | Apache-2.0 |
def cosine_distances(X, Y=None):
"""Compute cosine distance between samples in X and Y.
Cosine distance is defined as 1.0 minus the cosine similarity.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like, sparse matrix
with shape (n_samples_X, n_features)... | Compute cosine distance between samples in X and Y.
Cosine distance is defined as 1.0 minus the cosine similarity.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like, sparse matrix
with shape (n_samples_X, n_features).
Y : array_like, sparse matrix (op... | cosine_distances | python | mars-project/mars | mars/learn/metrics/pairwise/cosine.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/cosine.py | Apache-2.0 |
def haversine_distances(X, Y=None):
"""Compute the Haversine distance between samples in X and Y
The Haversine (or great circle) distance is the angular distance between
two points on the surface of a sphere. The first distance of each point is
assumed to be the latitude, the second is the longitude, g... | Compute the Haversine distance between samples in X and Y
The Haversine (or great circle) distance is the angular distance between
two points on the surface of a sphere. The first distance of each point is
assumed to be the latitude, the second is the longitude, given in radians.
The dimension of the d... | haversine_distances | python | mars-project/mars | mars/learn/metrics/pairwise/haversine.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/haversine.py | Apache-2.0 |
def manhattan_distances(X, Y=None, sum_over_features=True):
""" Compute the L1 distances between the vectors in X and Y.
With sum_over_features equal to False it returns the componentwise
distances.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like
... | Compute the L1 distances between the vectors in X and Y.
With sum_over_features equal to False it returns the componentwise
distances.
Read more in the :ref:`User Guide <metrics>`.
Parameters
----------
X : array_like
A tensor with shape (n_samples_X, n_features).
Y : array_like... | manhattan_distances | python | mars-project/mars | mars/learn/metrics/pairwise/manhattan.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/manhattan.py | Apache-2.0 |
def _precompute_metric_params(X, Y, xp, metric=None, **kwds): # pragma: no cover
"""Precompute data-derived metric parameters if not provided"""
if metric == "seuclidean" and "V" not in kwds:
if X is Y:
V = xp.var(X, axis=0, ddof=1)
else:
V = xp.var(xp.vstack([X, Y]), ax... | Precompute data-derived metric parameters if not provided | _precompute_metric_params | python | mars-project/mars | mars/learn/metrics/pairwise/pairwise_distances_topk.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/pairwise_distances_topk.py | Apache-2.0 |
def _check_chunk_size(reduced, chunk_size): # pragma: no cover
"""Checks chunk is a sequence of expected size or a tuple of same"""
if reduced is None:
return
is_tuple = isinstance(reduced, tuple)
if not is_tuple:
reduced = (reduced,)
if any(isinstance(r, tuple) or not hasattr(r, "_... | Checks chunk is a sequence of expected size or a tuple of same | _check_chunk_size | python | mars-project/mars | mars/learn/metrics/pairwise/pairwise_distances_topk.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/pairwise_distances_topk.py | Apache-2.0 |
def _topk_reduce_func(cls, dist, start, topk, xp, metric):
"""Reduce a chunk of distances to topk
Parameters
----------
dist : array of shape (n_samples_chunk, n_samples)
start : int
The index in X which the first row of dist corresponds to.
topk : int
... | Reduce a chunk of distances to topk
Parameters
----------
dist : array of shape (n_samples_chunk, n_samples)
start : int
The index in X which the first row of dist corresponds to.
topk : int
Returns
-------
dist : array of shape (n_samples_ch... | _topk_reduce_func | python | mars-project/mars | mars/learn/metrics/pairwise/pairwise_distances_topk.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/pairwise_distances_topk.py | Apache-2.0 |
def rbf_kernel(X, Y=None, gamma=None):
"""
Compute the rbf (gaussian) kernel between X and Y::
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <rbf_kernel>`.
Parameters
----------
X : tensor of shape (n_samples_X, n_featu... |
Compute the rbf (gaussian) kernel between X and Y::
K(x, y) = exp(-gamma ||x-y||^2)
for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <rbf_kernel>`.
Parameters
----------
X : tensor of shape (n_samples_X, n_features)
Y : tensor of shape (n_samples_Y, n_... | rbf_kernel | python | mars-project/mars | mars/learn/metrics/pairwise/rbf_kernel.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/pairwise/rbf_kernel.py | Apache-2.0 |
def make_prediction(dataset=None, binary=False):
"""Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a
multiclass classification problem
"""
if dataset is None:
# import some data to play with
... | Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a
multiclass classification problem
| make_prediction | python | mars-project/mars | mars/learn/metrics/tests/test_classification.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/tests/test_classification.py | Apache-2.0 |
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, _ = sklearn_roc_curve(y_true, y_predict)
new_fpr = fpr[fpr <= max_fpr]
... | Alternative implementation to check for correctness of `roc_auc_score`
with `max_fpr` set.
| _partial_roc_auc_score | python | mars-project/mars | mars/learn/metrics/tests/test_ranking.py | https://github.com/mars-project/mars/blob/master/mars/learn/metrics/tests/test_ranking.py | Apache-2.0 |
def train_test_split(*arrays, **options):
"""Split arrays or matrices into random train and test subsets
Parameters
----------
*arrays : sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse
matrices or pandas dataframes.
test_size ... | Split arrays or matrices into random train and test subsets
Parameters
----------
*arrays : sequence of indexables with same length / shape[0]
Allowed inputs are lists, numpy arrays, scipy-sparse
matrices or pandas dataframes.
test_size : float, int or None, optional (default=None)
... | train_test_split | python | mars-project/mars | mars/learn/model_selection/_split.py | https://github.com/mars-project/mars/blob/master/mars/learn/model_selection/_split.py | Apache-2.0 |
def _validate_shuffle_split(n_samples, test_size, train_size, default_test_size=None):
"""
Validation helper to check if the test/test sizes are meaningful wrt to the
size of the data (n_samples)
"""
if test_size is None and train_size is None:
test_size = default_test_size
test_size_ty... |
Validation helper to check if the test/test sizes are meaningful wrt to the
size of the data (n_samples)
| _validate_shuffle_split | python | mars-project/mars | mars/learn/model_selection/_split.py | https://github.com/mars-project/mars/blob/master/mars/learn/model_selection/_split.py | Apache-2.0 |
def split(self, X, y=None, groups=None): # pragma: no cover
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features... | Generate indices to split data into training and test set.
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 : array-like of shape (n_samples,... | split | python | mars-project/mars | mars/learn/model_selection/_split.py | https://github.com/mars-project/mars/blob/master/mars/learn/model_selection/_split.py | Apache-2.0 |
def _iter_test_masks(self, X=None, y=None, groups=None): # pragma: no cover
"""Generates boolean masks corresponding to test sets.
By default, delegates to _iter_test_indices(X, y, groups)
"""
for test_index in self._iter_test_indices(X, y, groups):
test_mask = mt.zeros(_nu... | Generates boolean masks corresponding to test sets.
By default, delegates to _iter_test_indices(X, y, groups)
| _iter_test_masks | python | mars-project/mars | mars/learn/model_selection/_split.py | https://github.com/mars-project/mars/blob/master/mars/learn/model_selection/_split.py | Apache-2.0 |
def split(self, X, y=None, groups=None):
"""Generate indices to split data into training and test set.
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 fe... | Generate indices to split data into training and test set.
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 : array-like of shape (n_samples,... | split | python | mars-project/mars | mars/learn/model_selection/_split.py | https://github.com/mars-project/mars/blob/master/mars/learn/model_selection/_split.py | Apache-2.0 |
def kneighbors(
self,
X=None,
n_neighbors=None,
return_distance=True,
session=None,
run_kwargs=None,
**kw,
):
"""Finds the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters
----... | Finds the K-neighbors of a point.
Returns indices of and distances to the neighbors of each point.
Parameters
----------
X : array-like, shape (n_query, n_features), or (n_query, n_indexed) if metric == 'precomputed'
The query point or points.
If ... | kneighbors | python | mars-project/mars | mars/learn/neighbors/base.py | https://github.com/mars-project/mars/blob/master/mars/learn/neighbors/base.py | Apache-2.0 |
def kneighbors_graph(
self,
X=None,
n_neighbors=None,
mode="connectivity",
session=None,
run_kwargs=None,
):
"""Computes the (weighted) graph of k-Neighbors for points in X
Parameters
----------
X : array-like, shape (n_query, n_featur... | Computes the (weighted) graph of k-Neighbors for points in X
Parameters
----------
X : array-like, shape (n_query, n_features), or (n_query, n_indexed) if metric == 'precomputed'
The query point or points.
If not provided, neighbors of each indexed point ... | kneighbors_graph | python | mars-project/mars | mars/learn/neighbors/base.py | https://github.com/mars-project/mars/blob/master/mars/learn/neighbors/base.py | Apache-2.0 |
def _tile_chunks(cls, op, in_tensor, faiss_index, n_sample):
"""
If the distribution on each chunk is the same,
refer to:
https://github.com/facebookresearch/faiss/wiki/FAQ#how-can-i-distribute-index-building-on-several-machines
1. train an IndexIVF* on a representative sample o... |
If the distribution on each chunk is the same,
refer to:
https://github.com/facebookresearch/faiss/wiki/FAQ#how-can-i-distribute-index-building-on-several-machines
1. train an IndexIVF* on a representative sample of the data, store it.
2. for each node, load the trained index, ... | _tile_chunks | python | mars-project/mars | mars/learn/neighbors/_faiss.py | https://github.com/mars-project/mars/blob/master/mars/learn/neighbors/_faiss.py | Apache-2.0 |
def _gen_index_string_and_sample_count(
shape, n_sample, accuracy, memory_require, gpu=None, **kw
):
"""
Generate index string and sample count according to guidance of faiss:
https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index
"""
size, dim = shape
memory_require = ... |
Generate index string and sample count according to guidance of faiss:
https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index
| _gen_index_string_and_sample_count | python | mars-project/mars | mars/learn/neighbors/_faiss.py | https://github.com/mars-project/mars/blob/master/mars/learn/neighbors/_faiss.py | Apache-2.0 |
def normalize(X, norm="l2", axis=1, copy=True, return_norm=False):
"""
Scale input vectors individually to unit norm (vector length).
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to normalize, element by element.
scipy.sparse matrices... |
Scale input vectors individually to unit norm (vector length).
Parameters
----------
X : {array-like, sparse matrix}, shape [n_samples, n_features]
The data to normalize, element by element.
scipy.sparse matrices should be in CSR format to avoid an
un-necessary copy.
norm ... | normalize | python | mars-project/mars | mars/learn/preprocessing/normalize.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/normalize.py | Apache-2.0 |
def _handle_zeros_in_scale(scale, copy=True):
"""Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
"""
# if we are fitting on 1D arrays, scale might be a scalar
if np.isscalar(scale): # pragma: no cover
if scale ==... | Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
| _handle_zeros_in_scale | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def _reset(self): # pragma: no cover
"""Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
"""
# Checking one attribute is enough, because they are all set together
# in partial_fit
if hasattr(self, "scale_"):
... | Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched.
| _reset | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def fit(self, X, y=None, session=None, run_kwargs=None):
"""Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for l... | Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for later scaling along the features axis.
y : None
... | fit | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def partial_fit(self, X, y=None, session=None, run_kwargs=None):
"""Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read... | Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous stream.
Parameters
----------
X ... | partial_fit | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def transform(self, X, session=None, run_kwargs=None):
"""Scale features of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed.
Returns
-------
Xt : ndarray of shape... | Scale features of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed.
Returns
-------
Xt : ndarray of shape (n_samples, n_features)
Transformed data.
| transform | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def inverse_transform(self, X, session=None, run_kwargs=None):
"""Undo the scaling of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed. It cannot be sparse.
Returns
------... | Undo the scaling of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed. It cannot be sparse.
Returns
-------
Xt : ndarray of shape (n_samples, n_features)
Transf... | inverse_transform | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def minmax_scale(
X, feature_range=(0, 1), *, axis=0, copy=True, session=None, run_kwargs=None
):
"""Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero ... | Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero and one.
The transformation is given by (when ``axis=0``)::
X_std = (X - X.min(axis=0)) / (X.ma... | minmax_scale | python | mars-project/mars | mars/learn/preprocessing/_data.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_data.py | Apache-2.0 |
def fit(self, y, session=None, run_kwargs=None, execute=True):
"""Fit label encoder.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
Fitted label encoder.
... | Fit label encoder.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
self : returns an instance of self.
Fitted label encoder.
| fit | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def fit_transform(self, y, session=None, run_kwargs=None):
"""Fit label encoder and return encoded labels.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
y : array-like of shape (n_samples,)
Enco... | Fit label encoder and return encoded labels.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
y : array-like of shape (n_samples,)
Encoded labels.
| fit_transform | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def transform(self, y, session=None, run_kwargs=None, execute=True):
"""Transform labels to normalized encoding.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
y : array-like of shape (n_samples,)
... | Transform labels to normalized encoding.
Parameters
----------
y : array-like of shape (n_samples,)
Target values.
Returns
-------
y : array-like of shape (n_samples,)
Labels as normalized encodings.
| transform | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def inverse_transform(self, y, session=None, run_kwargs=None):
"""Transform labels back to original encoding.
Parameters
----------
y : ndarray of shape (n_samples,)
Target values.
Returns
-------
y : ndarray of shape (n_samples,)
Origina... | Transform labels back to original encoding.
Parameters
----------
y : ndarray of shape (n_samples,)
Target values.
Returns
-------
y : ndarray of shape (n_samples,)
Original encoding.
| inverse_transform | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def fit(self, y, session=None, run_kwargs=None):
"""Fit label binarizer.
Parameters
----------
y : ndarray of shape (n_samples,) or (n_samples, n_classes)
Target values. The 2-d matrix should only contain 0 and 1,
represents multilabel classification.
Re... | Fit label binarizer.
Parameters
----------
y : ndarray of shape (n_samples,) or (n_samples, n_classes)
Target values. The 2-d matrix should only contain 0 and 1,
represents multilabel classification.
Returns
-------
self : returns an instance of ... | fit | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def fit_transform(self, y, session=None, run_kwargs=None):
"""Fit label binarizer and transform multi-class labels to binary
labels.
The output of transform is sometimes referred to as
the 1-of-K coding scheme.
Parameters
----------
y : {ndarray, sparse matrix} ... | Fit label binarizer and transform multi-class labels to binary
labels.
The output of transform is sometimes referred to as
the 1-of-K coding scheme.
Parameters
----------
y : {ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)
... | fit_transform | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def transform(self, y, session=None, run_kwargs=None):
"""Transform multi-class labels to binary labels.
The output of transform is sometimes referred to by some authors as
the 1-of-K coding scheme.
Parameters
----------
y : {array, sparse matrix} of shape (n_samples,) ... | Transform multi-class labels to binary labels.
The output of transform is sometimes referred to by some authors as
the 1-of-K coding scheme.
Parameters
----------
y : {array, sparse matrix} of shape (n_samples,) or (n_samples, n_classes)
Target value... | transform | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def inverse_transform(self, Y, threshold=None):
"""Transform binary labels back to multi-class labels.
Parameters
----------
Y : {ndarray, sparse matrix} of shape (n_samples, n_classes)
Target values. All sparse matrices are converted to CSR before
inverse transf... | Transform binary labels back to multi-class labels.
Parameters
----------
Y : {ndarray, sparse matrix} of shape (n_samples, n_classes)
Target values. All sparse matrices are converted to CSR before
inverse transformation.
threshold : float, default=None
... | inverse_transform | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def label_binarize(
y, *, classes, neg_label=0, pos_label=1, sparse_output=False, execute=True
):
"""Binarize labels in a one-vs-all fashion.
Several regression and binary classification algorithms are
available in scikit-learn. A simple way to extend these algorithms
to the multi-class classificat... | Binarize labels in a one-vs-all fashion.
Several regression and binary classification algorithms are
available in scikit-learn. A simple way to extend these algorithms
to the multi-class classification case is to use the so-called
one-vs-all scheme.
This function makes it possible to compute this ... | label_binarize | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def _inverse_binarize_multiclass(y, classes): # pragma: no cover
"""Inverse label binarization transformation for multiclass.
Multiclass uses the maximal score instead of a threshold.
"""
classes = np.asarray(classes)
if sp.issparse(y):
# Find the argmax for each row in y where y is a CSR... | Inverse label binarization transformation for multiclass.
Multiclass uses the maximal score instead of a threshold.
| _inverse_binarize_multiclass | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def _inverse_binarize_thresholding(
y, output_type, classes, threshold
): # pragma: no cover
"""Inverse label binarization transformation using thresholding."""
if output_type == "binary" and y.ndim == 2 and y.shape[1] > 2:
raise ValueError("output_type='binary', but y.shape = {0}".format(y.shape)... | Inverse label binarization transformation using thresholding. | _inverse_binarize_thresholding | python | mars-project/mars | mars/learn/preprocessing/_label.py | https://github.com/mars-project/mars/blob/master/mars/learn/preprocessing/_label.py | Apache-2.0 |
def predict(self, X, session=None, run_kwargs=None):
"""Performs inductive inference across the model.
Parameters
----------
X : array_like, shape = [n_samples, n_features]
Returns
-------
y : array_like, shape = [n_samples]
Predictions for input dat... | Performs inductive inference across the model.
Parameters
----------
X : array_like, shape = [n_samples, n_features]
Returns
-------
y : array_like, shape = [n_samples]
Predictions for input data
| predict | python | mars-project/mars | mars/learn/semi_supervised/_label_propagation.py | https://github.com/mars-project/mars/blob/master/mars/learn/semi_supervised/_label_propagation.py | Apache-2.0 |
def predict_proba(self, X, session=None, run_kwargs=None):
"""Predict probability for each possible outcome.
Compute the probability estimates for each single sample in X
and each possible outcome seen during training (categorical
distribution).
Parameters
----------
... | Predict probability for each possible outcome.
Compute the probability estimates for each single sample in X
and each possible outcome seen during training (categorical
distribution).
Parameters
----------
X : array_like, shape = [n_samples, n_features]
Returns... | predict_proba | python | mars-project/mars | mars/learn/semi_supervised/_label_propagation.py | https://github.com/mars-project/mars/blob/master/mars/learn/semi_supervised/_label_propagation.py | Apache-2.0 |
def fit(self, X, y, session=None, run_kwargs=None):
"""Fit a semi-supervised label propagation model based
All the input data is provided matrix X (labeled and unlabeled)
and corresponding label matrix y with a dedicated marker value for
unlabeled samples.
Parameters
--... | Fit a semi-supervised label propagation model based
All the input data is provided matrix X (labeled and unlabeled)
and corresponding label matrix y with a dedicated marker value for
unlabeled samples.
Parameters
----------
X : array-like of shape (n_samples, n_features... | fit | python | mars-project/mars | mars/learn/semi_supervised/_label_propagation.py | https://github.com/mars-project/mars/blob/master/mars/learn/semi_supervised/_label_propagation.py | Apache-2.0 |
def _build_graph(self):
"""Matrix representing a fully connected graph between each sample
This basic implementation creates a non-stochastic affinity matrix, so
class distributions will exceed 1 (normalization may be desired).
"""
if self.kernel == "knn":
self.nn_fi... | Matrix representing a fully connected graph between each sample
This basic implementation creates a non-stochastic affinity matrix, so
class distributions will exceed 1 (normalization may be desired).
| _build_graph | python | mars-project/mars | mars/learn/semi_supervised/_label_propagation.py | https://github.com/mars-project/mars/blob/master/mars/learn/semi_supervised/_label_propagation.py | Apache-2.0 |
def get_chunk_n_rows(row_bytes, max_n_rows=None, working_memory=None):
"""Calculates how many rows can be processed within working_memory
Parameters
----------
row_bytes : int
The expected number of bytes of memory that will be consumed
during the processing of each row.
max_n_rows ... | Calculates how many rows can be processed within working_memory
Parameters
----------
row_bytes : int
The expected number of bytes of memory that will be consumed
during the processing of each row.
max_n_rows : int, optional
The maximum return value.
working_memory : int or ... | get_chunk_n_rows | python | mars-project/mars | mars/learn/utils/core.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/core.py | Apache-2.0 |
def _safe_accumulator_op(op, x, *args, **kwargs):
"""
This function provides numpy accumulator functions with a float64 dtype
when used on a floating point input. This prevents accumulator overflow on
smaller floating point dtypes.
Parameters
----------
op : function
A accumulator f... |
This function provides numpy accumulator functions with a float64 dtype
when used on a floating point input. This prevents accumulator overflow on
smaller floating point dtypes.
Parameters
----------
op : function
A accumulator function such as np.mean or np.sum
x : numpy array
... | _safe_accumulator_op | python | mars-project/mars | mars/learn/utils/extmath.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/extmath.py | Apache-2.0 |
def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.
Performs no input validation.
Parameters
----------
X : array_like
The input tensor
squared : bool, optional (default = False)
If True, return squared norms.
Returns
-------
array_like
... | Row-wise (squared) Euclidean norm of X.
Performs no input validation.
Parameters
----------
X : array_like
The input tensor
squared : bool, optional (default = False)
If True, return squared norms.
Returns
-------
array_like
The row-wise (squared) Euclidean nor... | row_norms | python | mars-project/mars | mars/learn/utils/extmath.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/extmath.py | Apache-2.0 |
def softmax(X, copy=True):
"""
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
... |
Calculate the softmax function.
The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)
This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.
Parameters
----------
... | softmax | python | mars-project/mars | mars/learn/utils/extmath.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/extmath.py | Apache-2.0 |
def unique_labels(*ys):
"""
Extract an ordered array of unique labels.
We don't allow:
- mix of multilabel and multiclass (single label) targets
- mix of label indicator matrix and anything else,
because there are no explicit labels)
- mix of label indicator matrices of di... |
Extract an ordered array of unique labels.
We don't allow:
- mix of multilabel and multiclass (single label) targets
- mix of label indicator matrix and anything else,
because there are no explicit labels)
- mix of label indicator matrices of different sizes
- mix of ... | unique_labels | python | mars-project/mars | mars/learn/utils/multiclass.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/multiclass.py | Apache-2.0 |
def is_multilabel(y):
"""
Check if ``y`` is in a multilabel format.
Parameters
----------
y : numpy array of shape [n_samples]
Target values.
Returns
-------
out : bool,
Return ``True``, if ``y`` is in a multilabel format, else ```False``.
Examples
--------
... |
Check if ``y`` is in a multilabel format.
Parameters
----------
y : numpy array of shape [n_samples]
Target values.
Returns
-------
out : bool,
Return ``True``, if ``y`` is in a multilabel format, else ```False``.
Examples
--------
>>> import mars.tensor as mt... | is_multilabel | python | mars-project/mars | mars/learn/utils/multiclass.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/multiclass.py | Apache-2.0 |
def type_of_target(y):
"""
Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred.
For example:
* ``binary`` is more specific but compatible with ``multiclass``.
* ``multiclass`` of integers is more specific but compatible... |
Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred.
For example:
* ``binary`` is more specific but compatible with ``multiclass``.
* ``multiclass`` of integers is more specific but compatible with
``continuous``... | type_of_target | python | mars-project/mars | mars/learn/utils/multiclass.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/multiclass.py | Apache-2.0 |
def check_classification_targets(y):
"""
Ensure that target y is of a non-regression type.
Only the following target types (as defined in type_of_target) are allowed:
'binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences'
Parameters
-------... |
Ensure that target y is of a non-regression type.
Only the following target types (as defined in type_of_target) are allowed:
'binary', 'multiclass', 'multiclass-multioutput',
'multilabel-indicator', 'multilabel-sequences'
Parameters
----------
y : array-like
| check_classification_targets | python | mars-project/mars | mars/learn/utils/multiclass.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/multiclass.py | Apache-2.0 |
def count_nonzero(X, axis: Optional[int] = None, sample_weight=None):
"""A variant of X.getnnz() with extension to weighting on axis 0
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : CSR sparse matrix of shape (n_samples, n_labels)
Input data.
axis : No... | A variant of X.getnnz() with extension to weighting on axis 0
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : CSR sparse matrix of shape (n_samples, n_labels)
Input data.
axis : None, 0 or 1
The axis on which the data is aggregated.
sample_weig... | count_nonzero | python | mars-project/mars | mars/learn/utils/sparsefuncs.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/sparsefuncs.py | Apache-2.0 |
def _num_samples(x):
"""Return number of samples in array-like x."""
if hasattr(x, "fit") and callable(x.fit):
# Don't get num_samples from an ensembles length!
raise TypeError(f"Expected sequence or array-like, got estimator {x}")
if not hasattr(x, "__len__") and not hasattr(x, "shape"):
... | Return number of samples in array-like x. | _num_samples | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def check_consistent_length(*arrays, session=None, run_kwargs=None):
"""Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Parameters
----------
*arrays : list or tuple of input objects.
Objects that will be checked f... | Check that all arrays have consistent first dimensions.
Checks whether all objects in arrays have the same shape or length.
Parameters
----------
*arrays : list or tuple of input objects.
Objects that will be checked for consistent length.
| check_consistent_length | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def _make_indexable(iterable):
"""Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, d... | Ensure iterable supports indexing or convert to an indexable variant.
Convert sparse matrices to csr and other non-indexable iterable to arrays.
Let `None` and indexable objects (e.g. pandas dataframes) pass unchanged.
Parameters
----------
iterable : {list, dataframe, array, sparse} or None
... | _make_indexable | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def indexable(*iterables, session=None, run_kwargs=None):
"""Make arrays indexable for cross-validation.
Checks consistent length, passes through None, and ensures that everything
can be indexed by converting sparse matrices to csr and converting
non-interable objects to arrays.
Parameters
---... | Make arrays indexable for cross-validation.
Checks consistent length, passes through None, and ensures that everything
can be indexed by converting sparse matrices to csr and converting
non-interable objects to arrays.
Parameters
----------
*iterables : lists, dataframes, arrays, sparse matric... | indexable | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def _ensure_sparse_format(
spmatrix, accept_sparse, dtype, copy, force_all_finite, accept_large_sparse
):
"""Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : scipy sparse matrix
Input to validate... | Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : scipy sparse matrix
Input to validate and convert.
accept_sparse : string, boolean or list/tuple of strings
String[s] representing allowed sp... | _ensure_sparse_format | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def check_array(
array,
accept_sparse=False,
accept_large_sparse=True,
dtype="numeric",
order=None,
copy=False,
force_all_finite=True,
ensure_2d=True,
allow_nd=False,
ensure_min_samples=1,
ensure_min_features=1,
estimator=None,
) -> Tensor:
"""Input validation on a te... | Input validation on a tensor, list, sparse matrix or similar.
By default, the input is checked to be a non-empty 2D array containing
only finite values. If the dtype of the tensor is object, attempt
converting to float, raising on failure.
Parameters
----------
array : object
Input obj... | check_array | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def check_X_y(
X,
y,
accept_sparse=False,
accept_large_sparse=True,
dtype="numeric",
order=None,
copy=False,
force_all_finite=True,
ensure_2d=True,
allow_nd=False,
multi_output=False,
ensure_min_samples=1,
ensure_min_features=1,
y_numeric=False,
estimator=None... | Input validation for standard estimators.
Checks X and y for consistent length, enforces X to be 2D and y 1D. By
default, X is checked to be non-empty and containing only finite values.
Standard input checks are also applied to y, such as checking that y
does not have np.nan or np.inf targets. For mult... | check_X_y | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def column_or_1d(y, warn=False):
"""Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
warn : boolean, default False
To control display of warnings.
Returns
-------
y : array
"""
y = mt.tensor(y)
shape = y.shape
if len(sha... | Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
warn : boolean, default False
To control display of warnings.
Returns
-------
y : array
| column_or_1d | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def _check_sample_weight(sample_weight, X, dtype=None):
"""Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
sample_weight = _check_sample_weight(...)
Pa... | Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
sample_weight = _check_sample_weight(...)
Parameters
----------
sample_weight : {ndarray, Number or... | _check_sample_weight | python | mars-project/mars | mars/learn/utils/validation.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/validation.py | Apache-2.0 |
def _unique(values, *, return_inverse=False):
"""Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unknowns.
return_inve... | Helper function to find unique values with support for python objects.
Uses pure python method for object dtype, and numpy method for
all other dtypes.
Parameters
----------
values : ndarray
Values to check for unknowns.
return_inverse : bool, default=False
If True, also retur... | _unique | python | mars-project/mars | mars/learn/utils/_encode.py | https://github.com/mars-project/mars/blob/master/mars/learn/utils/_encode.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.