select.py
import goldener.select
Selection of the most representative subset of samples.
The selection finds a coresubset: a subset of samples representing at best the full dataset from its vectors. It is
used to choose the data to annotate and, by the goldener.split.GoldSplitter, to fill the sets of a split.
GoldSelectionToolis the abstract interface of the coresubset selection algorithms.GoldGreedyKernelPointsSelectionTool,GoldGreedyKCenterSelectionTool,GoldGreedyClosestPointSelectionTool,GoldGreedyFarthestPointSelectionToolandGoldZCoreSelectionToolimplement different selection algorithms.GoldSelectorruns the selection on a whole dataset of vectors, possibly in chunks, after a dimensionality reduction (goldener.reduce) or stratified by label, and stores the selected samples locally.
Run selection of a subset of data points from vectorized samples using a coresubset selection algorithm.
Attributes:
- distance_func: The distance function to use for computing distances between points,
determined by the
distanceparameter in the constructor.
Select a subset of data points from the input data.
Arguments:
- x: A 2D torch.Tensor where each row represents a data point.
- k: The number of data points to select.
- anchors: Optional 2D torch.Tensor of anchor points to consider during selection. The shape should be (num_anchors, feature_dim). If provided, the selection will be performed with respect to these anchor points and it will affect the selection process.
Returns:
A list of indices corresponding to the selected data points.
Coresubset selection using Coreax's GreedyKernelPoints solver.
The solver is created at each request depending on the specified k points to select.
With this method, the anchors are not used for the selection process.
Attributes:
- feature_kernel: The kernel to use for the GreedyKernelPoints solver.
- random_key: Random key for reproducibility in the GreedyKernelPoints solver.
- distance_func: Not used in this selection tool, included for compatibility with the base class.
Initialize the GoldGreedyKernelPointsSelectionTool.
Arguments:
- feature_kernel: The kernel to use for the GreedyKernelPoints solver.
- random_key: Random key for reproducibility in the GreedyKernelPoints solver. Default is 42.
- distance: Not used in this selection tool, included for compatibility with the base class.
Select a subset of data points from the input data using greedy kernel point coresubset sampling.
With this method, the anchors are not used for the selection process.
Arguments:
- x: A 2D torch.Tensor where each row represents a data point.
- k: The number of data points to select.
- anchors: Not used in this selection tool, included for compatibility with the base class.
Returns:
A list of indices corresponding to the selected data points.
Raises:
- ValueError: If x is not a 2D tensor.
If
kis greater than the number of data points inx.
Inherited Members
Create a coresubset from selecting with the K Center greedy algorithm.
This is a greedy algorithm that selects iteratively the farthest to the already selected points among the not selected points. The first center is selected as the point with the largest aggregated distance to all the other points.
Attributes:
- device: The torch device to use for computations.
- distance_func: The distance function to use for computing distances between points,
determined by the
distanceparameter in the constructor.
Initialize the GoldGreedyKCenterSelectionTool.
Arguments:
- device: The torch device to use for computations.
- distance: The distance type to use for selection.
Select a subset of data points from the input data by choosing iteratively the point with the farthest nearest neighbors among the not selected points.
Arguments:
- x: A 2D torch.Tensor where each row represents a data point.
- k: The number of data points to select.
- anchors: Optional 2D torch.Tensor of anchor points to consider during selection. The shape should be (num_anchors, feature_dim). If provided, the selection will be performed with respect to these anchor points and it will affect the selection process.
Returns:
A list of indices corresponding to the selected data points.
Raises:
- ValueError: If x is not a 2D tensor.
If
kis greater than the number of data points inx.
Inherited Members
Create a coresubset from selecting the closest points iteratively.
This is a greedy algorithm that selects iteratively the point with the closest nearest neighbors among the not selected points.
With this method, the anchors are not used for the selection process.
Attributes:
- device: The torch device to use for computations.
Initialize the GoldGreedyClosestPointSelectionTool.
Arguments:
- device: The torch device to use for computations.
- distance: The distance type to use for selection.
Select a subset of data points from the input data by choosing iteratively the point with the closest nearest neighbors among the not selected points.
Arguments:
- x: A 2D torch.Tensor where each row represents a data point.
- k: The number of data points to select.
- anchors: Not used in this selection tool, included for compatibility with the base class.
Returns:
A list of indices corresponding to the selected data points.
Raises:
- ValueError: If x is not a 2D tensor.
If
kis greater than the number of data points inx.
Inherited Members
Create a coresubset from selecting the farthest points iteratively.
This is a greedy algorithm that selects iteratively the point with the farthest nearest neighbors among the not selected points.
With this method, the anchors are not used for the selection process.
Attributes:
- device: The torch device to use for computations.
- distance_func: The distance function to use for computing distances between points,
determined by the
distanceparameter in the constructor.
Initialize the GoldGreedyFarthestPointSelectionTool.
Arguments:
- device: The torch device to use for computations.
- distance: The distance type to use for selection.
Select a subset of data points from the input data by choosing iteratively the point with the farthest nearest neighbors among the not selected points.
Arguments:
- x: A 2D torch.Tensor where each row represents a data point.
- k: The number of data points to select.
- anchors: Not used in this selection tool, included for compatibility with the base class.
Returns:
A list of indices corresponding to the selected data points.
Raises:
- ValueError: If x is not a 2D tensor.
If
kis greater than the number of data points inx.
Inherited Members
Create a coresubset from selecting with the ZCore algorithm.
This algorithm compute a score of coverage penalized by a redundancy penalty for each point and select the points with the highest score.
This selection tool is inspired from Zero-Shot Coreset Selection via Iterative Subspace Sampling.
Attributes:
- device: The torch device to use for computations.
- distance_func: The distance function to use for computing distances between points
- n_dim_for_score: The number of dimensions to use when computing the coverage score and redundancy penalty. Default is 2.
- n_random_anchors: The number of random anchors to use for computing the coverage score. Default is 2 million.
- n_redundancy: The number of closest points to consider for the redundancy penalty. Default is 1000.
- redundancy_scale: The scale factor for the redundancy penalty. Default is 4.
- eps: A small value to avoid division by zero in the redundancy penalty. Default is 1e-8.
- random_state: Optional random state for reproducibility when generating random anchors. Default is None.
Initialize the GoldZCoreSelectionTool.
Arguments:
- device: The torch device to use for computations.
- distance: The distance type to use for selection.
- n_dim_for_score: The number of dimensions to use when computing the coverage score and redundancy penalty. Default is 2.
- n_random_anchors: The number of random anchors to use for computing the coverage score. Default is 2 million.
- n_redundancy: The number of closest points to consider for the redundancy penalty. Default is 1000.
- redundancy_scale: The scale factor for the redundancy penalty. Default is 4.
- eps: A small value to avoid division by zero in the redundancy penalty. Default is 1e-8.
- random_state: Optional random state for reproducibility when generating random anchors. Default is None.
Raises:
- ValueError: If
n_dim_for_scoreis not a positive integer. Ifn_random_anchorsis not a positive integer. Ifepsis not a positive float.
Select a subset of data points from the ZCore algorithm.
Arguments:
- x: A 2D torch.Tensor where each row represents a data point.
- k: The number of data points to select.
- anchors: This selection tool does not use anchors, included for compatibility with the base class.
Returns:
A list of indices corresponding to the selected data points.
Raises:
- ValueError: If x is not a 2D tensor.
If
kis greater than the number of data points inx. ifn_dim_for_scoreis greater than the number of dimensions inx.
Inherited Members
Select a subset of data points from vectorized samples.
The GoldSelector processes a dataset or PixelTable table to perform coresubset selection using a
selection algorithm on already vectorized representations. The selection results are stored
in a local PixelTable table (specified by table_path) so that the selection process is idempotent:
calling the same operation multiple times will not duplicate or recompute selections that are already
present in the table.
If the dataset is too big to fit into memory or the coresubset selection algorithm is too computationally expensive, the coresubset selection can be performed in chunks. All torch tensors will be converted to numpy arrays before saving.
The selection can operate in a sequential (single-process) mode or a
distributed mode (not implemented). The table schema is created/validated automatically and will include
minimal indexing columns (idx, idx_vector) required to link selected samples back to
their originating data points.
Attributes:
- table_path: Path to the PixelTable table where selection results will be stored locally.
- selection_tool: The GoldSelectionTool implementing the selection algorithm.
- reducer: Optional GoldReductionTool instance for dimensionality reduction before selection.
- chunk: Optional chunk size for processing data in chunks to reduce memory consumption.
- collate_fn: Optional function to collate dataset samples into batches composed of
dictionaries with at least the key specified by
vectorized_keyreturning a PyTorch Tensor. If None,collate_keeping_sequences_as_sequencesis used, which preserves sequence-valued fields as one sequence per sample. - vectorized_key: Key in the batch dictionary that contains the vectorized data for selection. Default is "vectorized".
- include_vectorized_in_table: Whether to include the vectorized data in the selection table. Defaults to False.
- It is only applied if the cluster table is created from a Table (it is forced anyway for Dataset).
- selection_key: Column name to store the selection value in the PixelTable table. Default is "selected".
- label_key: Optional key for label-based stratified selection.
- exclude_labels: Optional set of label strings to exclude from selection. Default is None.
- to_keep_schema: Optional dictionary defining additional columns to keep from the original dataset/table into the selection table. The keys are the column names and the values are the PixelTable types.
- min_pxt_insert_size: Minimum number of rows to accumulate before inserting into PixelTable. Default is 100.
- batch_size: Batch size used when iterating over the data.
- num_workers: Number of workers for the PyTorch DataLoader during iteration on data.
- allow_existing: If False, an error will be raised when the table already exists. Default is True.
- distribute: Whether to use distributed processing for selection and table population. Not implemented yet. Default is False.
- drop_table: Whether to drop the selection table after creating the dataset with selection results. It is only applied
when using
select_in_dataset. Default is False. - max_batches: Optional maximum number of batches to process. Useful for testing on a small subset of the dataset.
- random_state: Optional random state for reproducibility during chunk assignment. Default is None.
Initialize the GoldSelector.
Arguments:
- table_path: Path to store the PixelTable table.
- selection_tool: The GoldSelectionTool implementing the selection algorithm.
- reducer: Optional GoldReductionTool instance for dimensionality reduction before selection.
- chunk: Optional chunk size for processing data in chunks.
- collate_fn: Optional collate function for the DataLoader.
If None,
collate_keeping_sequences_as_sequencesis used. - vectorized_key: Key pointing to the vector for selection. Defaults to "vectorized".
- include_vectorized_in_table: Whether to include the vectorized data in the selection table. Defaults to False. It is only applied if the selection table is created from a Table (it is forced anyway for Dataset).
- selection_key: Key for storing selection values. Defaults to "selected".
- label_key: Optional key for label stratification.
- exclude_labels: Optional set of label strings to exclude from selection. Default is None.
- to_keep_schema: Optional schema for additional columns to preserve.
- min_pxt_insert_size: Minimum number of rows to accumulate before inserting into PixelTable. Default is 100.
- batch_size: Batch size used when iterating over the data.
- num_workers: Number of workers for the PyTorch DataLoader during iteration on data.
- allow_existing: Whether to allow using an existing table. Defaults to True.
- distribute: Whether to use distributed selection. Not implemented yet. Defaults to False.
- drop_table: Whether to drop the table after dataset creation. Defaults to False.
- max_batches: Optional maximum number of batches to process.
- random_state: Optional random state for reproducibility during chunk assignment. Default is None.
Raises:
- ValueError: If
exclude_labelsis provided butlabel_keyis None. - NotImplementedError: If
distributeis True.
Set up the selection table based on the source dataset or table.
Arguments:
- select_from: Dataset or Table to select from. If a Dataset is provided, each item should be a
dictionary with at least the
vectorized_keyandidxkeys after applying the collate_fn. If a Table is provided, it should contain at least thevectorized_key,idxandidx_vectorcolumns.
Returns: A PixelTable Table with the appropriate schema for selection, populated with rows corresponding to the source dataset or table.
Raises:
- ValueError: If
allow_existingis False and the table attable_pathalready exists, or if an existing selection table is missing the expected primary keyidx_vector.
Select a subset of samples using coresubset selection and return results as a GoldPxtTorchDataset.
The selection process applies a coresubset selection algorithm on already vectorized
representations of the data points and stores results in a PixelTable table specified by table_path.
When the chunk attribute is set, the selection is performed in chunks to reduce memory consumption.
If a reducer is provided, the vectors are reduced in dimension before applying the coresubset selection.
This is a convenience wrapper that runs select_in_table to populate
(or resume populating) the PixelTable table, then wraps the table into a
GoldPxtTorchDataset for downstream consumption. If drop_table is True,
the table will be removed after the dataset is created.
Arguments:
- select_from: Dataset or Table to select from. If a Dataset is provided, each item should be a
dictionary with at least the
vectorized_keyandidxkeys after applying the collate_fn. If a Table is provided, it should contain at least thevectorized_key,idxandidx_vectorcolumns. - select_size: Number or ratio (between 0 and 1) of data points to select
- value: Value to set in the
selection_keycolumn for selected samples. - restrict_to: Optional set of indices to restrict the search to.
If provided, only the selected indices in
restriction_idx_keywill be used for the selection. - restriction_idx_key: Column name used to get sample indices for restriction.
Returns:
A GoldPxtTorchDataset containing at least the selection information in the
selection_keykey andidx(index of the sample) andidx_vector(index of the vector) keys as well.
Select a subset of samples using coresubset selection and store results in a PixelTable table.
The selection process applies a coresubset selection algorithm on already vectorized
representations of the data points and stores results in a PixelTable table specified by table_path.
When the chunk attribute is set, the selection is performed in chunks to reduce memory consumption.
If a reducer is provided, the vectors are reduced in dimension before applying the coresubset selection.
This method is idempotent (i.e., failure proof), meaning that if it is called multiple times on the same dataset or table, it will restart the selection process based on the vectors already present in the PixelTable table.
Arguments:
- select_from: Dataset or Table to select from. If a Dataset is provided, each item should be a
dictionary with at least the
vectorized_keyandidxkeys after applying the collate_fn. If a Table is provided, it should contain at least thevectorized_key,idxandidx_vectorcolumns. - select_size: Number or ratio (between 0 and 1) of data points to select.
- value: Value to set in the
selection_keycolumn for selected samples. - restrict_to: Optional set of indices to restrict the search to.
If provided, only the selected indices in
restriction_idx_keywill be used for the selection. - restriction_idx_key: Column name used to get sample indices for restriction.
Returns:
A PixelTable Table containing at least the selection information in the
selection_keycolumn andidx(index of the sample) andidx_vector(index of the vector) columns as well.
Raises:
- ValueError: If
restriction_idx_keyis not"idx"or"idx_vector", or if select_size is a float not in the range ]0.0, 1.0].
Get the Pixeltable query to access samples selected with a given value.
Arguments:
- table: PixelTable table to query.
- value: Value in the selection_key column to filter selected samples.
- selection_key: Column name used to store selection values.
- label_key: Optional column name used to filter samples by label.
- label_value: Optional label value to filter samples by label.
- idx_key: Column name used to get sample indices.
- restrict_to: Optional set of indices to restrict the search to.
If provided, only the selected indices in
restriction_idx_keywill be used for the selection. - restriction_idx_key: Column name used to get sample indices for restriction.
Returns:
A PixelTable Query object that can be executed to access the samples with the specified value (and label if specified).
Raises:
- ValueError: If only one of
label_keyorlabel_valueis provided (both must be set together).
Get the indices of samples selected with a given value.
Arguments:
- table: PixelTable table to query.
- value: Value in the selection_key column to filter selected samples.
- selection_key: Column name used to store selection values.
- label_key: Optional column name used to filter samples by label.
- label_value: Optional label value to filter samples by label.
- idx_key: Column name used to get sample indices.
- restrict_to: Optional set of indices to restrict the search to.
If provided, only the selected indices in
restriction_idx_keywill be used for the selection. - restriction_idx_key: Column name used to get sample indices for restriction.
Returns:
A set of indices with the specified value (and label if specified).
Raises:
- ValueError: If only one of
label_keyorlabel_valueis provided (both must be set together).
Get the number of samples selected with a given value.
Arguments:
- table: PixelTable table to query.
- value: Value in the selection_key column to filter selected samples.
- selection_key: Column name used to store selection values.
- label_key: Optional column name used to filter samples by label.
- label_value: Optional label value to filter samples by label.
- idx_key: Column name used to get sample indices.
- restrict_to: Optional set of indices to restrict the search to.
If provided, only the selected indices in
restriction_idx_keywill be used for the selection. - restriction_idx_key: Column name used to get sample indices for restriction.
Returns:
The number of samples with the specified value (and label if specified).