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 _get_selection_columns(cls, op: DataFrameGroupByAgg) -> Union[None, List]: """ Get groupby selection columns from op parameters. If this returns None, it means all columns are required. Parameters ---------- op Returns ------- """ if ...
Get groupby selection columns from op parameters. If this returns None, it means all columns are required. Parameters ---------- op Returns -------
_get_selection_columns
python
mars-project/mars
mars/dataframe/groupby/nunique.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/nunique.py
Apache-2.0
def groupby_sample( groupby, n: Optional[int] = None, frac: Optional[float] = None, replace: bool = False, weights: Union[Sequence, pd.Series, None] = None, random_state: Optional[np.random.RandomState] = None, errors: str = "ignore", ): """ Return a random sample of items from each ...
Return a random sample of items from each group. You can use `random_state` for reproducibility. Parameters ---------- n : int, optional Number of items to return for each group. Cannot be used with `frac` and must be no larger than the smallest group unless `replace` is T...
groupby_sample
python
mars-project/mars
mars/dataframe/groupby/sample.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/sample.py
Apache-2.0
def groupby_transform( groupby, f, *args, dtypes=None, dtype=None, name=None, index=None, output_types=None, skip_infer=False, **kwargs, ): """ Call function producing a like-indexed DataFrame on each group and return a DataFrame having the same indexes as the origina...
Call function producing a like-indexed DataFrame on each group and return a DataFrame having the same indexes as the original object filled with the transformed values Parameters ---------- f : function Function to apply to each group. dtypes : Series, default None Specify...
groupby_transform
python
mars-project/mars
mars/dataframe/groupby/transform.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/groupby/transform.py
Apache-2.0
def _tree_getitem(cls, op): """ DataFrame doesn't store the index value except RangeIndex or specify `store=True` in `parse_index`, So we build a tree structure to avoid too much dependence for getitem node. """ out_series = op.outputs[0] combine_size = options.combine_si...
DataFrame doesn't store the index value except RangeIndex or specify `store=True` in `parse_index`, So we build a tree structure to avoid too much dependence for getitem node.
_tree_getitem
python
mars-project/mars
mars/dataframe/indexing/getitem.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/getitem.py
Apache-2.0
def df_insert(df, loc, column, value, allow_duplicates=False): """ Insert column into DataFrame at specified location. Raises a ValueError if `column` is already contained in the DataFrame, unless `allow_duplicates` is set to True. Parameters ---------- loc : int Insertion index. M...
Insert column into DataFrame at specified location. Raises a ValueError if `column` is already contained in the DataFrame, unless `allow_duplicates` is set to True. Parameters ---------- loc : int Insertion index. Must verify 0 <= loc <= len(columns). column : str, number, or hash...
df_insert
python
mars-project/mars
mars/dataframe/indexing/insert.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/insert.py
Apache-2.0
def df_rename( df, mapper=None, index=None, columns=None, axis="index", copy=True, inplace=False, level=None, errors="ignore", ): """ Alter axes labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra ...
Alter axes labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don't throw an error. Parameters ---------- mapper : dict-like or function Dict-like or functions transformations to apply to ...
df_rename
python
mars-project/mars
mars/dataframe/indexing/rename.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py
Apache-2.0
def series_rename( series, index=None, *, axis="index", copy=True, inplace=False, level=None, errors="ignore" ): """ Alter Series index labels or name. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra label...
Alter Series index labels or name. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don't throw an error. Alternatively, change ``Series.name`` with a scalar value. Parameters ---------- axis : {0 or "inde...
series_rename
python
mars-project/mars
mars/dataframe/indexing/rename.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py
Apache-2.0
def index_rename(index, name, inplace=False): """ Alter Index or MultiIndex name. Able to set new names without level. Defaults to returning new index. Length of names must match number of levels in MultiIndex. Parameters ---------- name : label or list of labels Name(s) to set. ...
Alter Index or MultiIndex name. Able to set new names without level. Defaults to returning new index. Length of names must match number of levels in MultiIndex. Parameters ---------- name : label or list of labels Name(s) to set. inplace : bool, default False Modifies the ...
index_rename
python
mars-project/mars
mars/dataframe/indexing/rename.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py
Apache-2.0
def index_set_names(index, names, level=None, inplace=False): """ Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or list of int or label, optional If the ind...
Set Index or MultiIndex name. Able to set new names partially and by level. Parameters ---------- names : label or list of label Name(s) to set. level : int, label or list of int or label, optional If the index is a MultiIndex, level(s) to set (None for all levels). Ot...
index_set_names
python
mars-project/mars
mars/dataframe/indexing/rename.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename.py
Apache-2.0
def rename_axis( df_or_series, mapper=None, index=None, columns=None, axis=0, copy=True, inplace=False, ): """ Set the name of the axis for the index or columns. Parameters ---------- mapper : scalar, list-like, optional Value to set the axis name attribute. ...
Set the name of the axis for the index or columns. Parameters ---------- mapper : scalar, list-like, optional Value to set the axis name attribute. index, columns : scalar, list-like, dict-like or function, optional A scalar, list-like, dict-like or functions transformations to ...
rename_axis
python
mars-project/mars
mars/dataframe/indexing/rename_axis.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/rename_axis.py
Apache-2.0
def calc_columns_index(column_name, df): """ Calculate the chunk index on the axis 1 according to the selected column. :param column_name: selected column name :param df: input tiled DataFrame :return: chunk index on the columns axis """ column_nsplits = df.nsplits[1] # if has duplicate ...
Calculate the chunk index on the axis 1 according to the selected column. :param column_name: selected column name :param df: input tiled DataFrame :return: chunk index on the columns axis
calc_columns_index
python
mars-project/mars
mars/dataframe/indexing/utils.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/utils.py
Apache-2.0
def convert_labels_into_positions(pandas_index, labels): """ Convert labels into positions :param pandas_index: pandas Index :param labels: labels :return: positions """ result = [] for label in labels: loc = pandas_index.get_loc(label) if isinstance(loc, (int, np.intege...
Convert labels into positions :param pandas_index: pandas Index :param labels: labels :return: positions
convert_labels_into_positions
python
mars-project/mars
mars/dataframe/indexing/utils.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/indexing/utils.py
Apache-2.0
def merge( df: Union[DataFrame, Series], right: Union[DataFrame, Series], how: str = "inner", on: str = None, left_on: str = None, right_on: str = None, left_index: bool = False, right_index: bool = False, sort: bool = False, suffixes: Tuple[Optional[str], Optional[str]] = ("_x",...
Merge DataFrame or named Series objects with a database-style join. A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes *will be ignored*. Otherwise if joining indexes on indexes o...
merge
python
mars-project/mars
mars/dataframe/merge/merge.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/merge/merge.py
Apache-2.0
def join( df: Union[DataFrame, Series], other: Union[DataFrame, Series], on: str = None, how: str = "left", lsuffix: str = "", rsuffix: str = "", sort: bool = False, method: str = None, auto_merge: str = "both", auto_merge_threshold: int = 8, bloom_filter: Union[bool, Dict] =...
Join columns of another DataFrame. Join columns with `other` DataFrame either on index or on a key column. Efficiently join multiple DataFrame objects by index at once by passing a list. Parameters ---------- other : DataFrame, Series, or list of DataFrame Index should be similar ...
join
python
mars-project/mars
mars/dataframe/merge/merge.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/merge/merge.py
Apache-2.0
def df_dropna( df, axis=0, how=no_default, thresh=no_default, subset=None, inplace=False ): """ Remove missing values. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- axis : {0 or 'index'...
Remove missing values. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 Determine if rows or columns which contain missing values are ...
df_dropna
python
mars-project/mars
mars/dataframe/missing/dropna.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/dropna.py
Apache-2.0
def series_dropna(series, axis=0, inplace=False, how=None): """ Return a new Series with missing values removed. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- axis : {0 or 'index'}, default...
Return a new Series with missing values removed. See the :ref:`User Guide <missing_data>` for more on which values are considered missing, and how to work with missing data. Parameters ---------- axis : {0 or 'index'}, default 0 There is only one axis to drop values from. inplace ...
series_dropna
python
mars-project/mars
mars/dataframe/missing/dropna.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/dropna.py
Apache-2.0
def index_dropna(index, how="any"): """ Return Index without NA/NaN values. Parameters ---------- how : {'any', 'all'}, default 'any' If the Index is a MultiIndex, drop the value when any or all levels are NaN. Returns ------- Index """ use_inf_as_na = options.d...
Return Index without NA/NaN values. Parameters ---------- how : {'any', 'all'}, default 'any' If the Index is a MultiIndex, drop the value when any or all levels are NaN. Returns ------- Index
index_dropna
python
mars-project/mars
mars/dataframe/missing/dropna.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/dropna.py
Apache-2.0
def ffill(df, axis=None, inplace=False, limit=None, downcast=None): """ Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``. Returns ------- {klass} or None Object with missing values filled or None if ``inplace=True``. """ return fillna( df, method="ffill", axis=ax...
Synonym for :meth:`DataFrame.fillna` with ``method='ffill'``. Returns ------- {klass} or None Object with missing values filled or None if ``inplace=True``.
ffill
python
mars-project/mars
mars/dataframe/missing/fillna.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/fillna.py
Apache-2.0
def bfill(df, axis=None, inplace=False, limit=None, downcast=None): """ Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``. Returns ------- {klass} or None Object with missing values filled or None if ``inplace=True``. """ return fillna( df, method="bfill", axis=ax...
Synonym for :meth:`DataFrame.fillna` with ``method='bfill'``. Returns ------- {klass} or None Object with missing values filled or None if ``inplace=True``.
bfill
python
mars-project/mars
mars/dataframe/missing/fillna.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/fillna.py
Apache-2.0
def index_fillna(index, value=None, downcast=None): """ Fill NA/NaN values with the specified value. Parameters ---------- value : scalar Scalar value to use to fill holes (e.g. 0). This value cannot be a list-likes. downcast : dict, default is None A dict of item->dtype...
Fill NA/NaN values with the specified value. Parameters ---------- value : scalar Scalar value to use to fill holes (e.g. 0). This value cannot be a list-likes. downcast : dict, default is None A dict of item->dtype of what to downcast if possible, or the string 'in...
index_fillna
python
mars-project/mars
mars/dataframe/missing/fillna.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/missing/fillna.py
Apache-2.0
def _generate_function_str(self, out_tileable): """ Generate python code from tileable DAG """ from ...tensor.arithmetic.core import TensorBinOp, TensorUnaryOp from ...tensor.base import TensorWhere from ...tensor.datasource import Scalar from ..arithmetic.core im...
Generate python code from tileable DAG
_generate_function_str
python
mars-project/mars
mars/dataframe/reduction/core.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/reduction/core.py
Apache-2.0
def nunique_dataframe(df, axis=0, dropna=True, combine_size=None): """ Count distinct observations over requested axis. Return Series with number of distinct observations. Can ignore NaN values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to use....
Count distinct observations over requested axis. Return Series with number of distinct observations. Can ignore NaN values. Parameters ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The axis to use. 0 or 'index' for row-wise, 1 or 'columns' for column-wise. dr...
nunique_dataframe
python
mars-project/mars
mars/dataframe/reduction/nunique.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/reduction/nunique.py
Apache-2.0
def nunique_series(series, dropna=True, combine_size=None): """ Return number of unique elements in the object. Excludes NA values by default. Parameters ---------- dropna : bool, default True Don't include NaN in the count. combine_size : int, optional The number of chunks...
Return number of unique elements in the object. Excludes NA values by default. Parameters ---------- dropna : bool, default True Don't include NaN in the count. combine_size : int, optional The number of chunks to combine. Returns ------- int See Also ---...
nunique_series
python
mars-project/mars
mars/dataframe/reduction/nunique.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/reduction/nunique.py
Apache-2.0
def df_corrwith(df, other, axis=0, drop=False, method="pearson"): """ Compute pairwise correlation. Pairwise correlation is computed between rows or columns of DataFrame with rows or columns of Series or DataFrame. DataFrames are first aligned along both axes before computing the correlations. ...
Compute pairwise correlation. Pairwise correlation is computed between rows or columns of DataFrame with rows or columns of Series or DataFrame. DataFrames are first aligned along both axes before computing the correlations. Parameters ---------- other : DataFrame, Series Obje...
df_corrwith
python
mars-project/mars
mars/dataframe/statistics/corr.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/statistics/corr.py
Apache-2.0
def quantile_series(series, q=0.5, interpolation="linear"): """ Return value at the given quantile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) 0 <= q <= 1, the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} ...
Return value at the given quantile. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) 0 <= q <= 1, the quantile(s) to compute. interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} This optional parameter specifies the interpolation method to...
quantile_series
python
mars-project/mars
mars/dataframe/statistics/quantile.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/statistics/quantile.py
Apache-2.0
def quantile_dataframe(df, q=0.5, axis=0, numeric_only=True, interpolation="linear"): """ Return values at the given quantile over requested axis. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value between 0 <= q <= 1, the quantile(s) to compute. axis : {0, ...
Return values at the given quantile over requested axis. Parameters ---------- q : float or array-like, default 0.5 (50% quantile) Value between 0 <= q <= 1, the quantile(s) to compute. axis : {0, 1, 'index', 'columns'} (default 0) Equals 0 or 'index' for row-wise, 1 or 'columns' f...
quantile_dataframe
python
mars-project/mars
mars/dataframe/statistics/quantile.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/statistics/quantile.py
Apache-2.0
def ewm( obj, com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, ): r""" Provide exponential weighted functions. Parameters ---------- com : float, optional Specify decay in terms of center of mass, ...
Provide exponential weighted functions. Parameters ---------- com : float, optional Specify decay in terms of center of mass, :math:`\alpha = 1 / (1 + com),\text{ for } com \geq 0`. span : float, optional Specify decay in terms of span, :math:`\alpha = 2 / (span + 1...
ewm
python
mars-project/mars
mars/dataframe/window/ewm/core.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/window/ewm/core.py
Apache-2.0
def expanding(obj, min_periods=1, center=False, axis=0): """ Provide expanding transformations. Parameters ---------- min_periods : int, default 1 Minimum number of observations in window required to have a value (otherwise result is NA). center : bool, default False Set the labels ...
Provide expanding transformations. Parameters ---------- min_periods : int, default 1 Minimum number of observations in window required to have a value (otherwise result is NA). center : bool, default False Set the labels at the center of the window. axis : int or str, default 0 ...
expanding
python
mars-project/mars
mars/dataframe/window/expanding/core.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/window/expanding/core.py
Apache-2.0
def rolling( obj, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, ): """ Provide rolling window calculations. Parameters ---------- window : int, or offset Size of the moving window. This is the number of observations used...
Provide rolling window calculations. Parameters ---------- window : int, or offset Size of the moving window. This is the number of observations used for calculating the statistic. Each window will be a fixed size. If its an offset then this will be the time period of each wind...
rolling
python
mars-project/mars
mars/dataframe/window/rolling/core.py
https://github.com/mars-project/mars/blob/master/mars/dataframe/window/rolling/core.py
Apache-2.0
def _merge_config(full_config: Dict, config: Dict) -> Dict: """ Merge the config to full_config, the config support flatten key, e.g. config={ 'scheduling.autoscale.enabled': True, 'scheduling.autoscale.scheduler_check_interval': 1, 'scheduling.autoscale.scheduler_backlog_timeout': ...
Merge the config to full_config, the config support flatten key, e.g. config={ 'scheduling.autoscale.enabled': True, 'scheduling.autoscale.scheduler_check_interval': 1, 'scheduling.autoscale.scheduler_backlog_timeout': 1, 'scheduling.autoscale.worker_idle_timeout': 10, ...
_merge_config
python
mars-project/mars
mars/deploy/utils.py
https://github.com/mars-project/mars/blob/master/mars/deploy/utils.py
Apache-2.0
async def wait_all_supervisors_ready(endpoint): """ Wait till all containers are ready """ from ..services.cluster import ClusterAPI cluster_api = None while True: try: cluster_api = await ClusterAPI.create(endpoint) break except: # noqa: E722 # pylint...
Wait till all containers are ready
wait_all_supervisors_ready
python
mars-project/mars
mars/deploy/utils.py
https://github.com/mars-project/mars/blob/master/mars/deploy/utils.py
Apache-2.0
def new_cluster( kube_api_client=None, image=None, supervisor_num=1, supervisor_cpu=None, supervisor_mem=None, worker_num=1, worker_cpu=None, worker_mem=None, worker_spill_paths=None, worker_cache_mem=None, min_worker_num=None, web_num=1, web_cpu=None, web_mem=Non...
:param kube_api_client: Kubernetes API client, can be created with ``new_client_from_config`` :param image: Docker image to use, ``marsproject/mars:<mars version>`` by default :param supervisor_num: Number of supervisors in the cluster, 1 by default :param supervisor_cpu: Number of CPUs for every super...
new_cluster
python
mars-project/mars
mars/deploy/kubernetes/client.py
https://github.com/mars-project/mars/blob/master/mars/deploy/kubernetes/client.py
Apache-2.0
async def wait_all_supervisors_ready(self): """ Wait till all containers are ready """ await wait_all_supervisors_ready(self.args.endpoint)
Wait till all containers are ready
wait_all_supervisors_ready
python
mars-project/mars
mars/deploy/kubernetes/core.py
https://github.com/mars-project/mars/blob/master/mars/deploy/kubernetes/core.py
Apache-2.0
def new_ray_session( address: str = None, session_id: str = None, backend: str = "mars", default: bool = True, **new_cluster_kwargs, ) -> AbstractSession: """ Parameters ---------- address: str mars web server address. session_id: str session id. If not specified...
Parameters ---------- address: str mars web server address. session_id: str session id. If not specified, will be generated automatically. backend: str The executor backend. Available values are "mars" and "ray", default is "mars". default: bool whether set the ...
new_ray_session
python
mars-project/mars
mars/deploy/oscar/ray.py
https://github.com/mars-project/mars/blob/master/mars/deploy/oscar/ray.py
Apache-2.0
async def wait_all_supervisors_ready(self): """ Wait till all containers are ready, both in yarn and in Cluster Service """ await wait_all_supervisors_ready(self.args.endpoint)
Wait till all containers are ready, both in yarn and in Cluster Service
wait_all_supervisors_ready
python
mars-project/mars
mars/deploy/yarn/core.py
https://github.com/mars-project/mars/blob/master/mars/deploy/yarn/core.py
Apache-2.0
def score(self, X, y, sample_weight=None, session=None, run_kwargs=None): """ Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be c...
Return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. Parameters ---------- X : array-like of ...
score
python
mars-project/mars
mars/learn/base.py
https://github.com/mars-project/mars/blob/master/mars/learn/base.py
Apache-2.0
def score(self, X, y, sample_weight=None): """Return the coefficient of determination :math:`R^2` of the prediction. The coefficient :math:`R^2` is defined as :math:`(1 - \\frac{u}{v})`, where :math:`u` is the residual sum of squares ``((y_true - y_pred) ** 2).sum()`` and :math:...
Return the coefficient of determination :math:`R^2` of the prediction. The coefficient :math:`R^2` is defined as :math:`(1 - \frac{u}{v})`, where :math:`u` is the residual sum of squares ``((y_true - y_pred) ** 2).sum()`` and :math:`v` is the total sum of squares ``((y_true - y_...
score
python
mars-project/mars
mars/learn/base.py
https://github.com/mars-project/mars/blob/master/mars/learn/base.py
Apache-2.0
def _validate_data( self, X, y=None, reset=True, validate_separately=False, **check_params ): """Validate input data and set or check the `n_features_in_` attribute. Parameters ---------- X : {array-like, sparse matrix, dataframe} of shape \ (n_samples, n_fea...
Validate input data and set or check the `n_features_in_` attribute. Parameters ---------- X : {array-like, sparse matrix, dataframe} of shape (n_samples, n_features) The input samples. y : array-like of shape (n_samples,), default=None The target...
_validate_data
python
mars-project/mars
mars/learn/base.py
https://github.com/mars-project/mars/blob/master/mars/learn/base.py
Apache-2.0
def _check_method(self, method): """ Check if self.estimator has 'method'. Raises ------ AttributeError """ estimator = self.estimator if not hasattr(estimator, method): msg = "The wrapped estimator '{}' does not have a '{}' method.".format( ...
Check if self.estimator has 'method'. Raises ------ AttributeError
_check_method
python
mars-project/mars
mars/learn/wrappers.py
https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py
Apache-2.0
def transform(self, X): """ Transform block or partition-wise for Mars inputs. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not h...
Transform block or partition-wise for Mars inputs. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not have a ``transform`` method, then ...
transform
python
mars-project/mars
mars/learn/wrappers.py
https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py
Apache-2.0
def score(self, X, y): """ Returns the score on the given data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input data, where n_samples is the number of samples and n_features is the number of features. y : array-like, s...
Returns the score on the given data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input data, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] or [n_samples, ...
score
python
mars-project/mars
mars/learn/wrappers.py
https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py
Apache-2.0
def predict(self, X, execute=True): """ Predict for X. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. Parameters ---------- X : array-like ...
Predict for X. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. Parameters ---------- X : array-like Returns ------- y : array-like ...
predict
python
mars-project/mars
mars/learn/wrappers.py
https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py
Apache-2.0
def predict_proba(self, X, execute=True): """ Probability estimates. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not have a ``pr...
Probability estimates. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not have a ``predict_proba`` method, then an ``AttributeErro...
predict_proba
python
mars-project/mars
mars/learn/wrappers.py
https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py
Apache-2.0
def predict_log_proba(self, X, execute=True): """ Log of probability estimates. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not ...
Log of probability estimates. For Mars inputs, a Mars tensor is returned. For other inputs (NumPy array, pandas dataframe, scipy sparse matrix), the regular return value is returned. If the underlying estimator does not have a ``predict_proba`` method, then an ``Attrib...
predict_log_proba
python
mars-project/mars
mars/learn/wrappers.py
https://github.com/mars-project/mars/blob/master/mars/learn/wrappers.py
Apache-2.0
def _validate_center_shape(X, n_centers, centers): """Check if centers is compatible with X and n_centers""" if len(centers) != n_centers: raise ValueError( "The shape of the initial centers (%s) " "does not match the number of clusters %i" % (centers.shape, n_centers) ) ...
Check if centers is compatible with X and n_centers
_validate_center_shape
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def _tolerance(X, tol): """Return a tolerance which is independent of the dataset""" variances = mt.var(X, axis=0) return mt.mean(variances) * tol
Return a tolerance which is independent of the dataset
_tolerance
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def _check_normalize_sample_weight(sample_weight, X): """Set sample_weight if None, and check for correct dtype""" sample_weight_was_none = sample_weight is None sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) if not sample_weight_was_none: # normalize the weights to sum ...
Set sample_weight if None, and check for correct dtype
_check_normalize_sample_weight
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def k_means( X, n_clusters, sample_weight=None, init="k-means||", n_init=10, max_iter=300, verbose=False, tol=1e-4, random_state=None, copy_x=True, algorithm="auto", oversampling_factor=2, init_iter=5, return_n_iter=False, ): """K-means clustering algorithm. ...
K-means clustering algorithm. Parameters ---------- X : Tensor, shape (n_samples, n_features) The observations to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. n_clusters : int ...
k_means
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def _labels_inertia( X, sample_weight, x_squared_norms, centers, session=None, run_kwargs=None ): """E step of the K-means EM algorithm. Compute the labels and the inertia of the given samples and centers. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) ...
E step of the K-means EM algorithm. Compute the labels and the inertia of the given samples and centers. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples to assign to the labels. If sparse matrix, must be in CSR format. sampl...
_labels_inertia
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def _init_centroids( X, n_clusters=8, init="k-means++", random_state=None, x_squared_norms=None, init_size=None, oversampling_factor=2, init_iter=5, ): """Compute the initial centroids Parameters ---------- X : Tensor of shape (n_samples, n_features) The input s...
Compute the initial centroids Parameters ---------- X : Tensor of shape (n_samples, n_features) The input samples. n_clusters : int, default=8 number of centroids. init : {'k-means++', 'k-means||', 'random', tensor, callable}, default="k-means++" Method for initialization...
_init_centroids
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def fit(self, X, y=None, sample_weight=None, session=None, run_kwargs=None): """Compute k-means clustering. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training instances to cluster. It must be noted that the data will b...
Compute k-means clustering. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data ...
fit
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def fit_predict(self, X, y=None, sample_weight=None, session=None, run_kwargs=None): """Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters ---------- X : {array-like, spa...
Compute cluster centers and predict cluster index for each sample. Convenience method; equivalent to calling fit(X) followed by predict(X). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data to transform. y : Ign...
fit_predict
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def fit_transform( self, X, y=None, sample_weight=None, session=None, run_kwargs=None ): """Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters ---------- X : {array-like, spar...
Compute clustering and transform X to cluster-distance space. Equivalent to fit(X).transform(X), but more efficiently implemented. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data to transform. y : Ignored ...
fit_transform
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def transform(self, X, session=None, run_kwargs=None): """Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by `transform` will typically be dense. Parameters ...
Transform X to a cluster-distance space. In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by `transform` will typically be dense. Parameters ---------- X : {array-like, sparse matrix} of shape (n...
transform
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def _transform(self, X, session=None, run_kwargs=None): """guts of transform method; no input validation""" return euclidean_distances(X, self.cluster_centers_).execute( session=session, **(run_kwargs or dict()) )
guts of transform method; no input validation
_transform
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def predict(self, X, sample_weight=None, session=None, run_kwargs=None): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in...
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : {array-like, spar...
predict
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def score(self, X, y=None, sample_weight=None, session=None, run_kwargs=None): """Opposite of the value of X on the K-means objective. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data. y : Ignored Not used, ...
Opposite of the value of X on the K-means objective. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) New data. y : Ignored Not used, present here for API consistency by convention. sample_weight : array-like of sha...
score
python
mars-project/mars
mars/learn/cluster/_kmeans.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_kmeans.py
Apache-2.0
def _k_init(X, n_clusters, x_squared_norms, random_state, n_local_trials=None): """Init n_clusters seeds according to k-means++ Parameters ---------- X : array or sparse matrix, shape (n_samples, n_features) The data to pick seeds for. To avoid memory copy, the input data should be doub...
Init n_clusters seeds according to k-means++ Parameters ---------- X : array or sparse matrix, shape (n_samples, n_features) The data to pick seeds for. To avoid memory copy, the input data should be double precision (dtype=np.float64). n_clusters : integer The number of seeds ...
_k_init
python
mars-project/mars
mars/learn/cluster/_k_means_init.py
https://github.com/mars-project/mars/blob/master/mars/learn/cluster/_k_means_init.py
Apache-2.0
def pick_workers(workers, size): """ Pick workers from a list. This method will try to pick workers as balanced as it can. 1. If size <= len(workers), randomly pick workers from the list. 2. If size > len(workers), just select all workers in a random order, then see the rest size, if it's s...
Pick workers from a list. This method will try to pick workers as balanced as it can. 1. If size <= len(workers), randomly pick workers from the list. 2. If size > len(workers), just select all workers in a random order, then see the rest size, if it's still more than the workers size, ...
pick_workers
python
mars-project/mars
mars/learn/contrib/utils.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/utils.py
Apache-2.0
def run_pytorch_script( script: Union[bytes, str, BinaryIO, TextIO], n_workers: int, 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, Any] = None, port: ...
Run PyTorch script in Mars cluster. Parameters ---------- script: str or file-like object Script to run n_workers : int Number of PyTorch workers data : dict Variable name to data. gpu : bool Run PyTorch script on GPU command_argv : list Extra co...
run_pytorch_script
python
mars-project/mars
mars/learn/contrib/pytorch/run_script.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/pytorch/run_script.py
Apache-2.0
def to_tf(self) -> "tf.data.Dataset": """Get TF Dataset. convert into a tensorflow.data.Dataset """ def make_generator(): # pragma: no cover if not self._executed: self._execute() self._executed = True for i in range(len(self._t...
Get TF Dataset. convert into a tensorflow.data.Dataset
to_tf
python
mars-project/mars
mars/learn/contrib/tensorflow/dataset.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/tensorflow/dataset.py
Apache-2.0
def gen_tensorflow_dataset( tensors, output_shapes: Tuple[int, ...] = None, output_types: Tuple[np.dtype, ...] = None, fetch_kwargs=None, ): """ convert mars data type to tf.data.Dataset. Note this is based tensorflow 2.0 For example ----------- >>> # convert a tensor to tf.data.Data...
convert mars data type to tf.data.Dataset. Note this is based tensorflow 2.0 For example ----------- >>> # convert a tensor to tf.data.Dataset. >>> data = mt.tensor([[1, 2], [3, 4]]) >>> dataset = gen_tensorflow_dataset(data) >>> list(dataset.as_numpy_iterator()) [array([1, 2]), array([...
gen_tensorflow_dataset
python
mars-project/mars
mars/learn/contrib/tensorflow/dataset.py
https://github.com/mars-project/mars/blob/master/mars/learn/contrib/tensorflow/dataset.py
Apache-2.0
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 test_make_classification_informative_features(setup): """Test the construction of informative features in make_classification Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and fully-specified `weights`. """ # Create very separate clusters; check that vertices are unique and # ...
Test the construction of informative features in make_classification Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and fully-specified `weights`.
test_make_classification_informative_features
python
mars-project/mars
mars/learn/datasets/tests/test_samples_generator.py
https://github.com/mars-project/mars/blob/master/mars/learn/datasets/tests/test_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 _infer_dimension(spectrum, n_samples): """Infers the dimension of a dataset with a given spectrum. The returned value will be in [1, n_features - 1]. """ xp = get_array_module(spectrum, nosparse=True) ll = xp.empty_like(spectrum) ll[0] = -np.inf # we don't want to return n_components = 0 ...
Infers the dimension of a dataset with a given spectrum. The returned value will be in [1, n_features - 1].
_infer_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(self, X, session=None, run=True, run_kwargs=None): """Dispatch to the right submethod depending on the chosen solver.""" # Raise an error for sparse input. # This is more informative than the generic one raised by check_array. if (hasattr(X, "issparse") and X.issparse()) or iss...
Dispatch to the right submethod depending on the chosen solver.
_fit
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