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 run_tensorflow_script( script: Union[bytes, str, BinaryIO, TextIO], n_workers: int, n_ps: int = 0, data: Dict[str, TileableType] = None, gpu: Optional[bool] = None, command_argv: List[str] = None, retry_when_fail: bool = False, session: SessionType = None, run_kwargs: Dict[str, A...
Run TensorFlow script in Mars cluster. Parameters ---------- script: str or file-like object Script to run n_workers : int Number of TensorFlow workers. n_ps : int Number of TensorFlow PS workers. data : dict Variable name to data. gpu : bool Run...
run_tensorflow_script
python
mars-project/mars
mars/learn/contrib/tensorflow/run_script.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/tensorflow/run_script.py
Apache-2.0
def fit( self, X, y, sample_weights=None, eval_set=None, sample_weight_eval_set=None, **kw, ): """ Fit the regressor. Parameters ---------- X : array_like ...
Fit the regressor. Parameters ---------- X : array_like Feature matrix y : array_like Labels sample_weight : array_like instance weights eval_set : list, optional A list o...
fit
python
mars-project/mars
mars/learn/contrib/xgboost/core.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/core.py
Apache-2.0
def wrap_evaluation_matrices( missing: float, X: Any, y: Any, sample_weight: Optional[Any], base_margin: Optional[Any], eval_set: Optional[List[Tuple[Any, Any]]], sample_weight_eval_set: Optional[List[Any]], base_margin_eval_set: Optional[List[Any]], ...
Convert array_like evaluation matrices into DMatrix. Perform validation on the way.
wrap_evaluation_matrices
python
mars-project/mars
mars/learn/contrib/xgboost/core.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/core.py
Apache-2.0
def print(self, use_logger: bool) -> None: """Execute the print command from worker.""" msg = self.sock.recvstr() # On dask we use print to avoid setting global verbosity. if use_logger: logger.info(msg.strip()) else: print(msg.strip(), flush=True)
Execute the print command from worker.
print
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def decide_rank(self, job_map: Dict[str, int]) -> int: """Get the rank of current entry.""" if self.rank >= 0: return self.rank if self.jobid != "NULL" and self.jobid in job_map: return job_map[self.jobid] return -1
Get the rank of current entry.
decide_rank
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def assign_rank( self, rank: int, wait_conn: Dict[int, "WorkerEntry"], tree_map: _TreeMap, parent_map: Dict[int, int], ring_map: _RingMap, ) -> List[int]: """Assign the rank for current entry.""" self.rank = rank nnset = set(tree_map[rank]) ...
Assign the rank for current entry.
assign_rank
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def __init__( self, host_ip: str, n_workers: int, port: int = 0, use_logger: bool = False ) -> None: """A Python implementation of RABIT tracker. Parameters .......... use_logger: Use logging.info for tracker print command. When set to False, Python print ...
A Python implementation of RABIT tracker. Parameters .......... use_logger: Use logging.info for tracker print command. When set to False, Python print function is used instead.
__init__
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def find_share_ring( self, tree_map: _TreeMap, parent_map: Dict[int, int], rank: int ) -> List[int]: """ get a ring structure that tends to share nodes with the tree return a list starting from rank """ nset = set(tree_map[rank]) cset = nset - set([parent_map[...
get a ring structure that tends to share nodes with the tree return a list starting from rank
find_share_ring
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def get_ring(self, tree_map: _TreeMap, parent_map: Dict[int, int]) -> _RingMap: """ get a ring connection used to recover local data """ assert parent_map[0] == -1 rlst = self.find_share_ring(tree_map, parent_map, 0) assert len(rlst) == len(tree_map) ring_map: _Ri...
get a ring connection used to recover local data
get_ring
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def get_link_map(self, n_workers: int) -> Tuple[_TreeMap, Dict[int, int], _RingMap]: """ get the link map, this is a bit hacky, call for better algorithm to place similar nodes together """ tree_map, parent_map = self._get_tree(n_workers) ring_map = self.get_ring(tree_map...
get the link map, this is a bit hacky, call for better algorithm to place similar nodes together
get_link_map
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def accept_workers(self, n_workers: int) -> None: """Wait for all workers to connect to the tracker.""" # set of nodes that finishes the job shutdown: Dict[int, WorkerEntry] = {} # set of nodes that is waiting for connections wait_conn: Dict[int, WorkerEntry] = {} # maps ...
Wait for all workers to connect to the tracker.
accept_workers
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def start(self, n_workers: int) -> None: """Start the tracker, it will wait for `n_workers` to connect.""" def run() -> None: self.accept_workers(n_workers) self.thread = Thread(target=run, args=(), daemon=True) self.thread.start()
Start the tracker, it will wait for `n_workers` to connect.
start
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def get_host_ip(host_ip: Optional[str] = None) -> str: """Get the IP address of current host. If `host_ip` is not none then it will be returned as it's """ if host_ip is None or host_ip == "auto": host_ip = "ip" if host_ip == "dns": host_ip = socket.getfqdn() elif host_ip == "i...
Get the IP address of current host. If `host_ip` is not none then it will be returned as it's
get_host_ip
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def start_rabit_tracker(args: argparse.Namespace) -> None: """Standalone function to start rabit tracker. Parameters ---------- args: arguments to start the rabit tracker. """ envs = {"DMLC_NUM_WORKER": args.num_workers, "DMLC_NUM_SERVER": args.num_servers} rabit = RabitTracker( host...
Standalone function to start rabit tracker. Parameters ---------- args: arguments to start the rabit tracker.
start_rabit_tracker
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def main() -> None: """Main function if tracker is executed in standalone mode.""" parser = argparse.ArgumentParser(description="Rabit Tracker start.") parser.add_argument( "--num-workers", required=True, type=int, help="Number of worker process to be launched.", ) pa...
Main function if tracker is executed in standalone mode.
main
python
mars-project/mars
mars/learn/contrib/xgboost/tracker.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/tracker.py
Apache-2.0
def train(params, dtrain, evals=(), **kwargs): """ Train XGBoost model in Mars manner. Parameters ---------- Parameters are the same as `xgboost.train`. Returns ------- results: Booster """ evals_result = kwargs.pop("evals_result", dict()) session = kwargs.pop("session", N...
Train XGBoost model in Mars manner. Parameters ---------- Parameters are the same as `xgboost.train`. Returns ------- results: Booster
train
python
mars-project/mars
mars/learn/contrib/xgboost/train.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/xgboost/train.py
Apache-2.0
def make_classification( n_samples=100, n_features=20, n_informative=2, n_redundant=2, n_repeated=0, n_classes=2, n_clusters_per_class=2, weights=None, flip_y=0.01, class_sep=1.0, hypercube=True, shift=0.0, scale=1.0, shuffle=True, random_state=None, ): ""...
Generate a random n-class classification problem. This initially creates clusters of points normally distributed (std=1) about vertices of an ``n_informative``-dimensional hypercube with sides of length ``2*class_sep`` and assigns an equal number of clusters to each class. It introduces interdependence...
make_classification
python
mars-project/mars
mars/learn/datasets/samples_generator.py
https://github.com/mars-project/mars/blob/master/mars/learn/datasets/samples_generator.py
Apache-2.0
def make_regression( n_samples=100, n_features=100, *, n_informative=10, n_targets=1, bias=0.0, effective_rank=None, tail_strength=0.5, noise=0.0, shuffle=True, coef=False, random_state=None, ): """Generate a random regression problem. The input set can either be...
Generate a random regression problem. The input set can either be well conditioned (by default) or have a low rank-fat tail singular profile. See :func:`make_low_rank_matrix` for more details. The output is generated by applying a (potentially biased) random linear regression model with `n_informa...
make_regression
python
mars-project/mars
mars/learn/datasets/samples_generator.py
https://github.com/mars-project/mars/blob/master/mars/learn/datasets/samples_generator.py
Apache-2.0
def make_blobs( n_samples=100, n_features=2, centers=None, cluster_std=1.0, center_box=(-10.0, 10.0), shuffle=True, random_state=None, ): """Generate isotropic Gaussian blobs for clustering. Read more in the :ref:`User Guide <sample_generators>`. Parameters ---------- n...
Generate isotropic Gaussian blobs for clustering. Read more in the :ref:`User Guide <sample_generators>`. Parameters ---------- n_samples : int or array-like, optional (default=100) If int, it is the total number of points equally divided among clusters. If array-like, each ele...
make_blobs
python
mars-project/mars
mars/learn/datasets/samples_generator.py
https://github.com/mars-project/mars/blob/master/mars/learn/datasets/samples_generator.py
Apache-2.0
def make_low_rank_matrix( n_samples=100, n_features=100, effective_rank=10, tail_strength=0.5, random_state=None, chunk_size=None, ): """Generate a mostly low rank matrix with bell-shaped singular values Most of the variance can be explained by a bell-shaped curve of width effective...
Generate a mostly low rank matrix with bell-shaped singular values Most of the variance can be explained by a bell-shaped curve of width effective_rank: the low rank part of the singular values profile is:: (1 - tail_strength) * exp(-1.0 * (i / effective_rank) ** 2) The remaining singular values'...
make_low_rank_matrix
python
mars-project/mars
mars/learn/datasets/samples_generator.py
https://github.com/mars-project/mars/blob/master/mars/learn/datasets/samples_generator.py
Apache-2.0
def get_covariance(self, session=None): """Compute data covariance with the generative model. ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` where S**2 contains the explained variances, and sigma2 contains the noise variances. Returns ------- ...
Compute data covariance with the generative model. ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` where S**2 contains the explained variances, and sigma2 contains the noise variances. Returns ------- cov : Tensor, shape=(n_features, n_features) ...
get_covariance
python
mars-project/mars
mars/learn/decomposition/_base.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_base.py
Apache-2.0
def get_precision(self, session=None): """Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency. Returns ------- precision : Tensor, shape=(n_features, n_features) ...
Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency. Returns ------- precision : Tensor, shape=(n_features, n_features) Estimated precision of data.
get_precision
python
mars-project/mars
mars/learn/decomposition/_base.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_base.py
Apache-2.0
def fit(X, y=None, session=None, run_kwargs=None): """Placeholder for fit. Subclasses should implement this method! Fit the model with X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and ...
Placeholder for fit. Subclasses should implement this method! Fit the model with X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. Ret...
fit
python
mars-project/mars
mars/learn/decomposition/_base.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_base.py
Apache-2.0
def transform(self, X, session=None): """Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_sam...
Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_f...
transform
python
mars-project/mars
mars/learn/decomposition/_base.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_base.py
Apache-2.0
def inverse_transform(self, X, session=None): """Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the ...
Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the num...
inverse_transform
python
mars-project/mars
mars/learn/decomposition/_base.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_base.py
Apache-2.0
def _assess_dimension(spectrum, rank, n_samples): """Compute the log-likelihood of a rank ``rank`` dataset. The dataset is assumed to be embedded in gaussian noise of shape(n, dimf) having spectrum ``spectrum``. Parameters ---------- spectrum : array of shape (n_features) Data spectrum...
Compute the log-likelihood of a rank ``rank`` dataset. The dataset is assumed to be embedded in gaussian noise of shape(n, dimf) having spectrum ``spectrum``. Parameters ---------- spectrum : array of shape (n_features) Data spectrum. rank : int Tested rank value. It should be ...
_assess_dimension
python
mars-project/mars
mars/learn/decomposition/_pca.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_pca.py
Apache-2.0
def fit_transform(self, X, y=None, session=None): """Fit the model with X and apply the dimensionality reduction on X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is th...
Fit the model with X and apply the dimensionality reduction on X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. y : Ignored Returns ...
fit_transform
python
mars-project/mars
mars/learn/decomposition/_pca.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_pca.py
Apache-2.0
def _fit_full(self, X, n_components, session=None, run_kwargs=None): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape if n_components == "mle": if n_samples < n_features: raise ValueError( "n_components='mle' is only ...
Fit the model by computing full SVD on X
_fit_full
python
mars-project/mars
mars/learn/decomposition/_pca.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_pca.py
Apache-2.0
def _fit_truncated(self, X, n_components, svd_solver): """Fit the model by computing truncated SVD (by ARPACK or randomized) on X """ n_samples, n_features = X.shape if isinstance(n_components, str): raise ValueError( "n_components=%r cannot be a stri...
Fit the model by computing truncated SVD (by ARPACK or randomized) on X
_fit_truncated
python
mars-project/mars
mars/learn/decomposition/_pca.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_pca.py
Apache-2.0
def score_samples(self, X, session=None): """Return the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : tensor, shape(n_sample...
Return the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : tensor, shape(n_samples, n_features) The data. Returns...
score_samples
python
mars-project/mars
mars/learn/decomposition/_pca.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_pca.py
Apache-2.0
def score(self, X, y=None, session=None): """Return the average log-likelihood of all samples. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : tensor, shape(...
Return the average log-likelihood of all samples. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : tensor, shape(n_samples, n_features) The data. ...
score
python
mars-project/mars
mars/learn/decomposition/_pca.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_pca.py
Apache-2.0
def fit_transform(self, X, y=None, session=None): """Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. session : session to run y : Ignored ...
Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. session : session to run y : Ignored Returns ------- X_new : array, shape (n_sa...
fit_transform
python
mars-project/mars
mars/learn/decomposition/_truncated_svd.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_truncated_svd.py
Apache-2.0
def transform(self, X, session=None): """Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. session : session to run Returns ------- X_new : array, shape (n_sa...
Perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) New data. session : session to run Returns ------- X_new : array, shape (n_samples, n_components) Reduced version ...
transform
python
mars-project/mars
mars/learn/decomposition/_truncated_svd.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_truncated_svd.py
Apache-2.0
def inverse_transform(self, X, session=None): """Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data. session : session to run ...
Transform X back to its original space. Returns an array X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data. session : session to run Returns ------- X_original : array, shap...
inverse_transform
python
mars-project/mars
mars/learn/decomposition/_truncated_svd.py
https://github.com/mars-project/mars/blob/master/mars/learn/decomposition/_truncated_svd.py
Apache-2.0
def _make_estimator(estimator, random_state=None): """Make and configure a copy of the `base_estimator_` attribute. Warning: This method should be used to properly instantiate new sub-estimators. """ estimator = clone_estimator(estimator) if random_state is not None: _set_random_states(...
Make and configure a copy of the `base_estimator_` attribute. Warning: This method should be used to properly instantiate new sub-estimators.
_make_estimator
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 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 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 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 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 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 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 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 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 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