text
stringlengths
81
112k
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: A list of BaseFramePartition objects. 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: A list of BaseFramePartition objects. """ preprocessed_func = self.preprocess_func(func) return [obj.apply(preprocessed_func, **kwargs) for obj in partitions]
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 the external representation. Args: axis: The axis to apply the func over. func: The function to apply to these indices. indices: The indices to apply the function to. keep_remaining: Whether or not to keep the other partitions. Some operations may want to drop the remaining partitions and keep only the results. Returns: A new BaseFrameManager object, the type of object that called this. 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 the external representation. Args: axis: The axis to apply the func over. func: The function to apply to these indices. indices: The indices to apply the function to. keep_remaining: Whether or not to keep the other partitions. Some operations may want to drop the remaining partitions and keep only the results. Returns: A new BaseFrameManager object, the type of object that called this. """ if self.partitions.size == 0: return np.array([[]]) # Handling dictionaries has to be done differently, but we still want # to figure out the partitions that need to be applied to, so we will # store the dictionary in a separate variable and assign `indices` to # the keys to handle it the same as we normally would. if isinstance(indices, dict): dict_indices = indices indices = list(indices.keys()) else: dict_indices = None if not isinstance(indices, list): indices = [indices] partitions_dict = self._get_dict_of_block_index( axis, indices, ordered=not keep_remaining ) if not axis: partitions_for_apply = self.partitions.T else: partitions_for_apply = self.partitions # We may have a command to perform different functions on different # columns at the same time. We attempt to handle this as efficiently as # possible here. Functions that use this in the dictionary format must # accept a keyword argument `func_dict`. if dict_indices is not None: def local_to_global_idx(partition_id, local_idx): if partition_id == 0: return local_idx if axis == 0: cumulative_axis = np.cumsum(self.block_widths) else: cumulative_axis = np.cumsum(self.block_lengths) return cumulative_axis[partition_id - 1] + local_idx if not keep_remaining: result = np.array( [ self._apply_func_to_list_of_partitions( func, partitions_for_apply[o_idx], func_dict={ i_idx: dict_indices[local_to_global_idx(o_idx, i_idx)] for i_idx in list_to_apply if i_idx >= 0 }, ) for o_idx, list_to_apply in partitions_dict ] ) else: result = np.array( [ partitions_for_apply[i] if i not in partitions_dict else self._apply_func_to_list_of_partitions( func, partitions_for_apply[i], func_dict={ idx: dict_indices[local_to_global_idx(i, idx)] for idx in partitions_dict[i] if idx >= 0 }, ) for i in range(len(partitions_for_apply)) ] ) else: if not keep_remaining: # We are passing internal indices in here. In order for func to # actually be able to use this information, it must be able to take in # the internal indices. This might mean an iloc in the case of Pandas # or some other way to index into the internal representation. result = np.array( [ self._apply_func_to_list_of_partitions( func, partitions_for_apply[idx], internal_indices=list_to_apply, ) for idx, list_to_apply in partitions_dict ] ) else: # The difference here is that we modify a subset and return the # remaining (non-updated) blocks in their original position. result = np.array( [ partitions_for_apply[i] if i not in partitions_dict else self._apply_func_to_list_of_partitions( func, partitions_for_apply[i], internal_indices=partitions_dict[i], ) for i in range(len(partitions_for_apply)) ] ) return ( self.__constructor__(result.T) if not axis else self.__constructor__(result) )
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 column/row, but only need to apply a function to a subset. Important: For your func to operate directly on the indices provided, it must use `internal_indices` as a keyword argument. Args: axis: The axis to apply the function over (0 - rows, 1 - columns) func: The function to apply. indices: The global indices to apply the func to. keep_remaining: Whether or not to keep the other partitions. Some operations may want to drop the remaining partitions and keep only the results. Returns: A new BaseFrameManager object, the type of object that called this. 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 column/row, but only need to apply a function to a subset. Important: For your func to operate directly on the indices provided, it must use `internal_indices` as a keyword argument. Args: axis: The axis to apply the function over (0 - rows, 1 - columns) func: The function to apply. indices: The global indices to apply the func to. keep_remaining: Whether or not to keep the other partitions. Some operations may want to drop the remaining partitions and keep only the results. Returns: A new BaseFrameManager object, the type of object that called this. """ if self.partitions.size == 0: return self.__constructor__(np.array([[]])) if isinstance(indices, dict): dict_indices = indices indices = list(indices.keys()) else: dict_indices = None if not isinstance(indices, list): indices = [indices] partitions_dict = self._get_dict_of_block_index(axis, indices) preprocessed_func = self.preprocess_func(func) # Since we might be keeping the remaining blocks that are not modified, # we have to also keep the block_partitions object in the correct # direction (transpose for columns). if not axis: partitions_for_apply = self.column_partitions partitions_for_remaining = self.partitions.T else: partitions_for_apply = self.row_partitions partitions_for_remaining = self.partitions # We may have a command to perform different functions on different # columns at the same time. We attempt to handle this as efficiently as # possible here. Functions that use this in the dictionary format must # accept a keyword argument `func_dict`. if dict_indices is not None: if not keep_remaining: result = np.array( [ partitions_for_apply[i].apply( preprocessed_func, func_dict={ idx: dict_indices[idx] for idx in partitions_dict[i] }, ) for i in partitions_dict ] ) else: result = np.array( [ partitions_for_remaining[i] if i not in partitions_dict else self._apply_func_to_list_of_partitions( preprocessed_func, partitions_for_apply[i], func_dict={ idx: dict_indices[idx] for idx in partitions_dict[i] }, ) for i in range(len(partitions_for_apply)) ] ) else: if not keep_remaining: # See notes in `apply_func_to_select_indices` result = np.array( [ partitions_for_apply[i].apply( preprocessed_func, internal_indices=partitions_dict[i] ) for i in partitions_dict ] ) else: # See notes in `apply_func_to_select_indices` result = np.array( [ partitions_for_remaining[i] if i not in partitions_dict else partitions_for_apply[i].apply( preprocessed_func, internal_indices=partitions_dict[i] ) for i in range(len(partitions_for_remaining)) ] ) return ( self.__constructor__(result.T) if not axis else self.__constructor__(result) )
Apply a function to along both axis Important: For your func to operate directly on the indices provided, it must use `row_internal_indices, col_internal_indices` as keyword arguments. 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 directly on the indices provided, it must use `row_internal_indices, col_internal_indices` as keyword arguments. """ if keep_remaining: row_partitions_list = self._get_dict_of_block_index(1, row_indices).items() col_partitions_list = self._get_dict_of_block_index(0, col_indices).items() else: row_partitions_list = self._get_dict_of_block_index( 1, row_indices, ordered=True ) col_partitions_list = self._get_dict_of_block_index( 0, col_indices, ordered=True ) result = np.empty( (len(row_partitions_list), len(col_partitions_list)), dtype=type(self) ) if not mutate: partition_copy = self.partitions.copy() else: partition_copy = self.partitions row_position_counter = 0 for row_idx, row_values in enumerate(row_partitions_list): row_blk_idx, row_internal_idx = row_values col_position_counter = 0 for col_idx, col_values in enumerate(col_partitions_list): col_blk_idx, col_internal_idx = col_values remote_part = partition_copy[row_blk_idx, col_blk_idx] if item_to_distribute is not None: item = item_to_distribute[ row_position_counter : row_position_counter + len(row_internal_idx), col_position_counter : col_position_counter + len(col_internal_idx), ] item = {"item": item} else: item = {} if lazy: block_result = remote_part.add_to_apply_calls( func, row_internal_indices=row_internal_idx, col_internal_indices=col_internal_idx, **item ) else: block_result = remote_part.apply( func, row_internal_indices=row_internal_idx, col_internal_indices=col_internal_idx, **item ) if keep_remaining: partition_copy[row_blk_idx, col_blk_idx] = block_result else: result[row_idx][col_idx] = block_result col_position_counter += len(col_internal_idx) row_position_counter += len(row_internal_idx) if keep_remaining: return self.__constructor__(partition_copy) else: return self.__constructor__(result)
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 func to. Returns: A new BaseFrameManager object, the type of object that called this. 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 func to. Returns: A new BaseFrameManager object, the type of object that called this. """ if axis: partitions = self.row_partitions other_partitions = other.row_partitions else: partitions = self.column_partitions other_partitions = other.column_partitions func = self.preprocess_func(func) result = np.array( [ partitions[i].apply( func, num_splits=self._compute_num_partitions(), other_axis_partition=other_partitions[i], ) for i in range(len(partitions)) ] ) return self.__constructor__(result) if axis else self.__constructor__(result.T)
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 result into. Returns: A new BaseFrameManager object, the type of object that called this. 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 result into. Returns: A new BaseFrameManager object, the type of object that called this. """ if axis: partitions = self.row_partitions else: partitions = self.column_partitions func = self.preprocess_func(shuffle_func) result = np.array([part.shuffle(func, lengths) for part in partitions]) return self.__constructor__(result) if axis else self.__constructor__(result.T)
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: Pass into parquet's read_pandas function. 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: Pass into parquet's read_pandas function. """ return DataFrame( query_compiler=BaseFactory.read_parquet( path=path, columns=columns, engine=engine, **kwargs ) )
Creates a parser function from the given sep. Args: sep: The separator default to use for the parser. Returns: A function object. 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", names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression="infer", thousands=None, decimal=b".", lineterminator=None, quotechar='"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=None, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, doublequote=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, ): _, _, _, kwargs = inspect.getargvalues(inspect.currentframe()) if not kwargs.get("sep", sep): kwargs["sep"] = "\t" return _read(**kwargs) return parser_func
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 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 `read_csv` returns a TextFileReader object for iterating through if isinstance(pd_obj, pandas.io.parsers.TextFileReader): reader = pd_obj.read pd_obj.read = lambda *args, **kwargs: DataFrame( query_compiler=reader(*args, **kwargs) ) return pd_obj return DataFrame(query_compiler=pd_obj)
Read SQL query or database table into a DataFrame. Args: sql: string or SQLAlchemy Selectable (select or text object) SQL query to be executed or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode) index_col: Column(s) to set as index(MultiIndex). coerce_float: Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. params: List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. parse_dates: - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. columns: List of column names to select from SQL table (only used when reading a table). chunksize: If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns: Modin Dataframe 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 or a table name. con: SQLAlchemy connectable (engine/connection) or database string URI or DBAPI2 connection (fallback mode) index_col: Column(s) to set as index(MultiIndex). coerce_float: Attempts to convert values of non-string, non-numeric objects (like decimal.Decimal) to floating point, useful for SQL result sets. params: List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. parse_dates: - List of column names to parse as dates. - Dict of ``{column_name: format string}`` where format string is strftime compatible in case of parsing string times, or is one of (D, s, ns, ms, us) in case of parsing integer timestamps. - Dict of ``{column_name: arg dict}``, where the arg dict corresponds to the keyword arguments of :func:`pandas.to_datetime` Especially useful with databases without native Datetime support, such as SQLite. columns: List of column names to select from SQL table (only used when reading a table). chunksize: If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. Returns: Modin Dataframe """ _, _, _, kwargs = inspect.getargvalues(inspect.currentframe()) return DataFrame(query_compiler=BaseFactory.read_sql(**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. engine: Ray only support pyarrow reader. This argument doesn't do anything for now. kwargs: Pass into parquet's read_pandas function. Notes: ParquetFile API is used. Please refer to the documentation here https://arrow.apache.org/docs/python/parquet.html 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. engine: Ray only support pyarrow reader. This argument doesn't do anything for now. kwargs: Pass into parquet's read_pandas function. Notes: ParquetFile API is used. Please refer to the documentation here https://arrow.apache.org/docs/python/parquet.html """ ErrorMessage.default_to_pandas("`read_parquet`") return cls.from_pandas(pandas.read_parquet(path, engine, columns, **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 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(**kwargs) if isinstance(pd_obj, pandas.DataFrame): return cls.from_pandas(pd_obj) if isinstance(pd_obj, pandas.io.parsers.TextFileReader): # Overwriting the read method should return a ray DataFrame for calls # to __next__ and get_chunk pd_read = pd_obj.read pd_obj.read = lambda *args, **kwargs: cls.from_pandas( pd_read(*args, **kwargs) ) return pd_obj
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. threshold : int Maximum number of unique values per feature to consider the feature to be categorical. Returns ------- feature_mask : array of booleans of size {n_features, } 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. threshold : int Maximum number of unique values per feature to consider the feature to be categorical. Returns ------- feature_mask : array of booleans of size {n_features, } """ feature_mask = [] for column in range(X.shape[1]): if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] unique = np.unique(X.data[indptr_start:indptr_end]) else: unique = np.unique(X[:, column]) feature_mask.append(len(unique) <= threshold) return feature_mask
Split X into selected features and other features 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]] X_not_sel = X[:, ind[non_sel]] return X_sel, X_not_sel, n_selected, n_features
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) -> X_transformed copy : boolean, optional Copy X even if it could be avoided. selected: "all", "auto" or array of indices or mask Specify which features to apply the transform to. Returns ------- X : array or sparse matrix, shape=(n_samples, n_features_new) 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) -> X_transformed copy : boolean, optional Copy X even if it could be avoided. selected: "all", "auto" or array of indices or mask Specify which features to apply the transform to. Returns ------- X : array or sparse matrix, shape=(n_samples, n_features_new) """ if selected == "all": return transform(X) if len(selected) == 0: return X X = check_array(X, accept_sparse='csc', force_all_finite=False) X_sel, X_not_sel, n_selected, n_features = _X_selected(X, selected) if n_selected == 0: # No features selected. return X elif n_selected == n_features: # All features selected. return transform(X) else: X_sel = transform(X_sel) if sparse.issparse(X_sel) or sparse.issparse(X_not_sel): return sparse.hstack((X_sel, X_not_sel), format='csr') else: return np.hstack((X_sel, X_not_sel))
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_feature) Input array without any NaNs or infinities. 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_feature) Input array without any NaNs or infinities. """ data_matrix = X.data if sparse.issparse(X) else X # Shift all values to specially encode for NAN/infinity/OTHER and 0 # Old value New Value # --------- --------- # N (0..int_max) N + 3 # np.NaN 2 # infinity 2 # *other* 1 # # A value of 0 is reserved, as that is specially handled in sparse # matrices. data_matrix += len(SPARSE_ENCODINGS) + 1 data_matrix[~np.isfinite(data_matrix)] = SPARSE_ENCODINGS['NAN'] return X
Assume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. 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( X, accept_sparse='csc', force_all_finite=False, dtype=int ) if X.min() < 0: raise ValueError("X needs to contain only non-negative integers.") n_samples, n_features = X.shape # Remember which values should not be replaced by the value 'other' if self.minimum_fraction is not None: do_not_replace_by_other = list() for column in range(X.shape[1]): do_not_replace_by_other.append(list()) if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] unique = np.unique(X.data[indptr_start:indptr_end]) colsize = indptr_end - indptr_start else: unique = np.unique(X[:, column]) colsize = X.shape[0] for unique_value in unique: if np.isfinite(unique_value): if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] count = np.nansum(unique_value == X.data[indptr_start:indptr_end]) else: count = np.nansum(unique_value == X[:, column]) else: if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] count = np.nansum(~np.isfinite( X.data[indptr_start:indptr_end])) else: count = np.nansum(~np.isfinite(X[:, column])) fraction = float(count) / colsize if fraction >= self.minimum_fraction: do_not_replace_by_other[-1].append(unique_value) for unique_value in unique: if unique_value not in do_not_replace_by_other[-1]: if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] X.data[indptr_start:indptr_end][ X.data[indptr_start:indptr_end] == unique_value] = SPARSE_ENCODINGS['OTHER'] else: X[:, column][X[:, column] == unique_value] = SPARSE_ENCODINGS['OTHER'] self.do_not_replace_by_other_ = do_not_replace_by_other if sparse.issparse(X): n_values = X.max(axis=0).toarray().flatten() + len(SPARSE_ENCODINGS) else: n_values = np.max(X, axis=0) + len(SPARSE_ENCODINGS) self.n_values_ = n_values n_values = np.hstack([[0], n_values]) indices = np.cumsum(n_values) self.feature_indices_ = indices if sparse.issparse(X): row_indices = X.indices column_indices = [] for i in range(len(X.indptr) - 1): nbr = X.indptr[i+1] - X.indptr[i] column_indices_ = [indices[i]] * nbr column_indices_ += X.data[X.indptr[i]:X.indptr[i+1]] column_indices.extend(column_indices_) data = np.ones(X.data.size) else: column_indices = (X + indices[:-1]).ravel() row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), n_features) data = np.ones(n_samples * n_features) out = sparse.coo_matrix((data, (row_indices, column_indices)), shape=(n_samples, indices[-1]), dtype=self.dtype).tocsc() mask = np.array(out.sum(axis=0)).ravel() != 0 active_features = np.where(mask)[0] out = out[:, active_features] self.active_features_ = active_features return out.tocsr() if self.sparse else out.toarray()
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 matrix, shape=(n_samples, n_features) Dense array or sparse matrix. y: array-like {n_samples,} (Optional, ignored) Feature labels 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 matrix, shape=(n_samples, n_features) Dense array or sparse matrix. y: array-like {n_samples,} (Optional, ignored) Feature labels """ if self.categorical_features == "auto": self.categorical_features = auto_select_categorical_features(X, threshold=self.threshold) return _transform_selected( X, self._fit_transform, self.categorical_features, copy=True )
Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. 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_sparse='csc', force_all_finite=False, dtype=int) if X.min() < 0: raise ValueError("X needs to contain only non-negative integers.") n_samples, n_features = X.shape indices = self.feature_indices_ if n_features != indices.shape[0] - 1: raise ValueError("X has different shape than during fitting." " Expected %d, got %d." % (indices.shape[0] - 1, n_features)) # Replace all indicators which were below `minimum_fraction` in the # training set by 'other' if self.minimum_fraction is not None: for column in range(X.shape[1]): if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] unique = np.unique(X.data[indptr_start:indptr_end]) else: unique = np.unique(X[:, column]) for unique_value in unique: if unique_value not in self.do_not_replace_by_other_[column]: if sparse.issparse(X): indptr_start = X.indptr[column] indptr_end = X.indptr[column + 1] X.data[indptr_start:indptr_end][ X.data[indptr_start:indptr_end] == unique_value] = SPARSE_ENCODINGS['OTHER'] else: X[:, column][X[:, column] == unique_value] = SPARSE_ENCODINGS['OTHER'] if sparse.issparse(X): n_values_check = X.max(axis=0).toarray().flatten() + 1 else: n_values_check = np.max(X, axis=0) + 1 # Replace all indicators which are out of bounds by 'other' (index 0) if (n_values_check > self.n_values_).any(): # raise ValueError("Feature out of bounds. Try setting n_values.") for i, n_value_check in enumerate(n_values_check): if (n_value_check - 1) >= self.n_values_[i]: if sparse.issparse(X): indptr_start = X.indptr[i] indptr_end = X.indptr[i+1] X.data[indptr_start:indptr_end][X.data[indptr_start:indptr_end] >= self.n_values_[i]] = 0 else: X[:, i][X[:, i] >= self.n_values_[i]] = 0 if sparse.issparse(X): row_indices = X.indices column_indices = [] for i in range(len(X.indptr) - 1): nbr = X.indptr[i + 1] - X.indptr[i] column_indices_ = [indices[i]] * nbr column_indices_ += X.data[X.indptr[i]:X.indptr[i + 1]] column_indices.extend(column_indices_) data = np.ones(X.data.size) else: column_indices = (X + indices[:-1]).ravel() row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), n_features) data = np.ones(n_samples * n_features) out = sparse.coo_matrix((data, (row_indices, column_indices)), shape=(n_samples, indices[-1]), dtype=self.dtype).tocsc() out = out[:, self.active_features_] return out.tocsr() if self.sparse else out.toarray()
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, dtype=int Transformed input. 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, dtype=int Transformed input. """ return _transform_selected( X, self._transform, self.categorical_features, copy=True )
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 overfitting on the provided data. The best pipeline is then trained on the entire set of provided samples. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix TPOT and all scikit-learn algorithms assume that the features will be numerical and there will be no missing values. As such, when a feature matrix is provided to TPOT, all missing values will automatically be replaced (i.e., imputed) using median value imputation. If you wish to use a different imputation strategy than median imputation, please make sure to apply imputation to your feature set prior to passing it to TPOT. target: array-like {n_samples} List of class labels for prediction sample_weight: array-like {n_samples}, optional Per-sample weights. Higher weights indicate more importance. If specified, sample_weight will be passed to any pipeline element whose fit() function accepts a sample_weight argument. By default, using sample_weight does not affect tpot's scoring functions, which determine preferences between pipelines. groups: array-like, with shape {n_samples, }, optional Group labels for the samples used when performing cross-validation. This parameter should only be used in conjunction with sklearn's Group cross-validation functions, such as sklearn.model_selection.GroupKFold Returns ------- self: object Returns a copy of the fitted TPOT object 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 overfitting on the provided data. The best pipeline is then trained on the entire set of provided samples. Parameters ---------- features: array-like {n_samples, n_features} Feature matrix TPOT and all scikit-learn algorithms assume that the features will be numerical and there will be no missing values. As such, when a feature matrix is provided to TPOT, all missing values will automatically be replaced (i.e., imputed) using median value imputation. If you wish to use a different imputation strategy than median imputation, please make sure to apply imputation to your feature set prior to passing it to TPOT. target: array-like {n_samples} List of class labels for prediction sample_weight: array-like {n_samples}, optional Per-sample weights. Higher weights indicate more importance. If specified, sample_weight will be passed to any pipeline element whose fit() function accepts a sample_weight argument. By default, using sample_weight does not affect tpot's scoring functions, which determine preferences between pipelines. groups: array-like, with shape {n_samples, }, optional Group labels for the samples used when performing cross-validation. This parameter should only be used in conjunction with sklearn's Group cross-validation functions, such as sklearn.model_selection.GroupKFold Returns ------- self: object Returns a copy of the fitted TPOT object """ self._fit_init() features, target = self._check_dataset(features, target, sample_weight) self.pretest_X, _, self.pretest_y, _ = train_test_split(features, target, train_size=min(50, int(0.9*features.shape[0])), test_size=None, random_state=self.random_state) # Randomly collect a subsample of training samples for pipeline optimization process. if self.subsample < 1.0: features, _, target, _ = train_test_split(features, target, train_size=self.subsample, test_size=None, random_state=self.random_state) # Raise a warning message if the training size is less than 1500 when subsample is not default value if features.shape[0] < 1500: print( 'Warning: Although subsample can accelerate pipeline optimization process, ' 'too small training sample size may cause unpredictable effect on maximizing ' 'score in pipeline optimization process. Increasing subsample ratio may get ' 'a more reasonable outcome from optimization process in TPOT.' ) # Set the seed for the GP run if self.random_state is not None: random.seed(self.random_state) # deap uses random np.random.seed(self.random_state) self._start_datetime = datetime.now() self._last_pipeline_write = self._start_datetime self._toolbox.register('evaluate', self._evaluate_individuals, features=features, target=target, sample_weight=sample_weight, groups=groups) # assign population, self._pop can only be not None if warm_start is enabled if self._pop: pop = self._pop else: pop = self._toolbox.population(n=self.population_size) def pareto_eq(ind1, ind2): """Determine whether two individuals are equal on the Pareto front. Parameters ---------- ind1: DEAP individual from the GP population First individual to compare ind2: DEAP individual from the GP population Second individual to compare Returns ---------- individuals_equal: bool Boolean indicating whether the two individuals are equal on the Pareto front """ return np.allclose(ind1.fitness.values, ind2.fitness.values) # Generate new pareto front if it doesn't already exist for warm start if not self.warm_start or not self._pareto_front: self._pareto_front = tools.ParetoFront(similar=pareto_eq) # Set lambda_ (offspring size in GP) equal to population_size by default if not self.offspring_size: self._lambda = self.population_size else: self._lambda = self.offspring_size # Start the progress bar if self.max_time_mins: total_evals = self.population_size else: total_evals = self._lambda * self.generations + self.population_size self._pbar = tqdm(total=total_evals, unit='pipeline', leave=False, disable=not (self.verbosity >= 2), desc='Optimization Progress') try: with warnings.catch_warnings(): self._setup_memory() warnings.simplefilter('ignore') pop, _ = eaMuPlusLambda( population=pop, toolbox=self._toolbox, mu=self.population_size, lambda_=self._lambda, cxpb=self.crossover_rate, mutpb=self.mutation_rate, ngen=self.generations, pbar=self._pbar, halloffame=self._pareto_front, verbose=self.verbosity, per_generation_function=self._check_periodic_pipeline ) # store population for the next call if self.warm_start: self._pop = pop # Allow for certain exceptions to signal a premature fit() cancellation except (KeyboardInterrupt, SystemExit, StopIteration) as e: if self.verbosity > 0: self._pbar.write('', file=self._file) self._pbar.write('{}\nTPOT closed prematurely. Will use the current best pipeline.'.format(e), file=self._file) finally: # keep trying 10 times in case weird things happened like multiple CTRL+C or exceptions attempts = 10 for attempt in range(attempts): try: # Close the progress bar # Standard truthiness checks won't work for tqdm if not isinstance(self._pbar, type(None)): self._pbar.close() self._update_top_pipeline() self._summary_of_best_pipeline(features, target) # Delete the temporary cache before exiting self._cleanup_memory() break except (KeyboardInterrupt, SystemExit, Exception) as e: # raise the exception if it's our last attempt if attempt == (attempts - 1): raise e return self
Setup Memory object for memory caching. 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._cachedir = mkdtemp() else: if not os.path.isdir(self.memory): try: os.makedirs(self.memory) except: raise ValueError( 'Could not create directory for memory caching: {}'.format(self.memory) ) self._cachedir = self.memory self._memory = Memory(cachedir=self._cachedir, verbose=0) elif isinstance(self.memory, Memory): self._memory = self.memory else: raise ValueError( 'Could not recognize Memory object for pipeline caching. ' 'Please provide an instance of sklearn.external.joblib.Memory,' ' a path to a directory on your system, or \"auto\".' )
Helper function to update the _optimized_pipeline field. 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._pareto_front.items, reversed(self._pareto_front.keys)): if pipeline_scores.wvalues[1] > self._optimized_pipeline_score: self._optimized_pipeline = pipeline self._optimized_pipeline_score = pipeline_scores.wvalues[1] if not self._optimized_pipeline: raise RuntimeError('There was an error in the TPOT optimization ' 'process. This could be because the data was ' 'not formatted properly, or because data for ' 'a regression problem was provided to the ' 'TPOTClassifier object. Please make sure you ' 'passed the data to TPOT correctly.') else: pareto_front_wvalues = [pipeline_scores.wvalues[1] for pipeline_scores in self._pareto_front.keys] if not self._last_optimized_pareto_front: self._last_optimized_pareto_front = pareto_front_wvalues elif self._last_optimized_pareto_front == pareto_front_wvalues: self._last_optimized_pareto_front_n_gens += 1 else: self._last_optimized_pareto_front = pareto_front_wvalues self._last_optimized_pareto_front_n_gens = 0 else: # If user passes CTRL+C in initial generation, self._pareto_front (halloffame) shoule be not updated yet. # need raise RuntimeError because no pipeline has been optimized raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.')
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 for prediction Returns ------- self: object Returns a copy of the fitted TPOT object 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 for prediction Returns ------- self: object Returns a copy of the fitted TPOT object """ if not self._optimized_pipeline: raise RuntimeError('There was an error in the TPOT optimization ' 'process. This could be because the data was ' 'not formatted properly, or because data for ' 'a regression problem was provided to the ' 'TPOTClassifier object. Please make sure you ' 'passed the data to TPOT correctly.') else: self.fitted_pipeline_ = self._toolbox.compile(expr=self._optimized_pipeline) with warnings.catch_warnings(): warnings.simplefilter('ignore') self.fitted_pipeline_.fit(features, target) if self.verbosity in [1, 2]: # Add an extra line of spacing if the progress bar was used if self.verbosity >= 2: print('') optimized_pipeline_str = self.clean_pipeline_string(self._optimized_pipeline) print('Best pipeline:', optimized_pipeline_str) # Store and fit the entire Pareto front as fitted models for convenience self.pareto_front_fitted_pipelines_ = {} for pipeline in self._pareto_front.items: self.pareto_front_fitted_pipelines_[str(pipeline)] = self._toolbox.compile(expr=pipeline) with warnings.catch_warnings(): warnings.simplefilter('ignore') self.pareto_front_fitted_pipelines_[str(pipeline)].fit(features, target)
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 target for the samples in the feature matrix 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 target for the samples in the feature matrix """ if not self.fitted_pipeline_: raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.') features = self._check_dataset(features, target=None, sample_weight=None) return self.fitted_pipeline_.predict(features)
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 prediction sample_weight: array-like {n_samples}, optional Per-sample weights. Higher weights force TPOT to put more emphasis on those points groups: array-like, with shape {n_samples, }, optional Group labels for the samples used when performing cross-validation. This parameter should only be used in conjunction with sklearn's Group cross-validation functions, such as sklearn.model_selection.GroupKFold Returns ---------- array-like: {n_samples} Predicted target for the provided features 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 prediction sample_weight: array-like {n_samples}, optional Per-sample weights. Higher weights force TPOT to put more emphasis on those points groups: array-like, with shape {n_samples, }, optional Group labels for the samples used when performing cross-validation. This parameter should only be used in conjunction with sklearn's Group cross-validation functions, such as sklearn.model_selection.GroupKFold Returns ---------- array-like: {n_samples} Predicted target for the provided features """ self.fit(features, target, sample_weight=sample_weight, groups=groups) return self.predict(features)
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: array-like {n_samples} List of class labels for prediction in the testing set Returns ------- accuracy_score: float The estimated test set accuracy 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: array-like {n_samples} List of class labels for prediction in the testing set Returns ------- accuracy_score: float The estimated test set accuracy """ if self.fitted_pipeline_ is None: raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.') testing_features, testing_target = self._check_dataset(testing_features, testing_target, sample_weight=None) # If the scoring function is a string, we must adjust to use the sklearn # scoring interface score = SCORERS[self.scoring_function]( self.fitted_pipeline_, testing_features.astype(np.float64), testing_target.astype(np.float64) ) return score
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: {n_samples, n_target} The class probabilities of the input samples 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: {n_samples, n_target} The class probabilities of the input samples """ if not self.fitted_pipeline_: raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.') else: if not (hasattr(self.fitted_pipeline_, 'predict_proba')): raise RuntimeError('The fitted pipeline does not have the predict_proba() function.') features = self._check_dataset(features, target=None, sample_weight=None) return self.fitted_pipeline_.predict_proba(features)
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 str(individual), but with parameter prefixes removed. 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 str(individual), but with parameter prefixes removed. """ dirty_string = str(individual) # There are many parameter prefixes in the pipeline strings, used solely for # making the terminal name unique, eg. LinearSVC__. parameter_prefixes = [(m.start(), m.end()) for m in re.finditer(', [\w]+__', dirty_string)] # We handle them in reverse so we do not mess up indices pretty = dirty_string for (start, end) in reversed(parameter_prefixes): pretty = pretty[:start + 2] + pretty[end:] return pretty
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 _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 """ self._update_top_pipeline() if self.periodic_checkpoint_folder is not None: total_since_last_pipeline_save = (datetime.now() - self._last_pipeline_write).total_seconds() if total_since_last_pipeline_save > self._output_best_pipeline_period_seconds: self._last_pipeline_write = datetime.now() self._save_periodic_pipeline(gen) if self.early_stop is not None: if self._last_optimized_pareto_front_n_gens >= self.early_stop: raise StopIteration("The optimized pipeline was not improved after evaluating {} more generations. " "Will end the optimization process.\n".format(self.early_stop))
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: '') By default, the path of input dataset is 'PATH/TO/DATA/FILE' by default. If data_file_path is another string, the path will be replaced. Returns ------- False if it skipped writing the pipeline to file True if the pipeline was actually written 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: '') By default, the path of input dataset is 'PATH/TO/DATA/FILE' by default. If data_file_path is another string, the path will be replaced. Returns ------- False if it skipped writing the pipeline to file True if the pipeline was actually written """ if self._optimized_pipeline is None: raise RuntimeError('A pipeline has not yet been optimized. Please call fit() first.') to_write = export_pipeline(self._optimized_pipeline, self.operators, self._pset, self._imputed, self._optimized_pipeline_score, self.random_state, data_file_path=data_file_path) with open(output_file_name, 'w') as output_file: output_file.write(to_write)
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} 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.verbosity > 1: print('Imputing missing values in feature set') if self._fitted_imputer is None: self._fitted_imputer = Imputer(strategy="median") self._fitted_imputer.fit(features) return self._fitted_imputer.transform(features)
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 class labels for prediction sample_weight: array-like {n_samples} (optional) List of weights indicating relative importance Returns ------- (features, target) 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 class labels for prediction sample_weight: array-like {n_samples} (optional) List of weights indicating relative importance Returns ------- (features, target) """ # Check sample_weight if sample_weight is not None: try: sample_weight = np.array(sample_weight).astype('float') except ValueError as e: raise ValueError('sample_weight could not be converted to float array: %s' % e) if np.any(np.isnan(sample_weight)): raise ValueError('sample_weight contained NaN values.') try: check_consistent_length(sample_weight, target) except ValueError as e: raise ValueError('sample_weight dimensions did not match target: %s' % e) # If features is a sparse matrix, do not apply imputation if sparse.issparse(features): if self.config_dict in [None, "TPOT light", "TPOT MDR"]: raise ValueError( 'Not all operators in {} supports sparse matrix. ' 'Please use \"TPOT sparse\" for sparse matrix.'.format(self.config_dict) ) elif self.config_dict != "TPOT sparse": print( 'Warning: Since the input matrix is a sparse matrix, please makes sure all the operators in the ' 'customized config dictionary supports sparse matriies.' ) else: if isinstance(features, np.ndarray): if np.any(np.isnan(features)): self._imputed = True elif isinstance(features, DataFrame): if features.isnull().values.any(): self._imputed = True if self._imputed: features = self._impute_values(features) try: if target is not None: X, y = check_X_y(features, target, accept_sparse=True, dtype=None) if self._imputed: return X, y else: return features, target else: X = check_array(features, accept_sparse=True, dtype=None) if self._imputed: return X else: return features except (AssertionError, ValueError): raise ValueError( 'Error: Input data is not in a valid format. Please confirm ' 'that the input data is scikit-learn compatible. For example, ' 'the features must be a 2-D array and target labels must be a ' '1-D array.' )
Compile a DEAP pipeline into a sklearn pipeline. Parameters ---------- expr: DEAP individual The DEAP pipeline to be compiled Returns ------- sklearn_pipeline: sklearn.pipeline.Pipeline 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 """ sklearn_pipeline_str = generate_pipeline_code(expr_to_tree(expr, self._pset), self.operators) sklearn_pipeline = eval(sklearn_pipeline_str, self.operators_context) sklearn_pipeline.memory = self._memory return sklearn_pipeline
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 parameter: str The parameter to assign a value for in each pipeline object value: any The value to assign the parameter to in each pipeline object Returns ------- None 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 parameter: str The parameter to assign a value for in each pipeline object value: any The value to assign the parameter to in each pipeline object Returns ------- None """ for (_, obj) in pipeline_steps: recursive_attrs = ['steps', 'transformer_list', 'estimators'] for attr in recursive_attrs: if hasattr(obj, attr): self._set_param_recursive(getattr(obj, attr), parameter, value) if hasattr(obj, 'estimator'): # nested estimator est = getattr(obj, 'estimator') if hasattr(est, parameter): setattr(est, parameter, value) if hasattr(obj, parameter): setattr(obj, parameter, value)
Stop optimization process once maximum minutes have elapsed. 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 KeyboardInterrupt('{} minutes have elapsed. TPOT will close down.'.format(total_mins_elapsed))
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 cv_score: float internal cross validation score individual_stats: dictionary dict containing statistics about the individual. currently: 'generation': generation in which the individual was evaluated 'mutation_count': number of mutation operations applied to the individual and its predecessor cumulatively 'crossover_count': number of crossover operations applied to the individual and its predecessor cumulatively 'predecessor': string representation of the individual Returns ------- stats: dictionary dict containing the combined statistics: 'operator_count': number of operators in the pipeline 'internal_cv_score': internal cross validation score and all the statistics contained in the 'individual_stats' parameter 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 cv_score: float internal cross validation score individual_stats: dictionary dict containing statistics about the individual. currently: 'generation': generation in which the individual was evaluated 'mutation_count': number of mutation operations applied to the individual and its predecessor cumulatively 'crossover_count': number of crossover operations applied to the individual and its predecessor cumulatively 'predecessor': string representation of the individual Returns ------- stats: dictionary dict containing the combined statistics: 'operator_count': number of operators in the pipeline 'internal_cv_score': internal cross validation score and all the statistics contained in the 'individual_stats' parameter """ stats = deepcopy(individual_stats) # Deepcopy, since the string reference to predecessor should be cloned stats['operator_count'] = operator_count stats['internal_cv_score'] = cv_score return stats
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 that can be compiled by DEAP into a callable function features: numpy.ndarray {n_samples, n_features} A numpy matrix containing the training and testing features for the individual's evaluation target: numpy.ndarray {n_samples} A numpy matrix containing the training and testing target for the individual's evaluation sample_weight: array-like {n_samples}, optional List of sample weights to balance (or un-balanace) the dataset target as needed groups: array-like {n_samples, }, optional Group labels for the samples used while splitting the dataset into train/test set Returns ------- fitnesses_ordered: float Returns a list of tuple value indicating the individual's fitness according to its performance on the provided data 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 that can be compiled by DEAP into a callable function features: numpy.ndarray {n_samples, n_features} A numpy matrix containing the training and testing features for the individual's evaluation target: numpy.ndarray {n_samples} A numpy matrix containing the training and testing target for the individual's evaluation sample_weight: array-like {n_samples}, optional List of sample weights to balance (or un-balanace) the dataset target as needed groups: array-like {n_samples, }, optional Group labels for the samples used while splitting the dataset into train/test set Returns ------- fitnesses_ordered: float Returns a list of tuple value indicating the individual's fitness according to its performance on the provided data """ # Evaluate the individuals with an invalid fitness individuals = [ind for ind in population if not ind.fitness.valid] # update pbar for valid individuals (with fitness values) if self.verbosity > 0: self._pbar.update(len(population)-len(individuals)) operator_counts, eval_individuals_str, sklearn_pipeline_list, stats_dicts = self._preprocess_individuals(individuals) # Make the partial function that will be called below partial_wrapped_cross_val_score = partial( _wrapped_cross_val_score, features=features, target=target, cv=self.cv, scoring_function=self.scoring_function, sample_weight=sample_weight, groups=groups, timeout=max(int(self.max_eval_time_mins * 60), 1), use_dask=self.use_dask ) result_score_list = [] try: # Don't use parallelization if n_jobs==1 if self._n_jobs == 1 and not self.use_dask: for sklearn_pipeline in sklearn_pipeline_list: self._stop_by_max_time_mins() val = partial_wrapped_cross_val_score(sklearn_pipeline=sklearn_pipeline) result_score_list = self._update_val(val, result_score_list) else: # chunk size for pbar update if self.use_dask: # chunk size is min of _lambda and n_jobs * 10 chunk_size = min(self._lambda, self._n_jobs*10) else: # chunk size is min of cpu_count * 2 and n_jobs * 4 chunk_size = min(cpu_count()*2, self._n_jobs*4) for chunk_idx in range(0, len(sklearn_pipeline_list), chunk_size): self._stop_by_max_time_mins() if self.use_dask: import dask tmp_result_scores = [ partial_wrapped_cross_val_score(sklearn_pipeline=sklearn_pipeline) for sklearn_pipeline in sklearn_pipeline_list[chunk_idx:chunk_idx + chunk_size] ] self.dask_graphs_ = tmp_result_scores with warnings.catch_warnings(): warnings.simplefilter('ignore') tmp_result_scores = list(dask.compute(*tmp_result_scores)) else: parallel = Parallel(n_jobs=self._n_jobs, verbose=0, pre_dispatch='2*n_jobs') tmp_result_scores = parallel( delayed(partial_wrapped_cross_val_score)(sklearn_pipeline=sklearn_pipeline) for sklearn_pipeline in sklearn_pipeline_list[chunk_idx:chunk_idx + chunk_size]) # update pbar for val in tmp_result_scores: result_score_list = self._update_val(val, result_score_list) except (KeyboardInterrupt, SystemExit, StopIteration) as e: if self.verbosity > 0: self._pbar.write('', file=self._file) self._pbar.write('{}\nTPOT closed during evaluation in one generation.\n' 'WARNING: TPOT may not provide a good pipeline if TPOT is stopped/interrupted in a early generation.'.format(e), file=self._file) # number of individuals already evaluated in this generation num_eval_ind = len(result_score_list) self._update_evaluated_individuals_(result_score_list, eval_individuals_str[:num_eval_ind], operator_counts, stats_dicts) for ind in individuals[:num_eval_ind]: ind_str = str(ind) ind.fitness.values = (self.evaluated_individuals_[ind_str]['operator_count'], self.evaluated_individuals_[ind_str]['internal_cv_score']) # for individuals were not evaluated in this generation, TPOT will assign a bad fitness score for ind in individuals[num_eval_ind:]: ind.fitness.values = (5000.,-float('inf')) self._pareto_front.update(population) raise KeyboardInterrupt self._update_evaluated_individuals_(result_score_list, eval_individuals_str, operator_counts, stats_dicts) for ind in individuals: ind_str = str(ind) ind.fitness.values = (self.evaluated_individuals_[ind_str]['operator_count'], self.evaluated_individuals_[ind_str]['internal_cv_score']) individuals = [ind for ind in population if not ind.fitness.valid] self._pareto_front.update(population) return population
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 DEAP into a callable function Returns ------- operator_counts: dictionary a dictionary of operator counts in individuals for evaluation eval_individuals_str: list a list of string of individuals for evaluation sklearn_pipeline_list: list a list of scikit-learn pipelines converted from DEAP individuals for evaluation stats_dicts: dictionary A dict where 'key' is the string representation of an individual and 'value' is a dict containing statistics about the individual 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 DEAP into a callable function Returns ------- operator_counts: dictionary a dictionary of operator counts in individuals for evaluation eval_individuals_str: list a list of string of individuals for evaluation sklearn_pipeline_list: list a list of scikit-learn pipelines converted from DEAP individuals for evaluation stats_dicts: dictionary A dict where 'key' is the string representation of an individual and 'value' is a dict containing statistics about the individual """ # update self._pbar.total if not (self.max_time_mins is None) and not self._pbar.disable and self._pbar.total <= self._pbar.n: self._pbar.total += self._lambda # Check we do not evaluate twice the same individual in one pass. _, unique_individual_indices = np.unique([str(ind) for ind in individuals], return_index=True) unique_individuals = [ind for i, ind in enumerate(individuals) if i in unique_individual_indices] # update number of duplicate pipelines self._update_pbar(pbar_num=len(individuals) - len(unique_individuals)) # a dictionary for storing operator counts operator_counts = {} stats_dicts = {} # 2 lists of DEAP individuals' string, their sklearn pipelines for parallel computing eval_individuals_str = [] sklearn_pipeline_list = [] for individual in unique_individuals: # Disallow certain combinations of operators because they will take too long or take up too much RAM # This is a fairly hacky way to prevent TPOT from getting stuck on bad pipelines and should be improved in a future release individual_str = str(individual) if not len(individual): # a pipeline cannot be randomly generated self.evaluated_individuals_[individual_str] = self._combine_individual_stats(5000., -float('inf'), individual.statistics) self._update_pbar(pbar_msg='Invalid pipeline encountered. Skipping its evaluation.') continue sklearn_pipeline_str = generate_pipeline_code(expr_to_tree(individual, self._pset), self.operators) if sklearn_pipeline_str.count('PolynomialFeatures') > 1: self.evaluated_individuals_[individual_str] = self._combine_individual_stats(5000., -float('inf'), individual.statistics) self._update_pbar(pbar_msg='Invalid pipeline encountered. Skipping its evaluation.') # Check if the individual was evaluated before elif individual_str in self.evaluated_individuals_: self._update_pbar(pbar_msg=('Pipeline encountered that has previously been evaluated during the ' 'optimization process. Using the score from the previous evaluation.')) else: try: # Transform the tree expression into an sklearn pipeline sklearn_pipeline = self._toolbox.compile(expr=individual) # Fix random state when the operator allows self._set_param_recursive(sklearn_pipeline.steps, 'random_state', 42) # Setting the seed is needed for XGBoost support because XGBoost currently stores # both a seed and random_state, and they're not synced correctly. # XGBoost will raise an exception if random_state != seed. if 'XGB' in sklearn_pipeline_str: self._set_param_recursive(sklearn_pipeline.steps, 'seed', 42) # Count the number of pipeline operators as a measure of pipeline complexity operator_count = self._operator_count(individual) operator_counts[individual_str] = max(1, operator_count) stats_dicts[individual_str] = individual.statistics except Exception: self.evaluated_individuals_[individual_str] = self._combine_individual_stats(5000., -float('inf'), individual.statistics) self._update_pbar() continue eval_individuals_str.append(individual_str) sklearn_pipeline_list.append(sklearn_pipeline) return operator_counts, eval_individuals_str, sklearn_pipeline_list, stats_dicts
Update self.evaluated_individuals_ and error message during pipeline evaluation. Parameters ---------- result_score_list: list A list of CV scores for evaluated pipelines eval_individuals_str: list A list of strings for evaluated pipelines operator_counts: dict A dict where 'key' is the string representation of an individual and 'value' is the number of operators in the pipeline stats_dicts: dict A dict where 'key' is the string representation of an individual and 'value' is a dict containing statistics about the individual Returns ------- None 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 evaluated pipelines eval_individuals_str: list A list of strings for evaluated pipelines operator_counts: dict A dict where 'key' is the string representation of an individual and 'value' is the number of operators in the pipeline stats_dicts: dict A dict where 'key' is the string representation of an individual and 'value' is a dict containing statistics about the individual Returns ------- None """ for result_score, individual_str in zip(result_score_list, eval_individuals_str): if type(result_score) in [float, np.float64, np.float32]: self.evaluated_individuals_[individual_str] = self._combine_individual_stats(operator_counts[individual_str], result_score, stats_dicts[individual_str]) else: raise ValueError('Scoring function does not return a float.')
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 ------- None 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 ------- None """ if not isinstance(self._pbar, type(None)): if self.verbosity > 2 and pbar_msg is not None: self._pbar.write(pbar_msg, file=self._file) if not self._pbar.disable: self._pbar.update(pbar_num)
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 by DEAP into a callable function allow_shrink: bool (True) If True the `mutShrink` operator, which randomly shrinks the pipeline, is allowed to be chosen as one of the random mutation operators. If False, `mutShrink` will never be chosen as a mutation operator. Returns ------- mut_ind: DEAP individual Returns the individual with one of the mutations applied to it 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 by DEAP into a callable function allow_shrink: bool (True) If True the `mutShrink` operator, which randomly shrinks the pipeline, is allowed to be chosen as one of the random mutation operators. If False, `mutShrink` will never be chosen as a mutation operator. Returns ------- mut_ind: DEAP individual Returns the individual with one of the mutations applied to it """ if self.tree_structure: mutation_techniques = [ partial(gp.mutInsert, pset=self._pset), partial(mutNodeReplacement, pset=self._pset) ] # We can't shrink pipelines with only one primitive, so we only add it if we find more primitives. number_of_primitives = sum([isinstance(node, deap.gp.Primitive) for node in individual]) if number_of_primitives > 1 and allow_shrink: mutation_techniques.append(partial(gp.mutShrink)) else: mutation_techniques = [partial(mutNodeReplacement, pset=self._pset)] mutator = np.random.choice(mutation_techniques) unsuccesful_mutations = 0 for _ in range(self._max_mut_loops): # We have to clone the individual because mutator operators work in-place. ind = self._toolbox.clone(individual) offspring, = mutator(ind) if str(offspring) not in self.evaluated_individuals_: # Update statistics # crossover_count is kept the same as for the predecessor # mutation count is increased by 1 # predecessor is set to the string representation of the individual before mutation # generation is set to 'INVALID' such that we can recognize that it should be updated accordingly offspring.statistics['crossover_count'] = individual.statistics['crossover_count'] offspring.statistics['mutation_count'] = individual.statistics['mutation_count'] + 1 offspring.statistics['predecessor'] = (str(individual),) offspring.statistics['generation'] = 'INVALID' break else: unsuccesful_mutations += 1 # Sometimes you have pipelines for which every shrunk version has already been explored too. # To still mutate the individual, one of the two other mutators should be applied instead. if ((unsuccesful_mutations == 50) and (type(mutator) is partial and mutator.func is gp.mutShrink)): offspring, = self._random_mutation_operator(individual, allow_shrink=False) return offspring,
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 Minimum height of the produced trees. max_: int Maximum Height of the produced trees. type_: class The type that should return the tree when called, when :obj:None (default) the type of :pset: (pset.ret) is assumed. Returns ------- individual: list A grown tree with leaves at possibly different depths. 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 Minimum height of the produced trees. max_: int Maximum Height of the produced trees. type_: class The type that should return the tree when called, when :obj:None (default) the type of :pset: (pset.ret) is assumed. Returns ------- individual: list A grown tree with leaves at possibly different depths. """ def condition(height, depth, type_): """Stop when the depth is equal to height or when a node should be a terminal.""" return type_ not in self.ret_types or depth == height return self._generate(pset, min_, max_, condition, type_)
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. Returns ------- operator_count: int How many operators in a pipeline 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. Returns ------- operator_count: int How many operators in a pipeline """ operator_count = 0 for i in range(len(individual)): node = individual[i] if type(node) is deap.gp.Primitive and node.name != 'CombineDFs': operator_count += 1 return operator_count
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 ------- result_score_list: list A updated list of CV scores 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 ------- result_score_list: list A updated list of CV scores """ self._update_pbar() if val == 'Timeout': self._update_pbar(pbar_msg=('Skipped pipeline #{0} due to time out. ' 'Continuing to the next pipeline.'.format(self._pbar.n))) result_score_list.append(-float('inf')) else: result_score_list.append(val) return result_score_list
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 set from which primitives are selected. min_: int Minimum height of the produced trees. max_: int Maximum Height of the produced trees. condition: function The condition is a function that takes two arguments, the height of the tree to build and the current depth in the tree. type_: class The type that should return the tree when called, when :obj:None (default) no return type is enforced. Returns ------- individual: list A grown tree with leaves at possibly different depths dependending on the condition function. 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 set from which primitives are selected. min_: int Minimum height of the produced trees. max_: int Maximum Height of the produced trees. condition: function The condition is a function that takes two arguments, the height of the tree to build and the current depth in the tree. type_: class The type that should return the tree when called, when :obj:None (default) no return type is enforced. Returns ------- individual: list A grown tree with leaves at possibly different depths dependending on the condition function. """ if type_ is None: type_ = pset.ret expr = [] height = np.random.randint(min_, max_) stack = [(0, type_)] while len(stack) != 0: depth, type_ = stack.pop() # We've added a type_ parameter to the condition function if condition(height, depth, type_): try: term = np.random.choice(pset.terminals[type_]) except IndexError: _, _, traceback = sys.exc_info() raise IndexError( 'The gp.generate function tried to add ' 'a terminal of type {}, but there is' 'none available. {}'.format(type_, traceback) ) if inspect.isclass(term): term = term() expr.append(term) else: try: prim = np.random.choice(pset.primitives[type_]) except IndexError: _, _, traceback = sys.exc_info() raise IndexError( 'The gp.generate function tried to add ' 'a primitive of type {}, but there is' 'none available. {}'.format(type_, traceback) ) expr.append(prim) for arg in reversed(prim.args): stack.append((depth + 1, arg)) return expr
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 ------- array-like, {n_samples, n_components} 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 ------- array-like, {n_samples, n_components} """ selected = auto_select_categorical_features(X, threshold=self.threshold) X_sel, _, n_selected, _ = _X_selected(X, selected) if n_selected == 0: # No features selected. raise ValueError('No categorical feature was found!') else: ohe = OneHotEncoder(categorical_features='all', sparse=False, minimum_fraction=self.minimum_fraction) return ohe.fit_transform(X_sel)
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 ------- array-like, {n_samples, n_components} 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 ------- array-like, {n_samples, n_components} """ selected = auto_select_categorical_features(X, threshold=self.threshold) _, X_sel, n_selected, _ = _X_selected(X, selected) if n_selected == 0: # No features selected. raise ValueError('No continuous feature was found!') else: pca = PCA(svd_solver=self.svd_solver, iterated_power=self.iterated_power, random_state=self.random_state) return pca.fit_transform(X_sel)
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 correspond to classes in classification, real numbers in regression). fit_params: Other estimator-specific parameters. Returns ------- self: object Returns a copy of the estimator 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 correspond to classes in classification, real numbers in regression). fit_params: Other estimator-specific parameters. Returns ------- self: object Returns a copy of the estimator """ self.estimator.fit(X, y, **fit_params) return self
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 ------- X_transformed: array-like, shape (n_samples, n_features + 1) or (n_samples, n_features + 1 + n_classes) for classifier with predict_proba attribute The transformed feature set. 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 ------- X_transformed: array-like, shape (n_samples, n_features + 1) or (n_samples, n_features + 1 + n_classes) for classifier with predict_proba attribute The transformed feature set. """ X = check_array(X) X_transformed = np.copy(X) # add class probabilities as a synthetic feature if issubclass(self.estimator.__class__, ClassifierMixin) and hasattr(self.estimator, 'predict_proba'): X_transformed = np.hstack((self.estimator.predict_proba(X), X)) # add class prodiction as a synthetic feature X_transformed = np.hstack((np.reshape(self.estimator.predict(X), (-1, 1)), X_transformed)) return X_transformed
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_samples} True class labels y_pred: numpy.ndarray {n_samples} Predicted class labels by the estimator Returns ------- fitness: float Returns a float value indicating the individual's balanced accuracy 0.5 is as good as chance, and 1.0 is perfect predictive accuracy 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_samples} True class labels y_pred: numpy.ndarray {n_samples} Predicted class labels by the estimator Returns ------- fitness: float Returns a float value indicating the individual's balanced accuracy 0.5 is as good as chance, and 1.0 is perfect predictive accuracy """ all_classes = list(set(np.append(y_true, y_pred))) all_class_accuracies = [] for this_class in all_classes: this_class_sensitivity = 0. this_class_specificity = 0. if sum(y_true == this_class) != 0: this_class_sensitivity = \ float(sum((y_pred == this_class) & (y_true == this_class))) /\ float(sum((y_true == this_class))) this_class_specificity = \ float(sum((y_pred != this_class) & (y_true != this_class))) /\ float(sum((y_true != this_class))) this_class_accuracy = (this_class_sensitivity + this_class_specificity) / 2. all_class_accuracies.append(this_class_accuracy) return np.mean(all_class_accuracies)
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 Unused Returns ------- X_transformed: array-like, shape (n_samples, n_features) The transformed feature set 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 Unused Returns ------- X_transformed: array-like, shape (n_samples, n_features) The transformed feature set """ X = check_array(X) n_features = X.shape[1] X_transformed = np.copy(X) non_zero_vector = np.count_nonzero(X_transformed, axis=1) non_zero = np.reshape(non_zero_vector, (-1, 1)) zero_col = np.reshape(n_features - non_zero_vector, (-1, 1)) X_transformed = np.hstack((non_zero, X_transformed)) X_transformed = np.hstack((zero_col, X_transformed)) return X_transformed
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 it's running. 0 = none, 1 = minimal, 2 = high, 3 = all. if verbose > 2 then ImportError will rasie during initialization Returns ------- import_str: string a string of operator class source (e.g. 'sklearn.feature_selection') op_str: string a string of operator class (e.g. 'RFE') op_obj: object operator class (e.g. RFE) 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 it's running. 0 = none, 1 = minimal, 2 = high, 3 = all. if verbose > 2 then ImportError will rasie during initialization Returns ------- import_str: string a string of operator class source (e.g. 'sklearn.feature_selection') op_str: string a string of operator class (e.g. 'RFE') op_obj: object operator class (e.g. RFE) """ tmp_path = sourcecode.split('.') op_str = tmp_path.pop() import_str = '.'.join(tmp_path) try: if sourcecode.startswith('tpot.'): exec('from {} import {}'.format(import_str[4:], op_str)) else: exec('from {} import {}'.format(import_str, op_str)) op_obj = eval(op_str) except Exception as e: if verbose > 2: raise ImportError('Error: could not import {}.\n{}'.format(sourcecode, e)) else: print('Warning: {} is not available and will not be used by TPOT.'.format(sourcecode)) op_obj = None return import_str, op_str, op_obj
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 List of sample weight Returns ------- sample_weight_dict: A dictionary of sample_weight 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 List of sample weight Returns ------- sample_weight_dict: A dictionary of sample_weight """ sample_weight_dict = {} if not isinstance(sample_weight, type(None)): for (pname, obj) in pipeline_steps: if inspect.getargspec(obj.fit).args.count('sample_weight'): step_sw = pname + '__sample_weight' sample_weight_dict[step_sw] = sample_weight if sample_weight_dict: return sample_weight_dict else: return None
Dynamically create operator class. Parameters ---------- opsourse: string operator source in config dictionary (key) opdict: dictionary operator params in config dictionary (value) regression: bool True if it can be used in TPOTRegressor classification: bool True if it can be used in TPOTClassifier BaseClass: Class inherited BaseClass for operator ArgBaseClass: Class inherited BaseClass for parameter verbose: int, optional (default: 0) How much information TPOT communicates while it's running. 0 = none, 1 = minimal, 2 = high, 3 = all. if verbose > 2 then ImportError will rasie during initialization Returns ------- op_class: Class a new class for a operator arg_types: list a list of parameter class 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) regression: bool True if it can be used in TPOTRegressor classification: bool True if it can be used in TPOTClassifier BaseClass: Class inherited BaseClass for operator ArgBaseClass: Class inherited BaseClass for parameter verbose: int, optional (default: 0) How much information TPOT communicates while it's running. 0 = none, 1 = minimal, 2 = high, 3 = all. if verbose > 2 then ImportError will rasie during initialization Returns ------- op_class: Class a new class for a operator arg_types: list a list of parameter class """ class_profile = {} dep_op_list = {} # list of nested estimator/callable function dep_op_type = {} # type of nested estimator/callable function import_str, op_str, op_obj = source_decode(opsourse, verbose=verbose) if not op_obj: return None, None else: # define if the operator can be the root of a pipeline if issubclass(op_obj, ClassifierMixin): class_profile['root'] = True optype = "Classifier" elif issubclass(op_obj, RegressorMixin): class_profile['root'] = True optype = "Regressor" if issubclass(op_obj, TransformerMixin): optype = "Transformer" if issubclass(op_obj, SelectorMixin): optype = "Selector" @classmethod def op_type(cls): """Return the operator type. Possible values: "Classifier", "Regressor", "Selector", "Transformer" """ return optype class_profile['type'] = op_type class_profile['sklearn_class'] = op_obj import_hash = {} import_hash[import_str] = [op_str] arg_types = [] for pname in sorted(opdict.keys()): prange = opdict[pname] if not isinstance(prange, dict): classname = '{}__{}'.format(op_str, pname) arg_types.append(ARGTypeClassFactory(classname, prange, ArgBaseClass)) else: for dkey, dval in prange.items(): dep_import_str, dep_op_str, dep_op_obj = source_decode(dkey, verbose=verbose) if dep_import_str in import_hash: import_hash[import_str].append(dep_op_str) else: import_hash[dep_import_str] = [dep_op_str] dep_op_list[pname] = dep_op_str dep_op_type[pname] = dep_op_obj if dval: for dpname in sorted(dval.keys()): dprange = dval[dpname] classname = '{}__{}__{}'.format(op_str, dep_op_str, dpname) arg_types.append(ARGTypeClassFactory(classname, dprange, ArgBaseClass)) class_profile['arg_types'] = tuple(arg_types) class_profile['import_hash'] = import_hash class_profile['dep_op_list'] = dep_op_list class_profile['dep_op_type'] = dep_op_type @classmethod def parameter_types(cls): """Return the argument and return types of an operator. Parameters ---------- None Returns ------- parameter_types: tuple Tuple of the DEAP parameter types and the DEAP return type for the operator """ return ([np.ndarray] + arg_types, np.ndarray) # (input types, return types) class_profile['parameter_types'] = parameter_types @classmethod def export(cls, *args): """Represent the operator as a string so that it can be exported to a file. Parameters ---------- args Arbitrary arguments to be passed to the operator Returns ------- export_string: str String representation of the sklearn class with its parameters in the format: SklearnClassName(param1="val1", param2=val2) """ op_arguments = [] if dep_op_list: dep_op_arguments = {} for dep_op_str in dep_op_list.values(): dep_op_arguments[dep_op_str] = [] for arg_class, arg_value in zip(arg_types, args): aname_split = arg_class.__name__.split('__') if isinstance(arg_value, str): arg_value = '\"{}\"'.format(arg_value) if len(aname_split) == 2: # simple parameter op_arguments.append("{}={}".format(aname_split[-1], arg_value)) # Parameter of internal operator as a parameter in the # operator, usually in Selector else: dep_op_arguments[aname_split[1]].append("{}={}".format(aname_split[-1], arg_value)) tmp_op_args = [] if dep_op_list: # To make sure the inital operators is the first parameter just # for better persentation for dep_op_pname, dep_op_str in dep_op_list.items(): arg_value = dep_op_str # a callable function, e.g scoring function doptype = dep_op_type[dep_op_pname] if inspect.isclass(doptype): # a estimator if issubclass(doptype, BaseEstimator) or \ issubclass(doptype, ClassifierMixin) or \ issubclass(doptype, RegressorMixin) or \ issubclass(doptype, TransformerMixin): arg_value = "{}({})".format(dep_op_str, ", ".join(dep_op_arguments[dep_op_str])) tmp_op_args.append("{}={}".format(dep_op_pname, arg_value)) op_arguments = tmp_op_args + op_arguments return "{}({})".format(op_obj.__name__, ", ".join(op_arguments)) class_profile['export'] = export op_classname = 'TPOT_{}'.format(op_str) op_class = type(op_classname, (BaseClass,), class_profile) op_class.__name__ = op_str return op_class, arg_types
Ensure that the provided value is a positive integer. Parameters ---------- value: int The number to evaluate Returns ------- value: int Returns a positive integer 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: raise argparse.ArgumentTypeError('Invalid int value: \'{}\''.format(value)) if value < 0: raise argparse.ArgumentTypeError('Invalid positive int value: \'{}\''.format(value)) return 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.) 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) except Exception: raise argparse.ArgumentTypeError('Invalid float value: \'{}\''.format(value)) if value < 0.0 or value > 1.0: raise argparse.ArgumentTypeError('Invalid float value: \'{}\''.format(value)) return value
Main function that is called when TPOT is run on the command line. 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_help=False ) parser.add_argument( 'INPUT_FILE', type=str, help=( 'Data file to use in the TPOT optimization process. Ensure that ' 'the class label column is labeled as "class".' ) ) parser.add_argument( '-h', '--help', action='help', help='Show this help message and exit.' ) parser.add_argument( '-is', action='store', dest='INPUT_SEPARATOR', default='\t', type=str, help='Character used to separate columns in the input file.' ) parser.add_argument( '-target', action='store', dest='TARGET_NAME', default='class', type=str, help='Name of the target column in the input file.' ) parser.add_argument( '-mode', action='store', dest='TPOT_MODE', choices=['classification', 'regression'], default='classification', type=str, help=( 'Whether TPOT is being used for a supervised classification or ' 'regression problem.' ) ) parser.add_argument( '-o', action='store', dest='OUTPUT_FILE', default=None, type=str, help='File to export the code for the final optimized pipeline.' ) parser.add_argument( '-g', action='store', dest='GENERATIONS', default=100, type=positive_integer, help=( 'Number of iterations to run the pipeline optimization process. ' 'Generally, TPOT will work better when you give it more ' 'generations (and therefore time) to optimize the pipeline. TPOT ' 'will evaluate POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE ' 'pipelines in total.' ) ) parser.add_argument( '-p', action='store', dest='POPULATION_SIZE', default=100, type=positive_integer, help=( 'Number of individuals to retain in the GP population every ' 'generation. Generally, TPOT will work better when you give it ' 'more individuals (and therefore time) to optimize the pipeline. ' 'TPOT will evaluate POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE ' 'pipelines in total.' ) ) parser.add_argument( '-os', action='store', dest='OFFSPRING_SIZE', default=None, type=positive_integer, help=( 'Number of offspring to produce in each GP generation. By default,' 'OFFSPRING_SIZE = POPULATION_SIZE.' ) ) parser.add_argument( '-mr', action='store', dest='MUTATION_RATE', default=0.9, type=float_range, help=( 'GP mutation rate in the range [0.0, 1.0]. This tells the GP ' 'algorithm how many pipelines to apply random changes to every ' 'generation. We recommend using the default parameter unless you ' 'understand how the mutation rate affects GP algorithms.' ) ) parser.add_argument( '-xr', action='store', dest='CROSSOVER_RATE', default=0.1, type=float_range, help=( 'GP crossover rate in the range [0.0, 1.0]. This tells the GP ' 'algorithm how many pipelines to "breed" every generation. We ' 'recommend using the default parameter unless you understand how ' 'the crossover rate affects GP algorithms.' ) ) parser.add_argument( '-scoring', action='store', dest='SCORING_FN', default=None, type=str, help=( 'Function used to evaluate the quality of a given pipeline for the ' 'problem. By default, accuracy is used for classification problems ' 'and mean squared error (mse) is used for regression problems. ' 'Note: If you wrote your own function, set this argument to mymodule.myfunction' 'and TPOT will import your module and take the function from there.' 'TPOT will assume the module can be imported from the current workdir.' 'TPOT assumes that any function with "error" or "loss" in the name ' 'is meant to be minimized, whereas any other functions will be ' 'maximized. Offers the same options as cross_val_score: ' 'accuracy, ' 'adjusted_rand_score, ' 'average_precision, ' 'f1, ' 'f1_macro, ' 'f1_micro, ' 'f1_samples, ' 'f1_weighted, ' 'neg_log_loss, ' 'neg_mean_absolute_error, ' 'neg_mean_squared_error, ' 'neg_median_absolute_error, ' 'precision, ' 'precision_macro, ' 'precision_micro, ' 'precision_samples, ' 'precision_weighted, ' 'r2, ' 'recall, ' 'recall_macro, ' 'recall_micro, ' 'recall_samples, ' 'recall_weighted, ' 'roc_auc' ) ) parser.add_argument( '-cv', action='store', dest='NUM_CV_FOLDS', default=5, type=int, help=( 'Number of folds to evaluate each pipeline over in stratified k-fold ' 'cross-validation during the TPOT optimization process.' ) ) parser.add_argument( '-sub', action='store', dest='SUBSAMPLE', default=1.0, type=float, help=( 'Subsample ratio of the training instance. Setting it to 0.5 means that TPOT ' 'use a random subsample of half of training data for the pipeline optimization process.' ) ) parser.add_argument( '-njobs', action='store', dest='NUM_JOBS', default=1, type=int, help=( 'Number of CPUs for evaluating pipelines in parallel during the ' 'TPOT optimization process. Assigning this to -1 will use as many ' 'cores as available on the computer. For n_jobs below -1, ' '(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one are used.' ) ) parser.add_argument( '-maxtime', action='store', dest='MAX_TIME_MINS', default=None, type=int, help=( 'How many minutes TPOT has to optimize the pipeline. This setting ' 'will override the GENERATIONS parameter and allow TPOT to run ' 'until it runs out of time.' ) ) parser.add_argument( '-maxeval', action='store', dest='MAX_EVAL_MINS', default=5, type=float, help=( 'How many minutes TPOT has to evaluate a single pipeline. Setting ' 'this parameter to higher values will allow TPOT to explore more ' 'complex pipelines but will also allow TPOT to run longer.' ) ) parser.add_argument( '-s', action='store', dest='RANDOM_STATE', default=None, type=int, help=( 'Random number generator seed for reproducibility. Set this seed ' 'if you want your TPOT run to be reproducible with the same seed ' 'and data set in the future.' ) ) parser.add_argument( '-config', action='store', dest='CONFIG_FILE', default=None, type=str, help=( 'Configuration file for customizing the operators and parameters ' 'that TPOT uses in the optimization process. Must be a Python ' 'module containing a dict export named "tpot_config" or the name of ' 'built-in configuration.' ) ) parser.add_argument( '-template', action='store', dest='TEMPLATE', default='RandomTree', type=str, help=( 'Template of predefined pipeline structure. The option is for specifying a desired structure' 'for the machine learning pipeline evaluated in TPOT. So far this option only supports' 'linear pipeline structure. Each step in the pipeline should be a main class of operators' '(Selector, Transformer, Classifier or Regressor) or a specific operator' '(e.g. SelectPercentile) defined in TPOT operator configuration. If one step is a main class,' 'TPOT will randomly assign all subclass operators (subclasses of SelectorMixin,' 'TransformerMixin, ClassifierMixin or RegressorMixin in scikit-learn) to that step.' 'Steps in the template are delimited by "-", e.g. "SelectPercentile-Transformer-Classifier".' 'By default value of template is "RandomTree", TPOT generates tree-based pipeline randomly.' ) ) parser.add_argument( '-memory', action='store', dest='MEMORY', default=None, type=str, help=( 'Path of a directory for pipeline caching or \"auto\" for using a temporary ' 'caching directory during the optimization process. If supplied, pipelines will ' 'cache each transformer after fitting them. This feature is used to avoid ' 'repeated computation by transformers within a pipeline if the parameters and ' 'input data are identical with another fitted pipeline during optimization process.' ) ) parser.add_argument( '-cf', action='store', dest='CHECKPOINT_FOLDER', default=None, type=str, help=('If supplied, a folder in which tpot will periodically ' 'save the best pipeline so far while optimizing. ' 'This is useful in multiple cases: ' 'sudden death before tpot could save an optimized pipeline, ' 'progress tracking, ' "grabbing a pipeline while it's still optimizing etc." ) ) parser.add_argument( '-es', action='store', dest='EARLY_STOP', default=None, type=int, help=( 'How many generations TPOT checks whether there is no improvement ' 'in optimization process. End optimization process if there is no improvement ' 'in the set number of generations.' ) ) parser.add_argument( '-v', action='store', dest='VERBOSITY', default=1, choices=[0, 1, 2, 3], type=int, help=( 'How much information TPOT communicates while it is running: ' '0 = none, 1 = minimal, 2 = high, 3 = all. A setting of 2 or ' 'higher will add a progress bar during the optimization procedure.' ) ) parser.add_argument( '--no-update-check', action='store_true', dest='DISABLE_UPDATE_CHECK', default=False, help='Flag indicating whether the TPOT version checker should be disabled.' ) parser.add_argument( '--version', action='version', version='TPOT {version}'.format(version=__version__), help='Show the TPOT version number and exit.' ) return parser
converts mymodule.myfunc in the myfunc object itself so tpot receives a scoring function 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() sys.path.insert(0, module_path) scoring_func = getattr(import_module(module_name), func_name) sys.path.pop(0) print('manual scoring function: {}'.format(scoring_func)) print('taken from module: {}'.format(module_name)) except Exception as e: print('failed importing custom scoring function, error: {}'.format(str(e))) raise ValueError(e) return scoring_func
Perform a TPOT run. 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, input_data[args.TARGET_NAME], random_state=args.RANDOM_STATE) tpot_type = TPOTClassifier if args.TPOT_MODE == 'classification' else TPOTRegressor scoring_func = load_scoring_function(args.SCORING_FN) tpot_obj = tpot_type( generations=args.GENERATIONS, population_size=args.POPULATION_SIZE, offspring_size=args.OFFSPRING_SIZE, mutation_rate=args.MUTATION_RATE, crossover_rate=args.CROSSOVER_RATE, cv=args.NUM_CV_FOLDS, subsample=args.SUBSAMPLE, n_jobs=args.NUM_JOBS, scoring=scoring_func, max_time_mins=args.MAX_TIME_MINS, max_eval_time_mins=args.MAX_EVAL_MINS, random_state=args.RANDOM_STATE, config_dict=args.CONFIG_FILE, template=args.TEMPLATE, memory=args.MEMORY, periodic_checkpoint_folder=args.CHECKPOINT_FOLDER, early_stop=args.EARLY_STOP, verbosity=args.VERBOSITY, disable_update_check=args.DISABLE_UPDATE_CHECK ) tpot_obj.fit(training_features, training_target) if args.VERBOSITY in [1, 2] and tpot_obj._optimized_pipeline: training_score = max([x.wvalues[1] for x in tpot_obj._pareto_front.keys]) print('\nTraining score: {}'.format(training_score)) print('Holdout score: {}'.format(tpot_obj.score(testing_features, testing_target))) elif args.VERBOSITY >= 3 and tpot_obj._pareto_front: print('Final Pareto front testing scores:') pipelines = zip(tpot_obj._pareto_front.items, reversed(tpot_obj._pareto_front.keys)) for pipeline, pipeline_scores in pipelines: tpot_obj._fitted_pipeline = tpot_obj.pareto_front_fitted_pipelines_[str(pipeline)] print('{TRAIN_SCORE}\t{TEST_SCORE}\t{PIPELINE}'.format( TRAIN_SCORE=int(pipeline_scores.wvalues[0]), TEST_SCORE=tpot_obj.score(testing_features, testing_target), PIPELINE=pipeline ) ) if args.OUTPUT_FILE: tpot_obj.export(args.OUTPUT_FILE)
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 classes in classification, real numbers in regression). Returns ------- self: object Returns a copy of the estimator 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 classes in classification, real numbers in regression). Returns ------- self: object Returns a copy of the estimator """ subset_df = pd.read_csv(self.subset_list, header=0, index_col=0) if isinstance(self.sel_subset, int): self.sel_subset_name = subset_df.index[self.sel_subset] elif isinstance(self.sel_subset, str): self.sel_subset_name = self.sel_subset else: # list or tuple self.sel_subset_name = [] for s in self.sel_subset: if isinstance(s, int): self.sel_subset_name.append(subset_df.index[s]) else: self.sel_subset_name.append(s) sel_features = subset_df.loc[self.sel_subset_name, 'Features'] if not isinstance(sel_features, str): sel_features = ";".join(sel_features.tolist()) sel_uniq_features = set(sel_features.split(';')) if isinstance(X, pd.DataFrame): # use columns' names self.feature_names = list(X.columns.values) self.feat_list = sorted(list(set(sel_uniq_features).intersection(set(self.feature_names)))) self.feat_list_idx = [list(X.columns).index(feat_name) for feat_name in self.feat_list] elif isinstance(X, np.ndarray): # use index self.feature_names = list(range(X.shape[1])) sel_uniq_features = [int(val) for val in sel_uniq_features] self.feat_list = sorted(list(set(sel_uniq_features).intersection(set(self.feature_names)))) self.feat_list_idx = self.feat_list if not len(self.feat_list): raise ValueError('No feature is found on the subset list!') return self
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, shape (n_samples, n_features + 1) or (n_samples, n_features + 1 + n_classes) for classifier with predict_proba attribute The transformed feature set. 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, shape (n_samples, n_features + 1) or (n_samples, n_features + 1 + n_classes) for classifier with predict_proba attribute The transformed feature set. """ if isinstance(X, pd.DataFrame): X_transformed = X[self.feat_list].values elif isinstance(X, np.ndarray): X_transformed = X[:, self.feat_list_idx] return X_transformed.astype(np.float64)
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 _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. """ check_is_fitted(self, 'feat_list_idx') n_features = len(self.feature_names) mask = np.zeros(n_features, dtype=bool) mask[np.asarray(self.feat_list_idx)] = True return mask
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 individuals which are not the same, but share at least one primitive. Alternatively, if no such pair exists in the population, (None, None) is returned instead. 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 individuals which are not the same, but share at least one primitive. Alternatively, if no such pair exists in the population, (None, None) is returned instead. """ primitives_by_ind = [set([node.name for node in ind if isinstance(node, gp.Primitive)]) for ind in population] pop_as_str = [str(ind) for ind in population] eligible_pairs = [(i, i+1+j) for i, ind1_prims in enumerate(primitives_by_ind) for j, ind2_prims in enumerate(primitives_by_ind[i+1:]) if not ind1_prims.isdisjoint(ind2_prims) and pop_as_str[i] != pop_as_str[i+1+j]] # Pairs are eligible in both orders, this ensures that both orders are considered eligible_pairs += [(j, i) for (i, j) in eligible_pairs] if not eligible_pairs: # If there are no eligible pairs, the caller should decide what to do return None, None pair = np.random.randint(0, len(eligible_pairs)) idx1, idx2 = eligible_pairs[pair] return population[idx1], population[idx2]
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 of the individuals in population, the returned individual does not have fitness.values 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 of the individuals in population, the returned individual does not have fitness.values """ idx = np.random.randint(0,len(population)) ind = population[idx] ind, = toolbox.mutate(ind) del ind.fitness.values return ind
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 population. :param population: A list of individuals to vary. :param toolbox: A :class:`~deap.base.Toolbox` that contains the evolution operators. :param lambda\_: The number of children to produce :param cxpb: The probability of mating two individuals. :param mutpb: The probability of mutating an individual. :returns: The final population :returns: A class:`~deap.tools.Logbook` with the statistics of the evolution The variation goes as follow. On each of the *lambda_* iteration, it selects one of the three operations; crossover, mutation or reproduction. In the case of a crossover, two individuals are selected at random from the parental population :math:`P_\mathrm{p}`, those individuals are cloned using the :meth:`toolbox.clone` method and then mated using the :meth:`toolbox.mate` method. Only the first child is appended to the offspring population :math:`P_\mathrm{o}`, the second child is discarded. In the case of a mutation, one individual is selected at random from :math:`P_\mathrm{p}`, it is cloned and then mutated using using the :meth:`toolbox.mutate` method. The resulting mutant is appended to :math:`P_\mathrm{o}`. In the case of a reproduction, one individual is selected at random from :math:`P_\mathrm{p}`, cloned and appended to :math:`P_\mathrm{o}`. This variation is named *Or* beceause an offspring will never result from both operations crossover and mutation. The sum of both probabilities shall be in :math:`[0, 1]`, the reproduction probability is 1 - *cxpb* - *mutpb*. 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 population. :param population: A list of individuals to vary. :param toolbox: A :class:`~deap.base.Toolbox` that contains the evolution operators. :param lambda\_: The number of children to produce :param cxpb: The probability of mating two individuals. :param mutpb: The probability of mutating an individual. :returns: The final population :returns: A class:`~deap.tools.Logbook` with the statistics of the evolution The variation goes as follow. On each of the *lambda_* iteration, it selects one of the three operations; crossover, mutation or reproduction. In the case of a crossover, two individuals are selected at random from the parental population :math:`P_\mathrm{p}`, those individuals are cloned using the :meth:`toolbox.clone` method and then mated using the :meth:`toolbox.mate` method. Only the first child is appended to the offspring population :math:`P_\mathrm{o}`, the second child is discarded. In the case of a mutation, one individual is selected at random from :math:`P_\mathrm{p}`, it is cloned and then mutated using using the :meth:`toolbox.mutate` method. The resulting mutant is appended to :math:`P_\mathrm{o}`. In the case of a reproduction, one individual is selected at random from :math:`P_\mathrm{p}`, cloned and appended to :math:`P_\mathrm{o}`. This variation is named *Or* beceause an offspring will never result from both operations crossover and mutation. The sum of both probabilities shall be in :math:`[0, 1]`, the reproduction probability is 1 - *cxpb* - *mutpb*. """ offspring = [] for _ in range(lambda_): op_choice = np.random.random() if op_choice < cxpb: # Apply crossover ind1, ind2 = pick_two_individuals_eligible_for_crossover(population) if ind1 is not None: ind1, _ = toolbox.mate(ind1, ind2) del ind1.fitness.values else: # If there is no pair eligible for crossover, we still want to # create diversity in the population, and do so by mutation instead. ind1 = mutate_random_individual(population, toolbox) offspring.append(ind1) elif op_choice < cxpb + mutpb: # Apply mutation ind = mutate_random_individual(population, toolbox) offspring.append(ind) else: # Apply reproduction idx = np.random.randint(0, len(population)) offspring.append(toolbox.clone(population[idx])) return offspring
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 cumulatively. Initialized as: 0 'crossover_count': number of crossover operations applied to the individual and its predecessor cumulatively. Initialized as: 0 'predecessor': string representation of the individual. Initialized as: ('ROOT',) Parameters ---------- individual: deap individual Returns ------- object 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 cumulatively. Initialized as: 0 'crossover_count': number of crossover operations applied to the individual and its predecessor cumulatively. Initialized as: 0 'predecessor': string representation of the individual. Initialized as: ('ROOT',) Parameters ---------- individual: deap individual Returns ------- object ''' individual.statistics['generation'] = 0 individual.statistics['mutation_count'] = 0 individual.statistics['crossover_count'] = 0 individual.statistics['predecessor'] = 'ROOT',
This is the :math:`(\mu + \lambda)` evolutionary algorithm. :param population: A list of individuals. :param toolbox: A :class:`~deap.base.Toolbox` that contains the evolution operators. :param mu: The number of individuals to select for the next generation. :param lambda\_: The number of children to produce at each generation. :param cxpb: The probability that an offspring is produced by crossover. :param mutpb: The probability that an offspring is produced by mutation. :param ngen: The number of generation. :param pbar: processing bar :param stats: A :class:`~deap.tools.Statistics` object that is updated inplace, optional. :param halloffame: A :class:`~deap.tools.HallOfFame` object that will contain the best individuals, optional. :param verbose: Whether or not to log the statistics. :param per_generation_function: if supplied, call this function before each generation used by tpot to save best pipeline before each new generation :returns: The final population :returns: A class:`~deap.tools.Logbook` with the statistics of the evolution. The algorithm takes in a population and evolves it in place using the :func:`varOr` function. It returns the optimized population and a :class:`~deap.tools.Logbook` with the statistics of the evolution. The logbook will contain the generation number, the number of evalutions for each generation and the statistics if a :class:`~deap.tools.Statistics` is given as argument. The *cxpb* and *mutpb* arguments are passed to the :func:`varOr` function. The pseudocode goes as follow :: evaluate(population) for g in range(ngen): offspring = varOr(population, toolbox, lambda_, cxpb, mutpb) evaluate(offspring) population = select(population + offspring, mu) First, the individuals having an invalid fitness are evaluated. Second, the evolutionary loop begins by producing *lambda_* offspring from the population, the offspring are generated by the :func:`varOr` function. The offspring are then evaluated and the next generation population is selected from both the offspring **and** the population. Finally, when *ngen* generations are done, the algorithm returns a tuple with the final population and a :class:`~deap.tools.Logbook` of the evolution. This function expects :meth:`toolbox.mate`, :meth:`toolbox.mutate`, :meth:`toolbox.select` and :meth:`toolbox.evaluate` aliases to be registered in the toolbox. This algorithm uses the :func:`varOr` variation. 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.base.Toolbox` that contains the evolution operators. :param mu: The number of individuals to select for the next generation. :param lambda\_: The number of children to produce at each generation. :param cxpb: The probability that an offspring is produced by crossover. :param mutpb: The probability that an offspring is produced by mutation. :param ngen: The number of generation. :param pbar: processing bar :param stats: A :class:`~deap.tools.Statistics` object that is updated inplace, optional. :param halloffame: A :class:`~deap.tools.HallOfFame` object that will contain the best individuals, optional. :param verbose: Whether or not to log the statistics. :param per_generation_function: if supplied, call this function before each generation used by tpot to save best pipeline before each new generation :returns: The final population :returns: A class:`~deap.tools.Logbook` with the statistics of the evolution. The algorithm takes in a population and evolves it in place using the :func:`varOr` function. It returns the optimized population and a :class:`~deap.tools.Logbook` with the statistics of the evolution. The logbook will contain the generation number, the number of evalutions for each generation and the statistics if a :class:`~deap.tools.Statistics` is given as argument. The *cxpb* and *mutpb* arguments are passed to the :func:`varOr` function. The pseudocode goes as follow :: evaluate(population) for g in range(ngen): offspring = varOr(population, toolbox, lambda_, cxpb, mutpb) evaluate(offspring) population = select(population + offspring, mu) First, the individuals having an invalid fitness are evaluated. Second, the evolutionary loop begins by producing *lambda_* offspring from the population, the offspring are generated by the :func:`varOr` function. The offspring are then evaluated and the next generation population is selected from both the offspring **and** the population. Finally, when *ngen* generations are done, the algorithm returns a tuple with the final population and a :class:`~deap.tools.Logbook` of the evolution. This function expects :meth:`toolbox.mate`, :meth:`toolbox.mutate`, :meth:`toolbox.select` and :meth:`toolbox.evaluate` aliases to be registered in the toolbox. This algorithm uses the :func:`varOr` variation. """ logbook = tools.Logbook() logbook.header = ['gen', 'nevals'] + (stats.fields if stats else []) # Initialize statistics dict for the individuals in the population, to keep track of mutation/crossover operations and predecessor relations for ind in population: initialize_stats_dict(ind) population = toolbox.evaluate(population) record = stats.compile(population) if stats is not None else {} logbook.record(gen=0, nevals=len(population), **record) # Begin the generational process for gen in range(1, ngen + 1): # after each population save a periodic pipeline if per_generation_function is not None: per_generation_function(gen) # Vary the population offspring = varOr(population, toolbox, lambda_, cxpb, mutpb) # Update generation statistic for all individuals which have invalid 'generation' stats # This hold for individuals that have been altered in the varOr function for ind in population: if ind.statistics['generation'] == 'INVALID': ind.statistics['generation'] = gen # Evaluate the individuals with an invalid fitness invalid_ind = [ind for ind in offspring if not ind.fitness.valid] offspring = toolbox.evaluate(offspring) # Select the next generation population population[:] = toolbox.select(population + offspring, mu) # pbar process if not pbar.disable: # Print only the best individual fitness if verbose == 2: high_score = max([halloffame.keys[x].wvalues[1] for x in range(len(halloffame.keys))]) pbar.write('Generation {0} - Current best internal CV score: {1}'.format(gen, high_score)) # Print the entire Pareto front elif verbose == 3: pbar.write('Generation {} - Current Pareto front scores:'.format(gen)) for pipeline, pipeline_scores in zip(halloffame.items, reversed(halloffame.keys)): pbar.write('{}\t{}\t{}'.format( int(pipeline_scores.wvalues[0]), pipeline_scores.wvalues[1], pipeline ) ) pbar.write('') # after each population save a periodic pipeline if per_generation_function is not None: per_generation_function(gen) # Update the statistics with the new population record = stats.compile(population) if stats is not None else {} logbook.record(gen=gen, nevals=len(invalid_ind), **record) return population, logbook
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. 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. """ # List all available primitive types in each individual types1 = defaultdict(list) types2 = defaultdict(list) for idx, node in enumerate(ind1[1:], 1): types1[node.ret].append(idx) common_types = [] for idx, node in enumerate(ind2[1:], 1): if node.ret in types1 and node.ret not in types2: common_types.append(node.ret) types2[node.ret].append(idx) if len(common_types) > 0: type_ = np.random.choice(common_types) index1 = np.random.choice(types1[type_]) index2 = np.random.choice(types2[type_]) slice1 = ind1.searchSubtree(index1) slice2 = ind2.searchSubtree(index2) ind1[slice1], ind2[slice2] = ind2[slice2], ind1[slice1] return ind1, ind2
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 of pipeline operators and model parameters that can be compiled by DEAP into a callable function Returns ------- individual: DEAP individual Returns the individual with one of point mutation applied to it 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 of pipeline operators and model parameters that can be compiled by DEAP into a callable function Returns ------- individual: DEAP individual Returns the individual with one of point mutation applied to it """ index = np.random.randint(0, len(individual)) node = individual[index] slice_ = individual.searchSubtree(index) if node.arity == 0: # Terminal term = np.random.choice(pset.terminals[node.ret]) if isclass(term): term = term() individual[index] = term else: # Primitive # find next primitive if any rindex = None if index + 1 < len(individual): for i, tmpnode in enumerate(individual[index + 1:], index + 1): if isinstance(tmpnode, gp.Primitive) and tmpnode.ret in tmpnode.args: rindex = i break # pset.primitives[node.ret] can get a list of the type of node # for example: if op.root is True then the node.ret is Output_DF object # based on the function _setup_pset. Then primitives is the list of classifor or regressor primitives = pset.primitives[node.ret] if len(primitives) != 0: new_node = np.random.choice(primitives) new_subtree = [None] * len(new_node.args) if rindex: rnode = individual[rindex] rslice = individual.searchSubtree(rindex) # find position for passing return values to next operator position = np.random.choice([i for i, a in enumerate(new_node.args) if a == rnode.ret]) else: position = None for i, arg_type in enumerate(new_node.args): if i != position: term = np.random.choice(pset.terminals[arg_type]) if isclass(term): term = term() new_subtree[i] = term # paste the subtree to new node if rindex: new_subtree[position:position + 1] = individual[rslice] # combine with primitives new_subtree.insert(0, new_node) individual[slice_] = new_subtree return individual,
Fit estimator and compute scores for a given dataset split. Parameters ---------- sklearn_pipeline : pipeline object implementing 'fit' The object to use to fit the data. features : array-like of shape at least 2D The data to fit. target : array-like, optional, default: None The target variable to try to predict in the case of supervised learning. cv: int or cross-validation generator If CV is a number, then it is the number of folds to evaluate each pipeline over in k-fold cross-validation during the TPOT optimization process. If it is an object then it is an object to be used as a cross-validation generator. scoring_function : callable A scorer callable object / function with signature ``scorer(estimator, X, y)``. sample_weight : array-like, optional List of sample weights to balance (or un-balanace) the dataset target as needed groups: array-like {n_samples, }, optional Group labels for the samples used while splitting the dataset into train/test set use_dask : bool, default False Whether to use dask 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 : pipeline object implementing 'fit' The object to use to fit the data. features : array-like of shape at least 2D The data to fit. target : array-like, optional, default: None The target variable to try to predict in the case of supervised learning. cv: int or cross-validation generator If CV is a number, then it is the number of folds to evaluate each pipeline over in k-fold cross-validation during the TPOT optimization process. If it is an object then it is an object to be used as a cross-validation generator. scoring_function : callable A scorer callable object / function with signature ``scorer(estimator, X, y)``. sample_weight : array-like, optional List of sample weights to balance (or un-balanace) the dataset target as needed groups: array-like {n_samples, }, optional Group labels for the samples used while splitting the dataset into train/test set use_dask : bool, default False Whether to use dask """ sample_weight_dict = set_sample_weight(sklearn_pipeline.steps, sample_weight) features, target, groups = indexable(features, target, groups) cv = check_cv(cv, target, classifier=is_classifier(sklearn_pipeline)) cv_iter = list(cv.split(features, target, groups)) scorer = check_scoring(sklearn_pipeline, scoring=scoring_function) if use_dask: try: import dask_ml.model_selection # noqa import dask # noqa from dask.delayed import Delayed except ImportError: msg = "'use_dask' requires the optional dask and dask-ml depedencies." raise ImportError(msg) dsk, keys, n_splits = dask_ml.model_selection._search.build_graph( estimator=sklearn_pipeline, cv=cv, scorer=scorer, candidate_params=[{}], X=features, y=target, groups=groups, fit_params=sample_weight_dict, refit=False, error_score=float('-inf'), ) cv_results = Delayed(keys[0], dsk) scores = [cv_results['split{}_test_score'.format(i)] for i in range(n_splits)] CV_score = dask.delayed(np.array)(scores)[:, 0] return dask.delayed(np.nanmean)(CV_score) else: try: with warnings.catch_warnings(): warnings.simplefilter('ignore') scores = [_fit_and_score(estimator=clone(sklearn_pipeline), X=features, y=target, scorer=scorer, train=train, test=test, verbose=0, parameters=None, fit_params=sample_weight_dict) for train, test in cv_iter] CV_score = np.array(scores)[:, 0] return np.nanmean(CV_score) except TimeoutException: return "Timeout" except Exception as e: return -float('inf')
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 An operator class 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 An operator class """ ret_op_classes = [op for op in operators if op.__name__ == opname] if len(ret_op_classes) == 0: raise TypeError('Cannot found operator {} in operator dictionary'.format(opname)) elif len(ret_op_classes) > 1: raise ValueError( 'Found duplicate operators {} in operator dictionary. Please check ' 'your dictionary file.'.format(opname) ) ret_op_class = ret_op_classes[0] return ret_op_class
Generate source code for a TPOT Pipeline. Parameters ---------- exported_pipeline: deap.creator.Individual The pipeline that is being exported operators: List of operator classes from operator library pipeline_score: Optional pipeline score to be saved to the exported file impute: bool (False): If impute = True, then adda a imputation step. random_state: integer Random seed in train_test_split function. data_file_path: string (default: '') By default, the path of input dataset is 'PATH/TO/DATA/FILE' by default. If data_file_path is another string, the path will be replaced. Returns ------- pipeline_text: str The source code representing the pipeline 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.creator.Individual The pipeline that is being exported operators: List of operator classes from operator library pipeline_score: Optional pipeline score to be saved to the exported file impute: bool (False): If impute = True, then adda a imputation step. random_state: integer Random seed in train_test_split function. data_file_path: string (default: '') By default, the path of input dataset is 'PATH/TO/DATA/FILE' by default. If data_file_path is another string, the path will be replaced. Returns ------- pipeline_text: str The source code representing the pipeline """ # Unroll the nested function calls into serial code pipeline_tree = expr_to_tree(exported_pipeline, pset) # Have the exported code import all of the necessary modules and functions pipeline_text = generate_import_code(exported_pipeline, operators, impute) pipeline_code = pipeline_code_wrapper(generate_export_pipeline_code(pipeline_tree, operators)) if pipeline_code.count("FunctionTransformer(copy)"): pipeline_text += """from sklearn.preprocessing import FunctionTransformer from copy import copy """ if not data_file_path: data_file_path = 'PATH/TO/DATA/FILE' pipeline_text += """ # NOTE: Make sure that the class is labeled 'target' in the data file tpot_data = pd.read_csv('{}', sep='COLUMN_SEPARATOR', dtype=np.float64) features = tpot_data.drop('target', axis=1).values training_features, testing_features, training_target, testing_target = \\ train_test_split(features, tpot_data['target'].values, random_state={}) """.format(data_file_path, random_state) # Add the imputation step if it was used by TPOT if impute: pipeline_text += """ imputer = Imputer(strategy="median") imputer.fit(training_features) training_features = imputer.transform(training_features) testing_features = imputer.transform(testing_features) """ if pipeline_score is not None: pipeline_text += '\n# Average CV score on the training set was:{}'.format(pipeline_score) pipeline_text += '\n' # Replace the function calls with their corresponding Python code pipeline_text += pipeline_code return pipeline_text
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 EXAMPLE: pipeline: "DecisionTreeClassifier(input_matrix, 28.0)" pipeline_tree: ['DecisionTreeClassifier', 'input_matrix', 28.0] 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 EXAMPLE: pipeline: "DecisionTreeClassifier(input_matrix, 28.0)" pipeline_tree: ['DecisionTreeClassifier', 'input_matrix', 28.0] """ def prim_to_list(prim, args): if isinstance(prim, deap.gp.Terminal): if prim.name in pset.context: return pset.context[prim.name] else: return prim.value return [prim.name] + args tree = [] stack = [] for node in ind: stack.append((node, [])) while len(stack[-1][1]) == stack[-1][0].arity: prim, args = stack.pop() tree = prim_to_list(prim, args) if len(stack) == 0: break # If stack is empty, all nodes should have been seen stack[-1][1].append(tree) return tree
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 : bool Whether to impute new values in the feature set. Returns ------- pipeline_text: String The Python code that imports all required library used 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 : bool Whether to impute new values in the feature set. Returns ------- pipeline_text: String The Python code that imports all required library used in the current optimized pipeline """ def merge_imports(old_dict, new_dict): # Key is a module name for key in new_dict.keys(): if key in old_dict.keys(): # Union imports from the same module old_dict[key] = set(old_dict[key]) | set(new_dict[key]) else: old_dict[key] = set(new_dict[key]) operators_used = [x.name for x in pipeline if isinstance(x, deap.gp.Primitive)] pipeline_text = 'import numpy as np\nimport pandas as pd\n' pipeline_imports = _starting_imports(operators, operators_used) # Build dict of import requirments from list of operators import_relations = {op.__name__: op.import_hash for op in operators} # Add the imputer if necessary if impute: pipeline_imports['sklearn.preprocessing'] = ['Imputer'] # Build import dict from operators used for op in operators_used: try: operator_import = import_relations[op] merge_imports(pipeline_imports, operator_import) except KeyError: pass # Operator does not require imports # Build import string for key in sorted(pipeline_imports.keys()): module_list = ', '.join(sorted(pipeline_imports[key])) pipeline_text += 'from {} import {}\n'.format(key, module_list) return pipeline_text
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_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 """ steps = _process_operator(pipeline_tree, operators) pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_indent(",\n".join(steps), 4)) return pipeline_text
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 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 sklearn pipeline """ steps = _process_operator(pipeline_tree, operators) # number of steps in a pipeline num_step = len(steps) if num_step > 1: pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_indent(",\n".join(steps), 4)) # only one operator (root = True) else: pipeline_text = "{STEPS}".format(STEPS=_indent(",\n".join(steps), 0)) return pipeline_text
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 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 indentation + ('\n' + indentation).join(text.split('\n'))
Get the next value in the page. 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 return result
Verifies the parameters don't use any reserved parameter. Raises: ValueError: If a reserved parameter is used. 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("Using a reserved parameter", reserved_in_use)
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. 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() items = response.get(self._items_key, ()) page = Page(self, items, self.item_to_value) self._page_start(self, page, response) self.next_page_token = response.get(self._next_token) return page else: return None
Getter for query parameters for the next request. Returns: dict: A dictionary of query parameters. 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_results is not None: result[self._MAX_RESULTS] = self.max_results - self.num_results result.update(self.extra_params) return result
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``. 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_params() if self._HTTP_METHOD == "GET": return self.api_request( method=self._HTTP_METHOD, path=self.path, query_params=params ) elif self._HTTP_METHOD == "POST": return self.api_request( method=self._HTTP_METHOD, path=self.path, data=params ) else: raise ValueError("Unexpected HTTP method", self._HTTP_METHOD)
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 there are no pages left. 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 there are no pages left. """ try: items = six.next(self._gax_page_iter) page = Page(self, items, self.item_to_value) self.next_page_token = self._gax_page_iter.page_token or None return page except StopIteration: return None
Get the next page in the iterator. Returns: Page: The next page in the iterator or :data:`None` if there are no pages left. 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: setattr(self._request, self._request_token_field, self.next_page_token) response = self._method(self._request) self.next_page_token = getattr(response, self._response_token_field) items = getattr(response, self._items_field) page = Page(self, items, self.item_to_value) return page
Determines whether or not there are more pages with results. Returns: bool: Whether the iterator has more pages. 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 >= self.max_results: return False # Note: intentionally a falsy check instead of a None check. The RPC # can return an empty string indicating no more pages. return True if self.next_page_token else False
Main comparison function for all Firestore types. @return -1 is left < right, 0 if left == right, otherwise 1 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).value if leftType != rightType: if leftType < rightType: return -1 return 1 value_type = left.WhichOneof("value_type") if value_type == "null_value": return 0 # nulls are all equal elif value_type == "boolean_value": return cls._compare_to(left.boolean_value, right.boolean_value) elif value_type == "integer_value": return cls.compare_numbers(left, right) elif value_type == "double_value": return cls.compare_numbers(left, right) elif value_type == "timestamp_value": return cls.compare_timestamps(left, right) elif value_type == "string_value": return cls._compare_to(left.string_value, right.string_value) elif value_type == "bytes_value": return cls.compare_blobs(left, right) elif value_type == "reference_value": return cls.compare_resource_paths(left, right) elif value_type == "geo_point_value": return cls.compare_geo_points(left, right) elif value_type == "array_value": return cls.compare_arrays(left, right) elif value_type == "map_value": return cls.compare_objects(left, right) else: raise ValueError("Unknown ``value_type``", str(value_type))
Service that performs image detection and annotation for a batch of files. Now only "application/pdf", "image/tiff" and "image/gif" are supported. This service will extract at most the first 10 frames (gif) or pages (pdf or tiff) from each file provided and perform detection and annotation for each image extracted. Example: >>> from google.cloud import vision_v1p4beta1 >>> >>> client = vision_v1p4beta1.ImageAnnotatorClient() >>> >>> # TODO: Initialize `requests`: >>> requests = [] >>> >>> response = client.batch_annotate_files(requests) Args: requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]]): The list of file annotation requests. Right now we support only one AnnotateFileRequest in BatchAnnotateFilesRequest. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateFileRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.vision_v1p4beta1.types.BatchAnnotateFilesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. 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 "application/pdf", "image/tiff" and "image/gif" are supported. This service will extract at most the first 10 frames (gif) or pages (pdf or tiff) from each file provided and perform detection and annotation for each image extracted. Example: >>> from google.cloud import vision_v1p4beta1 >>> >>> client = vision_v1p4beta1.ImageAnnotatorClient() >>> >>> # TODO: Initialize `requests`: >>> requests = [] >>> >>> response = client.batch_annotate_files(requests) Args: requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]]): The list of file annotation requests. Right now we support only one AnnotateFileRequest in BatchAnnotateFilesRequest. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateFileRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.vision_v1p4beta1.types.BatchAnnotateFilesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "batch_annotate_files" not in self._inner_api_calls: self._inner_api_calls[ "batch_annotate_files" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.batch_annotate_files, default_retry=self._method_configs["BatchAnnotateFiles"].retry, default_timeout=self._method_configs["BatchAnnotateFiles"].timeout, client_info=self._client_info, ) request = image_annotator_pb2.BatchAnnotateFilesRequest(requests=requests) return self._inner_api_calls["batch_annotate_files"]( request, retry=retry, timeout=timeout, metadata=metadata )
Run asynchronous image detection and annotation for a list of images. Progress and results can be retrieved through the ``google.longrunning.Operations`` interface. ``Operation.metadata`` contains ``OperationMetadata`` (metadata). ``Operation.response`` contains ``AsyncBatchAnnotateImagesResponse`` (results). This service will write image annotation outputs to json files in customer GCS bucket, each json file containing BatchAnnotateImagesResponse proto. Example: >>> from google.cloud import vision_v1p4beta1 >>> >>> client = vision_v1p4beta1.ImageAnnotatorClient() >>> >>> # TODO: Initialize `requests`: >>> requests = [] >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.async_batch_annotate_images(requests, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]]): Individual image annotation requests for this batch. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest` output_config (Union[dict, ~google.cloud.vision_v1p4beta1.types.OutputConfig]): Required. The desired output location and metadata (e.g. format). If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.OutputConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. 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. Progress and results can be retrieved through the ``google.longrunning.Operations`` interface. ``Operation.metadata`` contains ``OperationMetadata`` (metadata). ``Operation.response`` contains ``AsyncBatchAnnotateImagesResponse`` (results). This service will write image annotation outputs to json files in customer GCS bucket, each json file containing BatchAnnotateImagesResponse proto. Example: >>> from google.cloud import vision_v1p4beta1 >>> >>> client = vision_v1p4beta1.ImageAnnotatorClient() >>> >>> # TODO: Initialize `requests`: >>> requests = [] >>> >>> # TODO: Initialize `output_config`: >>> output_config = {} >>> >>> response = client.async_batch_annotate_images(requests, output_config) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]]): Individual image annotation requests for this batch. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest` output_config (Union[dict, ~google.cloud.vision_v1p4beta1.types.OutputConfig]): Required. The desired output location and metadata (e.g. format). If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.OutputConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "async_batch_annotate_images" not in self._inner_api_calls: self._inner_api_calls[ "async_batch_annotate_images" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.async_batch_annotate_images, default_retry=self._method_configs["AsyncBatchAnnotateImages"].retry, default_timeout=self._method_configs[ "AsyncBatchAnnotateImages" ].timeout, client_info=self._client_info, ) request = image_annotator_pb2.AsyncBatchAnnotateImagesRequest( requests=requests, output_config=output_config ) operation = self._inner_api_calls["async_batch_annotate_images"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, image_annotator_pb2.AsyncBatchAnnotateImagesResponse, metadata_type=image_annotator_pb2.OperationMetadata, )
Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be retrieved through the ``google.longrunning.Operations`` interface. ``Operation.metadata`` contains ``OperationMetadata`` (metadata). ``Operation.response`` contains ``AsyncBatchAnnotateFilesResponse`` (results). Example: >>> from google.cloud import vision_v1p4beta1 >>> >>> client = vision_v1p4beta1.ImageAnnotatorClient() >>> >>> # TODO: Initialize `requests`: >>> requests = [] >>> >>> response = client.async_batch_annotate_files(requests) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]]): Individual async file annotation requests for this batch. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. 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 PDF files, which may contain multiple pages and multiple images per page. Progress and results can be retrieved through the ``google.longrunning.Operations`` interface. ``Operation.metadata`` contains ``OperationMetadata`` (metadata). ``Operation.response`` contains ``AsyncBatchAnnotateFilesResponse`` (results). Example: >>> from google.cloud import vision_v1p4beta1 >>> >>> client = vision_v1p4beta1.ImageAnnotatorClient() >>> >>> # TODO: Initialize `requests`: >>> requests = [] >>> >>> response = client.async_batch_annotate_files(requests) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]]): Individual async file annotation requests for this batch. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "async_batch_annotate_files" not in self._inner_api_calls: self._inner_api_calls[ "async_batch_annotate_files" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.async_batch_annotate_files, default_retry=self._method_configs["AsyncBatchAnnotateFiles"].retry, default_timeout=self._method_configs["AsyncBatchAnnotateFiles"].timeout, client_info=self._client_info, ) request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest(requests=requests) operation = self._inner_api_calls["async_batch_annotate_files"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, image_annotator_pb2.AsyncBatchAnnotateFilesResponse, metadata_type=image_annotator_pb2.OperationMetadata, )
Called by IPython when this module is loaded as an IPython extension. 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" )
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` constructor. Returns: GoogleAPICallError: An instance of the appropriate subclass of :class:`GoogleAPICallError`. 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` constructor. Returns: GoogleAPICallError: An instance of the appropriate subclass of :class:`GoogleAPICallError`. """ error_class = exception_class_for_http_status(status_code) error = error_class(message, **kwargs) if error.code is None: error.code = status_code return error
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 message and errors populated from the response. 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 message and errors populated from the response. """ try: payload = response.json() except ValueError: payload = {"error": {"message": response.text or "unknown error"}} error_message = payload.get("error", {}).get("message", "unknown error") errors = payload.get("error", {}).get("errors", ()) message = "{method} {url}: {error}".format( method=response.request.method, url=response.request.url, error=error_message ) exception = from_http_status( response.status_code, message, errors=errors, response=response ) return exception
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:`GoogleAPICallError` constructor. Returns: GoogleAPICallError: An instance of the appropriate subclass of :class:`GoogleAPICallError`. 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:`GoogleAPICallError` constructor. Returns: GoogleAPICallError: An instance of the appropriate subclass of :class:`GoogleAPICallError`. """ error_class = exception_class_for_grpc_status(status_code) error = error_class(message, **kwargs) if error.grpc_status_code is None: error.grpc_status_code = status_code return error
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`. 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_exc, grpc.Call): return from_grpc_status( rpc_exc.code(), rpc_exc.details(), errors=(rpc_exc,), response=rpc_exc ) else: return GoogleAPICallError(str(rpc_exc), errors=(rpc_exc,), response=rpc_exc)
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 :param method: The API call method name (ie, ``runQuery``, ``lookup``, etc) :type data: str :param data: The data to send with the API call. Typically this is a serialized Protobuf string. :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The string response content from the API call. :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the response code is not 200 OK. 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 :param method: The API call method name (ie, ``runQuery``, ``lookup``, etc) :type data: str :param data: The data to send with the API call. Typically this is a serialized Protobuf string. :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The string response content from the API call. :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the response code is not 200 OK. """ headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } api_url = build_api_url(project, method, base_url) response = http.request(url=api_url, method="POST", headers=headers, data=data) if response.status_code != 200: error_status = status_pb2.Status.FromString(response.content) raise exceptions.from_http_status( response.status_code, error_status.message, errors=[error_status] ) return response.content
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 name in the cloud console. :type method: str :param method: The name of the method to invoke. :type base_url: str :param base_url: The base URL where the API lives. :type request_pb: :class:`google.protobuf.message.Message` instance :param request_pb: the protobuf instance representing the request. :type response_pb_cls: A :class:`google.protobuf.message.Message` subclass. :param response_pb_cls: The class used to unmarshall the response protobuf. :rtype: :class:`google.protobuf.message.Message` :returns: The RPC message parsed from the response. 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 name in the cloud console. :type method: str :param method: The name of the method to invoke. :type base_url: str :param base_url: The base URL where the API lives. :type request_pb: :class:`google.protobuf.message.Message` instance :param request_pb: the protobuf instance representing the request. :type response_pb_cls: A :class:`google.protobuf.message.Message` subclass. :param response_pb_cls: The class used to unmarshall the response protobuf. :rtype: :class:`google.protobuf.message.Message` :returns: The RPC message parsed from the response. """ req_data = request_pb.SerializeToString() response = _request(http, project, method, req_data, base_url) return response_pb_cls.FromString(response)
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 your project name in the cloud console. :type method: str :param method: The API method to call (e.g. 'runQuery', 'lookup'). :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The API URL created. 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 your project name in the cloud console. :type method: str :param method: The API method to call (e.g. 'runQuery', 'lookup'). :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The API URL created. """ return API_URL_TEMPLATE.format( api_base=base_url, api_version=API_VERSION, project=project, method=method )
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] :param keys: The keys to retrieve from the datastore. :type read_options: :class:`.datastore_pb2.ReadOptions` :param read_options: (Optional) The options for this lookup. Contains either the transaction for the read or ``STRONG`` or ``EVENTUAL`` read consistency. :rtype: :class:`.datastore_pb2.LookupResponse` :returns: The returned protobuf response object. 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] :param keys: The keys to retrieve from the datastore. :type read_options: :class:`.datastore_pb2.ReadOptions` :param read_options: (Optional) The options for this lookup. Contains either the transaction for the read or ``STRONG`` or ``EVENTUAL`` read consistency. :rtype: :class:`.datastore_pb2.LookupResponse` :returns: The returned protobuf response object. """ request_pb = _datastore_pb2.LookupRequest( project_id=project_id, read_options=read_options, keys=keys ) return _rpc( self.client._http, project_id, "lookup", self.client._base_url, request_pb, _datastore_pb2.LookupResponse, )
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. :type partition_id: :class:`.entity_pb2.PartitionId` :param partition_id: Partition ID corresponding to an optional namespace and project ID. :type read_options: :class:`.datastore_pb2.ReadOptions` :param read_options: (Optional) The options for this query. Contains either the transaction for the read or ``STRONG`` or ``EVENTUAL`` read consistency. :type query: :class:`.query_pb2.Query` :param query: (Optional) The query protobuf to run. At most one of ``query`` and ``gql_query`` can be specified. :type gql_query: :class:`.query_pb2.GqlQuery` :param gql_query: (Optional) The GQL query to run. At most one of ``query`` and ``gql_query`` can be specified. :rtype: :class:`.datastore_pb2.RunQueryResponse` :returns: The returned protobuf response object. 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. :type partition_id: :class:`.entity_pb2.PartitionId` :param partition_id: Partition ID corresponding to an optional namespace and project ID. :type read_options: :class:`.datastore_pb2.ReadOptions` :param read_options: (Optional) The options for this query. Contains either the transaction for the read or ``STRONG`` or ``EVENTUAL`` read consistency. :type query: :class:`.query_pb2.Query` :param query: (Optional) The query protobuf to run. At most one of ``query`` and ``gql_query`` can be specified. :type gql_query: :class:`.query_pb2.GqlQuery` :param gql_query: (Optional) The GQL query to run. At most one of ``query`` and ``gql_query`` can be specified. :rtype: :class:`.datastore_pb2.RunQueryResponse` :returns: The returned protobuf response object. """ request_pb = _datastore_pb2.RunQueryRequest( project_id=project_id, partition_id=partition_id, read_options=read_options, query=query, gql_query=gql_query, ) return _rpc( self.client._http, project_id, "runQuery", self.client._base_url, request_pb, _datastore_pb2.RunQueryResponse, )