Search is not available for this dataset
text
stringlengths
75
104k
def _apply_func_to_list_of_partitions(self, func, partitions, **kwargs): """Applies a function to a list of remote partitions. Note: The main use for this is to preprocess the func. Args: func: The func to apply partitions: The list of partitions Returns: ...
def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False): """Applies a function to select indices. Note: Your internal function must take a kwarg `internal_indices` for this to work correctly. This prevents information leakage of the internal index to th...
def apply_func_to_select_indices_along_full_axis( self, axis, func, indices, keep_remaining=False ): """Applies a function to a select subset of full columns/rows. Note: This should be used when you need to apply a function that relies on some global information for the entire c...
def apply_func_to_indices_both_axis( self, func, row_indices, col_indices, lazy=False, keep_remaining=True, mutate=False, item_to_distribute=None, ): """ Apply a function to along both axis Important: For your func to operate d...
def inter_data_operation(self, axis, func, other): """Apply a function that requires two BaseFrameManager objects. Args: axis: The axis to apply the function over (0 - rows, 1 - columns) func: The function to apply other: The other BaseFrameManager object to apply fu...
def manual_shuffle(self, axis, shuffle_func, lengths): """Shuffle the partitions based on the `shuffle_func`. Args: axis: The axis to shuffle across. shuffle_func: The function to apply before splitting the result. lengths: The length of each partition to split the r...
def read_parquet(path, engine="auto", columns=None, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Args: path: The filepath of the parquet file. We only support local files for now. engine: This argument doesn't do anything for now. kwargs: ...
def _make_parser_func(sep): """Creates a parser function from the given sep. Args: sep: The separator default to use for the parser. Returns: A function object. """ def parser_func( filepath_or_buffer, sep=sep, delimiter=None, header="infer", ...
def _read(**kwargs): """Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv """ pd_obj = BaseFactory.read_csv(**kwargs) # This happens when...
def read_sql( sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None, ): """ Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed o...
def read_parquet(cls, path, engine, columns, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the parquet file. We only support local files for now. ...
def _read(cls, **kwargs): """Read csv file from local disk. Args: filepath_or_buffer: The filepath of the csv file. We only support local files for now. kwargs: Keyword arguments in pandas.read_csv """ pd_obj = pandas.read_csv(*...
def auto_select_categorical_features(X, threshold=10): """Make a feature mask of categorical features in X. Features with less than 10 unique values are considered categorical. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix...
def _X_selected(X, selected): """Split X into selected features and other features""" n_features = X.shape[1] ind = np.arange(n_features) sel = np.zeros(n_features, dtype=bool) sel[np.asarray(selected)] = True non_sel = np.logical_not(sel) n_selected = np.sum(sel) X_sel = X[:, ind[sel]] ...
def _transform_selected(X, transform, selected, copy=True): """Apply a transform function to portion of selected features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. transform : callable A callable transform(X)...
def _matrix_adjust(self, X): """Adjust all values in X to encode for NaNs and infinities in the data. Parameters ---------- X : array-like, shape=(n_samples, n_feature) Input array of type int. Returns ------- X : array-like, shape=(n_samples, n_feat...
def _fit_transform(self, X): """Assume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array( ...
def fit_transform(self, X, y=None): """Fit OneHotEncoder to X, then transform X. Equivalent to self.fit(X).transform(X), but more convenient and more efficient. See fit for the parameters, transform for the return value. Parameters ---------- X : array-like or sparse ma...
def _transform(self, X): """Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array(X, accept_spar...
def transform(self, X): """Transform X using one-hot encoding. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. Returns ------- X_out : sparse matrix if sparse=True else a 2-d array, d...
def fit(self, features, target, sample_weight=None, groups=None): """Fit an optimized machine learning pipeline. Uses genetic programming to optimize a machine learning pipeline that maximizes score on the provided features and target. Performs internal k-fold cross-validaton to avoid o...
def _setup_memory(self): """Setup Memory object for memory caching. """ if self.memory: if isinstance(self.memory, str): if self.memory == "auto": # Create a temporary folder to store the transformers of the pipeline self._cache...
def _update_top_pipeline(self): """Helper function to update the _optimized_pipeline field.""" # Store the pipeline with the highest internal testing score if self._pareto_front: self._optimized_pipeline_score = -float('inf') for pipeline, pipeline_scores in zip(self._par...
def _summary_of_best_pipeline(self, features, target): """Print out best pipeline at the end of optimization process. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix target: array-like {n_samples} List of class labels fo...
def predict(self, features): """Use the optimized pipeline to predict the target for a feature set. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix Returns ---------- array-like: {n_samples} Predicted tar...
def fit_predict(self, features, target, sample_weight=None, groups=None): """Call fit and predict in sequence. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix target: array-like {n_samples} List of class labels for predic...
def score(self, testing_features, testing_target): """Return the score on the given testing data using the user-specified scoring function. Parameters ---------- testing_features: array-like {n_samples, n_features} Feature matrix of the testing set testing_target: ar...
def predict_proba(self, features): """Use the optimized pipeline to estimate the class probabilities for a feature set. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix of the testing set Returns ------- array-like: {...
def clean_pipeline_string(self, individual): """Provide a string of the individual without the parameter prefixes. Parameters ---------- individual: individual Individual which should be represented by a pretty string Returns ------- A string like st...
def _check_periodic_pipeline(self, gen): """If enough time has passed, save a new optimized pipeline. Currently used in the per generation hook in the optimization loop. Parameters ---------- gen: int Generation number Returns ------- None """...
def export(self, output_file_name, data_file_path=''): """Export the optimized pipeline as Python code. Parameters ---------- output_file_name: string String containing the path and file name of the desired output file data_file_path: string (default: '') ...
def _impute_values(self, features): """Impute missing values in a feature set. Parameters ---------- features: array-like {n_samples, n_features} A feature matrix Returns ------- array-like {n_samples, n_features} """ if self.verbosit...
def _check_dataset(self, features, target, sample_weight=None): """Check if a dataset has a valid feature set and labels. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix target: array-like {n_samples} or None List of clas...
def _compile_to_sklearn(self, expr): """Compile a DEAP pipeline into a sklearn pipeline. Parameters ---------- expr: DEAP individual The DEAP pipeline to be compiled Returns ------- sklearn_pipeline: sklearn.pipeline.Pipeline """ skle...
def _set_param_recursive(self, pipeline_steps, parameter, value): """Recursively iterate through all objects in the pipeline and set a given parameter. Parameters ---------- pipeline_steps: array-like List of (str, obj) tuples from a scikit-learn pipeline or related object ...
def _stop_by_max_time_mins(self): """Stop optimization process once maximum minutes have elapsed.""" if self.max_time_mins: total_mins_elapsed = (datetime.now() - self._start_datetime).total_seconds() / 60. if total_mins_elapsed >= self.max_time_mins: raise Keyboa...
def _combine_individual_stats(self, operator_count, cv_score, individual_stats): """Combine the stats with operator count and cv score and preprare to be written to _evaluated_individuals Parameters ---------- operator_count: int number of components in the pipeline ...
def _evaluate_individuals(self, population, features, target, sample_weight=None, groups=None): """Determine the fit of the provided individuals. Parameters ---------- population: a list of DEAP individual One individual is a list of pipeline operators and model parameters t...
def _preprocess_individuals(self, individuals): """Preprocess DEAP individuals before pipeline evaluation. Parameters ---------- individuals: a list of DEAP individual One individual is a list of pipeline operators and model parameters that can be compiled by DEA...
def _update_evaluated_individuals_(self, result_score_list, eval_individuals_str, operator_counts, stats_dicts): """Update self.evaluated_individuals_ and error message during pipeline evaluation. Parameters ---------- result_score_list: list A list of CV scores for evaluate...
def _update_pbar(self, pbar_num=1, pbar_msg=None): """Update self._pbar and error message during pipeline evaluation. Parameters ---------- pbar_num: int How many pipelines has been processed pbar_msg: None or string Error message Returns ...
def _random_mutation_operator(self, individual, allow_shrink=True): """Perform a replacement, insertion, or shrink mutation on an individual. Parameters ---------- individual: DEAP individual A list of pipeline operators and model parameters that can be compiled ...
def _gen_grow_safe(self, pset, min_, max_, type_=None): """Generate an expression where each leaf might have a different depth between min_ and max_. Parameters ---------- pset: PrimitiveSetTyped Primitive set from which primitives are selected. min_: int ...
def _operator_count(self, individual): """Count the number of pipeline operators as a measure of pipeline complexity. Parameters ---------- individual: list A grown tree with leaves at possibly different depths dependending on the condition function. Ret...
def _update_val(self, val, result_score_list): """Update values in the list of result scores and self._pbar during pipeline evaluation. Parameters ---------- val: float or "Timeout" CV scores result_score_list: list A list of CV scores Returns ...
def _generate(self, pset, min_, max_, condition, type_=None): """Generate a Tree as a list of lists. The tree is build from the root to the leaves, and it stop growing when the condition is fulfilled. Parameters ---------- pset: PrimitiveSetTyped Primitive s...
def transform(self, X): """Select categorical features and transform them using OneHotEncoder. Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. Returns ...
def transform(self, X): """Select continuous features and transform them using PCA. Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. Returns ---...
def fit(self, X, y=None, **fit_params): """Fit the StackingEstimator meta-transformer. Parameters ---------- X: array-like of shape (n_samples, n_features) The training input samples. y: array-like, shape (n_samples,) The target values (integers that corr...
def transform(self, X): """Transform data by adding two synthetic feature(s). Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- ...
def balanced_accuracy(y_true, y_pred): """Default scoring function: balanced accuracy. Balanced accuracy computes each class' accuracy on a per-class basis using a one-vs-rest encoding, then computes an unweighted average of the class accuracies. Parameters ---------- y_true: numpy.ndarray {n_...
def transform(self, X, y=None): """Transform data by adding two virtual features. Parameters ---------- X: numpy ndarray, {n_samples, n_components} New data, where n_samples is the number of samples and n_components is the number of components. y: None ...
def source_decode(sourcecode, verbose=0): """Decode operator source and import operator class. Parameters ---------- sourcecode: string a string of operator source (e.g 'sklearn.feature_selection.RFE') verbose: int, optional (default: 0) How much information TPOT communicates while ...
def set_sample_weight(pipeline_steps, sample_weight=None): """Recursively iterates through all objects in the pipeline and sets sample weight. Parameters ---------- pipeline_steps: array-like List of (str, obj) tuples from a scikit-learn pipeline or related object sample_weight: array-like ...
def TPOTOperatorClassFactory(opsourse, opdict, BaseClass=Operator, ArgBaseClass=ARGType, verbose=0): """Dynamically create operator class. Parameters ---------- opsourse: string operator source in config dictionary (key) opdict: dictionary operator params in config dictionary (value...
def positive_integer(value): """Ensure that the provided value is a positive integer. Parameters ---------- value: int The number to evaluate Returns ------- value: int Returns a positive integer """ try: value = int(value) except Exception: rais...
def float_range(value): """Ensure that the provided value is a float integer in the range [0., 1.]. Parameters ---------- value: float The number to evaluate Returns ------- value: float Returns a float in the range (0., 1.) """ try: value = float(value) ...
def _get_arg_parser(): """Main function that is called when TPOT is run on the command line.""" parser = argparse.ArgumentParser( description=( 'A Python tool that automatically creates and optimizes machine ' 'learning pipelines using genetic programming.' ), add...
def load_scoring_function(scoring_func): """ converts mymodule.myfunc in the myfunc object itself so tpot receives a scoring function """ if scoring_func and ("." in scoring_func): try: module_name, func_name = scoring_func.rsplit('.', 1) module_path = os.getcwd() ...
def tpot_driver(args): """Perform a TPOT run.""" if args.VERBOSITY >= 2: _print_args(args) input_data = _read_data_file(args) features = input_data.drop(args.TARGET_NAME, axis=1) training_features, testing_features, training_target, testing_target = \ train_test_split(features, inp...
def fit(self, X, y=None): """Fit FeatureSetSelector for feature selection Parameters ---------- X: array-like of shape (n_samples, n_features) The training input samples. y: array-like, shape (n_samples,) The target values (integers that correspond to cla...
def transform(self, X): """Make subset after fit Parameters ---------- X: numpy ndarray, {n_samples, n_features} New data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_transformed: array-like, s...
def _get_support_mask(self): """ Get the boolean mask indicating which features are selected Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention. """ ...
def pick_two_individuals_eligible_for_crossover(population): """Pick two individuals from the population which can do crossover, that is, they share a primitive. Parameters ---------- population: array of individuals Returns ---------- tuple: (individual, individual) Two individual...
def mutate_random_individual(population, toolbox): """Picks a random individual from the population, and performs mutation on a copy of it. Parameters ---------- population: array of individuals Returns ---------- individual: individual An individual which is a mutated copy of one ...
def varOr(population, toolbox, lambda_, cxpb, mutpb): """Part of an evolutionary algorithm applying only the variation part (crossover, mutation **or** reproduction). The modified individuals have their fitness invalidated. The individuals are cloned so returned population is independent of the input po...
def initialize_stats_dict(individual): ''' Initializes the stats dict for individual The statistics initialized are: 'generation': generation in which the individual was evaluated. Initialized as: 0 'mutation_count': number of mutation operations applied to the individual and its predecessor...
def eaMuPlusLambda(population, toolbox, mu, lambda_, cxpb, mutpb, ngen, pbar, stats=None, halloffame=None, verbose=0, per_generation_function=None): """This is the :math:`(\mu + \lambda)` evolutionary algorithm. :param population: A list of individuals. :param toolbox: A :class:`~deap.bas...
def cxOnePoint(ind1, ind2): """Randomly select in each individual and exchange each subtree with the point as root between each individual. :param ind1: First tree participating in the crossover. :param ind2: Second tree participating in the crossover. :returns: A tuple of two trees. """ # L...
def mutNodeReplacement(individual, pset): """Replaces a randomly chosen primitive from *individual* by a randomly chosen primitive no matter if it has the same number of arguments from the :attr:`pset` attribute of the individual. Parameters ---------- individual: DEAP individual A list ...
def _wrapped_cross_val_score(sklearn_pipeline, features, target, cv, scoring_function, sample_weight=None, groups=None, use_dask=False): """Fit estimator and compute scores for a given dataset split. Parameters ---------- sklearn_pipeline : pipe...
def get_by_name(opname, operators): """Return operator class instance by name. Parameters ---------- opname: str Name of the sklearn class that belongs to a TPOT operator operators: list List of operator classes from operator library Returns ------- ret_op_class: class ...
def export_pipeline(exported_pipeline, operators, pset, impute=False, pipeline_score=None, random_state=None, data_file_path=''): """Generate source code for a TPOT Pipeline. Parameters ---------- exported_pipeline: deap.cr...
def expr_to_tree(ind, pset): """Convert the unstructured DEAP pipeline into a tree data-structure. Parameters ---------- ind: deap.creator.Individual The pipeline that is being exported Returns ------- pipeline_tree: list List of operators in the current optimized pipeline ...
def generate_import_code(pipeline, operators, impute=False): """Generate all library import calls for use in TPOT.export(). Parameters ---------- pipeline: List List of operators in the current optimized pipeline operators: List of operator class from operator library impute : b...
def generate_pipeline_code(pipeline_tree, operators): """Generate code specific to the construction of the sklearn Pipeline. Parameters ---------- pipeline_tree: list List of operators in the current optimized pipeline Returns ------- Source code for the sklearn pipeline """ ...
def generate_export_pipeline_code(pipeline_tree, operators): """Generate code specific to the construction of the sklearn Pipeline for export_pipeline. Parameters ---------- pipeline_tree: list List of operators in the current optimized pipeline Returns ------- Source code for the ...
def _indent(text, amount): """Indent a multiline string by some number of spaces. Parameters ---------- text: str The text to be indented amount: int The number of spaces to indent the text Returns ------- indented_text """ indentation = amount * ' ' return...
def next(self): """Get the next value in the page.""" item = six.next(self._item_iter) result = self._item_to_value(self._parent, item) # Since we've successfully got the next value from the # iterator, we update the number of remaining. self._remaining -= 1 retur...
def _verify_params(self): """Verifies the parameters don't use any reserved parameter. Raises: ValueError: If a reserved parameter is used. """ reserved_in_use = self._RESERVED_PARAMS.intersection(self.extra_params) if reserved_in_use: raise ValueError("U...
def _next_page(self): """Get the next page in the iterator. Returns: Optional[Page]: The next page in the iterator or :data:`None` if there are no pages left. """ if self._has_next_page(): response = self._get_next_page_response() item...
def _get_query_params(self): """Getter for query parameters for the next request. Returns: dict: A dictionary of query parameters. """ result = {} if self.next_page_token is not None: result[self._PAGE_TOKEN] = self.next_page_token if self.max_res...
def _get_next_page_response(self): """Requests the next page from the path provided. Returns: dict: The parsed JSON response of the next page's contents. Raises: ValueError: If the HTTP method is not ``GET`` or ``POST``. """ params = self._get_query_para...
def _next_page(self): """Get the next page in the iterator. Wraps the response from the :class:`~google.gax.PageIterator` in a :class:`Page` instance and captures some state at each page. Returns: Optional[Page]: The next page in the iterator or :data:`None` if ...
def _next_page(self): """Get the next page in the iterator. Returns: Page: The next page in the iterator or :data:`None` if there are no pages left. """ if not self._has_next_page(): return None if self.next_page_token is not None: ...
def _has_next_page(self): """Determines whether or not there are more pages with results. Returns: bool: Whether the iterator has more pages. """ if self.page_number == 0: return True if self.max_results is not None: if self.num_results >= se...
def compare(cls, left, right): """ Main comparison function for all Firestore types. @return -1 is left < right, 0 if left == right, otherwise 1 """ # First compare the types. leftType = TypeOrder.from_value(left).value rightType = TypeOrder.from_value(right).valu...
def batch_annotate_files( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Service that performs image detection and annotation for a batch of files. Now only "applica...
def async_batch_annotate_images( self, requests, output_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Run asynchronous image detection and annotation for a list of images. ...
def async_batch_annotate_files( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Run asynchronous image detection and annotation for a list of generic files, such as P...
def load_ipython_extension(ipython): """Called by IPython when this module is loaded as an IPython extension.""" from google.cloud.bigquery.magics import _cell_magic ipython.register_magic_function( _cell_magic, magic_kind="cell", magic_name="bigquery" )
def from_http_status(status_code, message, **kwargs): """Create a :class:`GoogleAPICallError` from an HTTP status code. Args: status_code (int): The HTTP status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICallError` ...
def from_http_response(response): """Create a :class:`GoogleAPICallError` from a :class:`requests.Response`. Args: response (requests.Response): The HTTP response. Returns: GoogleAPICallError: An instance of the appropriate subclass of :class:`GoogleAPICallError`, with the mess...
def from_grpc_status(status_code, message, **kwargs): """Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`. Args: status_code (grpc.StatusCode): The gRPC status code. message (str): The exception message. kwargs: Additional arguments passed to the :class:`GoogleAPICal...
def from_grpc_error(rpc_exc): """Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`. Args: rpc_exc (grpc.RpcError): The gRPC error. Returns: GoogleAPICallError: An instance of the appropriate subclass of :class:`GoogleAPICallError`. """ if isinstance(rpc...
def _request(http, project, method, data, base_url): """Make a request over the Http transport to the Cloud Datastore API. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to make the request for. :type method: str...
def _rpc(http, project, method, base_url, request_pb, response_pb_cls): """Make a protobuf RPC request. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to connect to. This is usually your project na...
def build_api_url(project, method, base_url): """Construct the URL for a particular API call. This method is used internally to come up with the URL to use when making RPCs to the Cloud Datastore API. :type project: str :param project: The project to connect to. This is usually...
def lookup(self, project_id, keys, read_options=None): """Perform a ``lookup`` request. :type project_id: str :param project_id: The project to connect to. This is usually your project name in the cloud console. :type keys: List[.entity_pb2.Key] :para...
def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None ): """Perform a ``runQuery`` request. :type project_id: str :param project_id: The project to connect to. This is usually your project name in the cloud console. ...