peal.data.datasets.Image2MixedDataset¶
- class peal.data.datasets.Image2MixedDataset[source]¶
Bases:
ImageDatasetImage dataset with multi-attribute CSV labels (CelebA-style).
Images live under
<root_dir>/<config.x_selection>/and are looked up by the keys of the label CSV<root_dir>/<config.label_rel_path>(seeimage_name/open_imagefor the tolerated filename variants); optional masks live under<root_dir>/masks/. Attribute names of the formA_vs_Byield the positive/negative phrases used for text descriptions. Targets are thetask_config.y_selectionattributes (or the firstconfig.output_size[0]columns); with a"ce"criterion the single target is returned as anint64class index.config.class_ratiossubsamples the split to fixed class proportions. If the subclass definessample_to_2d_latent, decision boundary and global counterfactual plots become available.- Parameters:
config (
DataConfig) – Usesdataset_path,label_rel_path,x_selection,delimiter,set_negative_to_zero,input_size,output_size,class_ratios,has_hints,in_memoryandconfounding_factors.mode (
str) – Split:"train","val","test"or"all".root_dir (
str, optional) – Dataset root; overrides and rewritesconfig.dataset_path.data_dir (
str, optional) – Path of the label CSV. Defaults to<root_dir>/<label_rel_path>.transform (
callable, optional) – Applied to the PIL image (and, with the same RNG state, to the mask). Defaults toToTensor().task_config (
TaskConfig, optional) – Target selection,output_channelsandcriterions.return_dict (
bool, optional) – Return a dict from__getitem__instead of(x, y...).
- Variables:
Methods
Restore
backup_keys(note:class_restrictions_enabledstays True).Stop returning
has_confounder.Stop returning masks.
Stop returning the sample index.
Stop returning the text description.
Drop the tokenizer and restore the previous description setting.
Stop returning the image key.
Keep only samples whose first selected target equals
class_idx.Also return
has_confounderfrom theconfounding_factorscolumns.Also return the mask from
<root_dir>/masksashint.Also return the sample index.
Also return a text
descriptionbuilt from the target attributes.Also return
tokens: the description tokenized withtokenizer.Also return the image key as
url.Collage rendering that adds the 2D latent coordinates to the title.
Generalized global counterfactual visualization using sample_to_2d_latent.
The image filename a dataset key refers to (keys may omit the suffix).
Cache every image (and mask, if
config.has_hints) as a numpy array.Open an image by filename, tolerating .jpg/.png and zero-padded variants.
Subsample
keysso the classes followconfig.class_ratios.Generalized decision boundary visualization using sample_to_2d_latent.
Attributes
task_config.output_channelswhen targets are selected, else columns.- visualize_decision_boundary(predictor, batch_size, device, path, temperature=1.0, train_dataloader=None, val_dataloaders=[], val_weights=[], test_dataloader=None)[source]¶
Generalized decision boundary visualization using sample_to_2d_latent.
Uses the balanced test dataset to fit a linear model in the 2D latent space, then visualizes the decision boundary with train/val/test sample overlays.
Requires
self.sample_to_2d_latent(returns silently otherwise). A logistic regression on the test latents (fitted on the predictor’s predictions) yields a probability grid that is saved as<path minus .png>.npyand..._bounds.npyforglobal_counterfactual_visualization; the test plot goes todecision_boundary_test.pngnext topathand the train/val plot topath. Marker fill shows the prediction, edge the label.- Parameters:
predictor (
torch.nn.Module) – Classifier evaluated ondevice.batch_size (
int) – Unused; kept for interface compatibility.device (
torch.deviceorstr) – Device for predictor and latent extraction.path (
str) – Output PNG of the train/val plot.temperature (
float, optional) – Unused.train_dataloader (
DataLoaderorDataloaderMixer, optional) – Up to 8 batches are plotted.val_dataloaders (
listorWeightedDataloaderList, optional) – Validation loaders;val_weightsscales the batch budget.test_dataloader (
DataLoader, optional) – Up to 16 batches define the latent range and fit the model.
- global_counterfactual_visualization(filename, x_list, counterfactuals, y_target_start_confidence, y_target_end_confidence, y_list, hint_list, attempts=1)[source]¶
Generalized global counterfactual visualization using sample_to_2d_latent.
Picks up to 10 samples of each of the first two classes seen in
y_list(plus their extra attempts), maps factuals and counterfactuals to 2D latents and draws arrows between them on top of the decision boundary grid saved byvisualize_decision_boundary(decision_boundary.npyordecision_boundary_precise.npyin the directory offilename). Returns silently withoutsample_to_2d_latent.- Parameters:
filename (
str) – Output image path;"_precise"in the name selects the precise grid.x_list (
listoftorch.Tensor) – Factual and counterfactual images, attempts stacked block-wise.counterfactuals (
listoftorch.Tensor) – Factual and counterfactual images, attempts stacked block-wise.y_target_start_confidence (
list) – Target confidences used to color the arrow ends.y_target_end_confidence (
list) – Target confidences used to color the arrow ends.y_list (
list) – Ground-truth labels.hint_list (
list, optional) – Hints forwarded tosample_to_2d_latent.attempts (
int, optional) – Number of attempts per factual contained in the lists.
- generate_contrastive_collage(x_list, x_counterfactual_list, y_target_list, y_source_list, y_list, y_target_start_confidence_list, y_target_end_confidence_list, base_path, idx_to_info=None, **kwargs)[source]¶
Collage rendering that adds the 2D latent coordinates to the title.
If
idx_to_infois not given and the dataset hassample_to_2d_latent, a default is built that prints<factor>: <before> -> <after>per latent dimension (named afterconfig.confounding_factors). Everything else is delegated toImageDataset.generate_contrastive_collage.- Returns:
(heatmap_list, collage_paths)from the base implementation.- Return type:
- Parameters:
- __init__(config, mode, root_dir=None, data_dir=None, transform=torchvision.transforms.ToTensor, task_config=None, return_dict=False)[source]¶
Parse the label CSV and optionally load all images into memory.
- load_in_memory()[source]¶
Cache every image (and mask, if
config.has_hints) as a numpy array.Images are stored in
in_memory_imagesunder the resolved filename and converted to"L"or"RGB"according toconfig.input_size[0]; masks go toin_memory_masks.
- property output_size¶
task_config.output_channelswhen targets are selected, else columns.
- enable_string_description()[source]¶
Also return a text
descriptionbuilt from the target attributes.
- enable_tokens(tokenizer)[source]¶
Also return
tokens: the description tokenized withtokenizer.- Parameters:
tokenizer (
callable) – HuggingFace-style tokenizer withmodel_max_length; the description is padded/truncated to that length.
- enable_class_restriction(class_idx)[source]¶
Keep only samples whose first selected target equals
class_idx.The full key list is saved in
backup_keys; requirestask_configwithy_selection.- Parameters:
class_idx (
int) – Class value to keep.
- disable_class_restriction()[source]¶
Restore
backup_keys(note:class_restrictions_enabledstays True).