{"id":13692120,"url":"https://github.com/p-lambda/wilds","last_synced_at":"2025-05-02T19:31:24.501Z","repository":{"id":38896263,"uuid":"320346918","full_name":"p-lambda/wilds","owner":"p-lambda","description":"A machine learning benchmark of in-the-wild distribution shifts, with data loaders, evaluators, and default models.","archived":false,"fork":false,"pushed_at":"2024-01-26T17:09:51.000Z","size":1329,"stargazers_count":564,"open_issues_count":14,"forks_count":129,"subscribers_count":19,"default_branch":"main","last_synced_at":"2025-04-21T06:58:09.007Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://wilds.stanford.edu","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/p-lambda.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-12-10T17:45:18.000Z","updated_at":"2025-04-20T17:34:20.000Z","dependencies_parsed_at":"2024-01-08T17:20:08.106Z","dependency_job_id":"a47e7a2c-253c-4166-abb2-ae507bb73c8a","html_url":"https://github.com/p-lambda/wilds","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p-lambda%2Fwilds","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p-lambda%2Fwilds/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p-lambda%2Fwilds/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/p-lambda%2Fwilds/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/p-lambda","download_url":"https://codeload.github.com/p-lambda/wilds/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252095218,"owners_count":21693877,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T17:00:53.914Z","updated_at":"2025-05-02T19:31:23.475Z","avatar_url":"https://github.com/p-lambda.png","language":"Python","readme":"\u003cp align='center'\u003e\n  \u003cimg width='40%' src='https://wilds.stanford.edu/WILDS_cropped.png' /\u003e\n\u003c/p\u003e\n\n--------------------------------------------------------------------------------\n\n[![PyPI](https://img.shields.io/pypi/v/wilds)](https://pypi.org/project/wilds/)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/p-lambda/wilds/blob/master/LICENSE)\n\n## Overview\nWILDS is a benchmark of in-the-wild distribution shifts spanning diverse data modalities and applications, from tumor identification to wildlife monitoring to poverty mapping.\n\nThe WILDS package contains:\n1. Data loaders that automatically handle data downloading, processing, and splitting, and\n2. Dataset evaluators that standardize model evaluation for each dataset.\n\nIn addition, the example scripts contain default models, optimizers, schedulers, and training/evaluation code.\nNew algorithms can be easily added and run on all of the WILDS datasets.\n\nFor more information, please visit [our website](https://wilds.stanford.edu) or read the main WILDS paper ([1](https://arxiv.org/abs/2012.07421)) and its follow-up integrating unlabeled data ([2](https://arxiv.org/abs/2112.05090)).\nFor questions and feedback, please post on the [discussion board](https://github.com/p-lambda/wilds/discussions).\n\n## Installation\n\nWe recommend using pip to install WILDS:\n```bash\npip install wilds\n```\n\nIf you have already installed it, please check that you have the latest version:\n```bash\npython -c \"import wilds; print(wilds.__version__)\"\n# This should print \"2.0.0\". If it doesn't, update by running:\npip install -U wilds\n```\n\nIf you plan to edit or contribute to WILDS, you should install from source:\n```bash\ngit clone git@github.com:p-lambda/wilds.git\ncd wilds\npip install -e .\n```\n\nIn `examples/`, we provide a set of scripts that can be used to train models on the WILDS datasets. These scripts were also used to benchmark baselines in our papers [[1](https://arxiv.org/abs/2012.07421), [2](https://arxiv.org/abs/2112.05090)].\nThese scripts are not part of the installed WILDS package. To use them, you should install from source, as described above.\n\n### Requirements\nThe WILDS package depends on the following requirements:\n\n- numpy\u003e=1.19.1\n- ogb\u003e=1.2.6\n- outdated\u003e=0.2.0\n- pandas\u003e=1.1.0\n- pillow\u003e=7.2.0\n- pytz\u003e=2020.4\n- torch\u003e=1.7.0\n- torch-scatter\u003e=2.0.5\n- torch-geometric\u003e=2.0.1\n- torchvision\u003e=0.8.2\n- tqdm\u003e=4.53.0\n- scikit-learn\u003e=0.20.0\n- scipy\u003e=1.5.4\n\nRunning `pip install wilds` or `pip install -e .` will automatically check for and install all of these requirements\n**except for the `torch-scatter` and `torch-geometric` packages**, which require a\n[quick manual install](https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html#installation-via-binaries).\n\n### Example script requirements\nTo run the example scripts, you will also need to install these additional dependencies:\n\n- transformers\u003e=3.5.0\n- SwAV requires [Apex](https://github.com/NVIDIA/apex).\n  To install Apex, please follow the [README from the official SwAV repository](https://github.com/facebookresearch/swav#requirements).\n- Our code supports the optional use of [Weights \u0026 Biases](https://wandb.ai/site) to track and monitor experiments.\n  To install the Weights and Biases Python package, run `pip install wandb`.\n\nAll baseline experiments in the paper were run on Python 3.8.5 and CUDA 10.1.\n\n## Datasets\nWILDS currently includes 10 datasets, which we've briefly listed below. For full dataset descriptions, please see our papers ([1](https://arxiv.org/abs/2012.07421), [2](https://arxiv.org/abs/2112.05090)).\n\n| Dataset       | Modality | Labeled splits                    | Unlabeled splits                                                |\n| ------------- | -------- | --------------------------------- | --------------------------------------------------------------- |\n| iwildcam      | Image    | train, val, test, id_val, id_test | extra_unlabeled                                                 |\n| camelyon17    | Image    | train, val, test, id_val          | train_unlabeled, val_unlabeled, test_unlabeled                  |\n| rxrx1         | Image    | train, val, test, id_test         | -                                                               |\n| ogb-molpcba   | Graph    | train, val, test                  | train_unlabeled, val_unlabeled, test_unlabeled                  |\n| globalwheat   | Image    | train, val, test, id_val, id_test | train_unlabeled, val_unlabeled, test_unlabeled, extra_unlabeled |\n| civilcomments | Text     | train, val, test                  | extra_unlabeled                                                 |\n| fmow          | Image    | train, val, test, id_val, id_test | train_unlabeled, val_unlabeled, test_unlabeled                  |\n| poverty       | Image    | train, val, test, id_val, id_test | train_unlabeled, val_unlabeled, test_unlabeled                  |\n| amazon        | Text     | train, val, test, id_val, id_test | val_unlabeled, test_unlabeled, extra_unlabeled                  |\n| py150         | Text     | train, val, test, id_val, id_test | -                                                               |\n\n## Using the WILDS package\n### Data\n\nThe WILDS package provides a simple, standardized interface for all datasets in the benchmark.\nThis short Python snippet covers all of the steps of getting started with a WILDS dataset, including dataset download and initialization, accessing various splits, and preparing a user-customizable data loader.\nWe discuss data loading in more detail in [#Data loading](#data-loading).\n\n```py\nfrom wilds import get_dataset\nfrom wilds.common.data_loaders import get_train_loader\nimport torchvision.transforms as transforms\n\n# Load the full dataset, and download it if necessary\ndataset = get_dataset(dataset=\"iwildcam\", download=True)\n\n# Get the training set\ntrain_data = dataset.get_subset(\n    \"train\",\n    transform=transforms.Compose(\n        [transforms.Resize((448, 448)), transforms.ToTensor()]\n    ),\n)\n\n# Prepare the standard data loader\ntrain_loader = get_train_loader(\"standard\", train_data, batch_size=16)\n\n# (Optional) Load unlabeled data\ndataset = get_dataset(dataset=\"iwildcam\", download=True, unlabeled=True)\nunlabeled_data = dataset.get_subset(\n    \"test_unlabeled\",\n    transform=transforms.Compose(\n        [transforms.Resize((448, 448)), transforms.ToTensor()]\n    ),\n)\nunlabeled_loader = get_train_loader(\"standard\", unlabeled_data, batch_size=16)\n\n# Train loop\nfor labeled_batch, unlabeled_batch in zip(train_loader, unlabeled_loader):\n    x, y, metadata = labeled_batch\n    unlabeled_x, unlabeled_metadata = unlabeled_batch\n    ...\n```\n\nThe `metadata` contains information like the domain identity, e.g., which camera a photo was taken from, or which hospital the patient's data came from, etc., as well as other metadata.\n\n### Domain information\nTo allow algorithms to leverage domain annotations as well as other groupings over the available metadata, the WILDS package provides `Grouper` objects.\nThese `Grouper` objects are helper objects that extract group annotations from metadata, allowing users to specify the grouping scheme in a flexible fashion.\nThey are used to initialize group-aware data loaders (as discussed in [#Data loading](#data-loading)) and to implement algorithms that rely on domain annotations (e.g., Group DRO).\nIn the following code snippet, we initialize and use a `Grouper` that extracts the domain annotations on the iWildCam dataset, where the domain is location.\n\n```py\nfrom wilds.common.grouper import CombinatorialGrouper\n\n# Initialize grouper, which extracts domain information\n# In this example, we form domains based on location\ngrouper = CombinatorialGrouper(dataset, ['location'])\n\n# Train loop\nfor x, y_true, metadata in train_loader:\n    z = grouper.metadata_to_group(metadata)\n    ...\n```\n\n### Data loading\n\nFor training, the WILDS package provides two types of data loaders.\nThe standard data loader shuffles examples in the training set, and is used for the standard approach of empirical risk minimization (ERM), where we minimize the average loss.\n```py\nfrom wilds.common.data_loaders import get_train_loader\n\n# Prepare the standard data loader\ntrain_loader = get_train_loader('standard', train_data, batch_size=16)\n```\n\nTo support other algorithms that rely on specific data loading schemes, we also provide the group data loader.\nIn each minibatch, the group loader first samples a specified number of groups, and then samples a fixed number of examples from each of those groups.\n(By default, the groups are sampled uniformly at random, which upweights minority groups as a result. This can be toggled by the `uniform_over_groups` parameter.)\nWe initialize group loaders as follows, using `Grouper` that specifies the grouping scheme.\n\n```py\n# Prepare a group data loader that samples from user-specified groups\ntrain_loader = get_train_loader(\n    \"group\", train_data, grouper=grouper, n_groups_per_batch=2, batch_size=16\n)\n\n```\n\nLastly, we also provide a data loader for evaluation, which loads examples without shuffling (unlike the training loaders).\n\n```py\nfrom wilds.common.data_loaders import get_eval_loader\n\n# Get the test set\ntest_data = dataset.get_subset(\n    \"test\",\n    transform=transforms.Compose(\n        [transforms.Resize((224, 224)), transforms.ToTensor()]\n    ),\n)\n\n# Prepare the evaluation data loader\ntest_loader = get_eval_loader(\"standard\", test_data, batch_size=16)\n\n```\n\n### Evaluators\n\nThe WILDS package standardizes and automates evaluation for each dataset.\nInvoking the `eval` method of each dataset yields all metrics reported in the paper and on the leaderboard.\n\n```py\nfrom wilds.common.data_loaders import get_eval_loader\n\n# Get the test set\ntest_data = dataset.get_subset(\n    \"test\",\n    transform=transforms.Compose(\n        [transforms.Resize((224, 224)), transforms.ToTensor()]\n    ),\n)\n\n# Prepare the data loader\ntest_loader = get_eval_loader(\"standard\", test_data, batch_size=16)\n\n# Get predictions for the full test set\nfor x, y_true, metadata in test_loader:\n    y_pred = model(x)\n    # Accumulate y_true, y_pred, metadata\n\n# Evaluate\ndataset.eval(all_y_pred, all_y_true, all_metadata)\n# {'recall_macro_all': 0.66, ...}\n```\nMost `eval` methods take in predicted labels for `all_y_pred` by default, but the default inputs vary across datasets and are documented in the `eval` docstrings of the corresponding dataset class.\n\n## Using the example scripts\nIn `examples/`, we provide a set of scripts that can be used to train models on the WILDS datasets.\n\n```bash\npython examples/run_expt.py --dataset iwildcam --algorithm ERM --root_dir data\npython examples/run_expt.py --dataset civilcomments --algorithm groupDRO --root_dir data\npython examples/run_expt.py --dataset fmow --algorithm DANN --unlabeled_split test_unlabeled --root_dir data\n```\n\nThe scripts are configured to use the default models and reasonable hyperparameters. For exact hyperparameter settings used in our papers, please see [our CodaLab executable paper](https://wilds.stanford.edu/codalab).\n\n### Downloading and training on the WILDS datasets\nThe first time you run these scripts, you might need to download the datasets. You can do so with the `--download` argument, for example:\n```python\n# downloads (labeled) dataset\npython examples/run_expt.py --dataset globalwheat --algorithm groupDRO --root_dir data --download\n\n# additionally downloads all unlabeled data\npython examples/run_expt.py --dataset globalwheat --algorithm groupDRO --root_dir data --download  --unlabeled_split [...]\n```\nNote that downloading the large amount of unlabeled data is optional; unlabeled data will only be downloaded if some `--unlabeled_split` is set. (It does not matter which `--unlabeled_split` is set; all unlabeled data will be downloaded together.)\n\nAlternatively, you can use the standalone `wilds/download_datasets.py` script to download the datasets, for example:\n\n```bash\n# downloads (labeled) data\npython wilds/download_datasets.py --root_dir data\n\n# downloads (unlabeled) data\npython wilds/download_datasets.py --root_dir data --unlabeled\n```\n\nThis will download all datasets to the specified `data` folder. You can also use the `--datasets` argument to download particular datasets.\n\nThese are the sizes of each of our datasets, as well as their approximate time taken to train and evaluate the default model for a single ERM run using a NVIDIA V100 GPU.\n\n| Dataset command | Modality | Download size (GB) | Size on disk (GB) | Train+eval time (Hours) |\n| --------------- | -------- | ------------------ | ----------------- | ----------------------- |\n| iwildcam        | Image    | 11                 | 25                | 7                       |\n| camelyon17      | Image    | 10                 | 15                | 2                       |\n| rxrx1           | Image    | 7                  | 7                 | 11                      |\n| ogb-molpcba     | Graph    | 0.04               | 2                 | 15                      |\n| globalwheat     | Image    | 10                 | 10                | 2                       |\n| civilcomments   | Text     | 0.1                | 0.3               | 4.5                     |\n| fmow            | Image    | 50                 | 55                | 6                       |\n| poverty         | Image    | 12                 | 14                | 5                       |\n| amazon          | Text     | 7                  | 7                 | 5                       |\n| py150           | Text     | 0.1                | 0.8               | 9.5                     |\n\nThe following are the sizes of the unlabeled data bundles:\n\n| Dataset command | Modality | Download size (GB) | Size on disk (GB) |\n| --------------- | -------- | ------------------ | ----------------- |\n| iwildcam        | Image    | 41                 | 41                |\n| camelyon17      | Image    | 69.4               | 96                |\n| ogb-molpcba     | Graph    | 1.2                | 21                |\n| globalwheat     | Image    | 103                | 108               |\n| civilcomments   | Text     | 0.3                | 0.6               |\n| fmow\\*          | Image    | 50                 | 55                |\n| poverty         | Image    | 172                | 184               |\n| amazon\\*        | Text     | 7                  | 7                 |\n\n\u003csup\u003e \\* These unlabeled datasets are downloaded simultaneously with the labeled data and do not need to be downloaded separately. \u003c/sup\u003e\n\nWhile the `camelyon17` dataset is small and fast to train on, we advise against using it as the only dataset to prototype methods on, as the test performance of models trained on this dataset tend to exhibit a large degree of variability over random seeds.\n\nThe image datasets (`iwildcam`, `camelyon17`, `rxrx1`, `globalwheat`, `fmow`, and `poverty`) tend to have high disk I/O usage. If training time is much slower for you than the approximate times listed above, consider checking if I/O is a bottleneck (e.g., by moving to a local disk if you are using a network drive, or by increasing the number of data loader workers). To speed up training, you could also disable evaluation at each epoch or for all splits by toggling `--evaluate_all_splits` and related arguments.\n\n### Algorithms\nIn the `examples/algorithms` folder, we provide implementations of the adaptation algorithms benchmarked in our papers ([1](https://arxiv.org/abs/2012.07421), [2](https://arxiv.org/abs/2112.05090)).\nAll algorithms train on labeled data from a WILDS dataset's `train` split.\nSome algorithms are designed to also leverage unlabeled data. To load unlabeled data, specify an `--unlabeled_split` when running.\n\nIn addition to shared hyperparameters such as `lr`, `weight_decay`, `batch_size`, and `unlabeled_batch_size`, the scripts also take in command line arguments for algorithm-specific hyperparameters.\n\n| Algorithm command                                | Hyperparameters                                                                            | Notes                             | See WILDS paper                                                                |\n| ------------------------------------------------ | ------------------------------------------------------------------------------------------ | --------------------------------- | ------------------------------------------------------------------------------ |\n| ERM                                              | -                                                                                          | Only uses labeled data            | ([1](https://arxiv.org/abs/2012.07421), [2](https://arxiv.org/abs/2112.05090)) |\n| [groupDRO](https://arxiv.org/abs/1911.08731)     | `group_dro_step_size`                                                                      | Only uses labeled data            | ([1](https://arxiv.org/abs/2012.07421))                                        |\n| [deepCORAL](https://arxiv.org/abs/1511.05547)    | `coral_penalty_weight`                                                                     | Can optionally use unlabeled data | ([1](https://arxiv.org/abs/2012.07421), [2](https://arxiv.org/abs/2112.05090)) |\n| [IRM](https://arxiv.org/abs/1907.02893)          | `irm_lambda`, `irm_penalty_anneal_iters`                                                   | Only uses labeled data            | ([1](https://arxiv.org/abs/2012.07421))                                        |\n| [DANN](https://arxiv.org/abs/1505.07818)         | `dann_penalty_weight`, `dann_classifier_lr`, `dann_featurizer_lr`, `dann_discriminator_lr` | Can use unlabeled data            | ([2](https://arxiv.org/abs/2112.05090))                                        |\n| [AFN](https://arxiv.org/abs/1811.07456)          | `afn_penalty_weight`, `safn_delta_r`, `hafn_r`                                             | Designed to use unlabeled data    | ([2](https://arxiv.org/abs/2112.05090))                                        |\n| [FixMatch](https://arxiv.org/abs/2001.07685)     | `self_training_lambda`, `self_training_threshold`                                          | Designed to use unlabeled data    | ([2](https://arxiv.org/abs/2112.05090))                                        |\n| PseudoLabel                                      | `self_training_lambda`, `self_training_threshold`, `pseudolabel_T2`                        | Designed to use unlabeled data    | ([2](https://arxiv.org/abs/2112.05090))                                        |\n| [NoisyStudent](https://arxiv.org/abs/1911.04252) | `soft_pseudolabels`, `noisystudent_dropout_rate`                                           | Designed to use unlabeled data    | ([2](https://arxiv.org/abs/2112.05090))                                        |\n\nThe repository is set up to facilitate general-purpose algorithm development: new algorithms can be added to `examples/algorithms` and then run on all of the WILDS datasets using the default models.\n\n### Evaluating trained models\nWe also provide an evaluation script that aggregates prediction CSV files for different replicates and reports on their combined evaluation. To use this, run:\n\n```bash\npython examples/evaluate.py \u003cpredictions_dir\u003e \u003coutput_dir\u003e --root_dir \u003croot_dir\u003e\n```\n\nwhere `\u003cpredictions_dir\u003e` is the path to your predictions directory, `\u003coutput_dir\u003e` is where the results JSON will be writte, and `\u003croot_dir\u003e` is the dataset root directory.\nThe predictions directory should have a subdirectory for each dataset\n(e.g. `iwildcam`) containing prediction CSV files to evaluate; see our [submission guidelines](https://wilds.stanford.edu/submit/) for the format.\nThe evaluation script will skip over any datasets that has missing prediction files.\nAny dataset not in `\u003croot_dir\u003e` will be downloaded to `\u003croot_dir\u003e`.\n\n### Reproducibility\nWe have an [executable version](https://wilds.stanford.edu/codalab) of our paper on CodaLab that contains the exact commands, code, and data for the experiments reported in our paper, which rely on these scripts. Trained model weights for all datasets can also be found there.\nAll configurations and hyperparameters can also be found in the `examples/configs` folder of this repo, and dataset-specific parameters are in `examples/configs/datasets.py`.\n\n## Leaderboard\nIf you are developing new training algorithms and/or models on WILDS, please consider submitting them to our [public leaderboard](https://wilds.stanford.edu/leaderboard/).\n\n## Citing WILDS ([Bibtex](https://wilds.stanford.edu/assets/files/wilds_bib.txt))\nIf you use WILDS datasets in your work, please cite our paper:\n\n1. [**WILDS: A Benchmark of in-the-Wild Distribution Shifts.**](https://arxiv.org/abs/2012.07421) Pang Wei Koh*, Shiori Sagawa*, Henrik Marklund, Sang Michael Xie, Marvin Zhang, Akshay Balsubramani, Weihua Hu, Michihiro Yasunaga, Richard Lanas Phillips, Irena Gao, Tony Lee, Etienne David, Ian Stavness, Wei Guo, Berton A. Earnshaw, Imran S. Haque, Sara Beery, Jure Leskovec, Anshul Kundaje, Emma Pierson, Sergey Levine, Chelsea Finn, and Percy Liang. ICML 2021.\n\nIf you use unlabeled data from the WILDS datasets, please also cite:\n\n2. [**Extending the WILDS Benchmark for Unsupervised Adaptation.**](https://arxiv.org/abs/2112.05090) Shiori Sagawa*, Pang Wei Koh*, Tony Lee*, Irena Gao*, Sang Michael Xie, Kendrick Shen, Ananya Kumar, Weihua Hu, Michihiro Yasunaga, Henrik Marklund, Sara Beery, Etienne David, Ian Stavness, Wei Guo, Jure Leskovec, Kate Saenko, Tatsunori Hashimoto, Sergey Levine, Chelsea Finn, and Percy Liang. ICLR 2022.\n\nIn addition, please cite the original papers that introduced the datasets, as listed on the [datasets page](https://wilds.stanford.edu/datasets/).\n\n## Acknowledgements\nThe design of the WILDS benchmark was inspired by the [Open Graph Benchmark](https://ogb.stanford.edu/), and we are grateful to the Open Graph Benchmark team for their advice and help in setting up WILDS.\n","funding_links":[],"categories":["Causal Machine Learning","Python","Code"],"sub_categories":["OoD Generalization"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fp-lambda%2Fwilds","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fp-lambda%2Fwilds","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fp-lambda%2Fwilds/lists"}