GitRead 中文社区
首页趋势排行榜原创文章严选周刊
更多资源
新手训练营
精选专题热门话题GitHub 文档资源精选实战指南

Dassl.pytorch

A PyTorch toolbox for domain generalization, domain adaptation and semi-supervised learning.

  • 语言Python
  • 默认分支master
  • 大小465 KB
  • 更新2023年11月3日
  • Issues26
在 GitHub 打开
avatarKaiyangZhou

项目介绍

KaiyangZhou/Dassl.pytorch 是一个托管在 GitHub 上的开源项目,主要使用 Python 编写,采用 MIT License 许可证,目前获得 1.4k 个 Star、194 次 Fork。

仓库全名
KaiyangZhou/Dassl.pytorch

README 摘要

Dassl Introduction Dassl is a PyTorch toolbox initially developed for our project Domain Adaptive Ensemble Learning (DAEL) to support research in domain adaptation and generalization---since in DAEL we study how to unify these two problems in a single learning framework. Given that domain adaptation is closely related to semi-supervised learning---both study how to exploit unlabeled data---we also incorporate…

完整内容见 GitHub 原始 README 或本页 。

常见问题

Dassl.pytorch 用什么语言开发?

主要使用 Python 编写,采用 MIT License 许可证,目前有 1.4k 个 Star。

Dassl.pytorch 可以免费商用吗?

仓库采用 MIT License 许可证,可免费使用与修改,商业使用请遵守许可证条款(例如保留版权声明与许可声明)。

如何获取 Dassl.pytorch 的源码?

可以直接克隆仓库:git clone https://github.com/KaiyangZhou/Dassl.pytorch.git,默认分支为 master;安装与运行步骤见仓库 README。

Dassl.pytorch 最近还在维护吗?

仓库最近一次更新为 2023年11月3日,当前有 26 个未关闭 Issue;Star 数为 1.4k,可作为社区活跃度的参考。

本页面展示项目元数据与原始 README,GitRead 中文社区 编辑团队负责选题收录。

相关仓库

public-apis/public-apis avatar
public-apispublic-apis
1 天前
497.5k
55.6k
2.6k

免费 API 汇总列表

apipublic-apisfree+7
Python
15.5 MB
7
详情
EbookFoundation/free-programming-books avatar
free-programming-booksEbookFoundation
1 天前
401.3k
67.5k
95

免费可获取的编程书籍

bookseducationhacktoberfest+2
Python
21.8 MB
3
详情
donnemartin/system-design-primer avatar
system-design-primerdonnemartin
9月15日
377.4k
59.2k
644

学习如何设计大规模系统。为系统设计面试做准备。包含 Anki 闪卡。

designdesign-patternsdesign-system+10
Python
11.0 MB
0
详情
vinta/awesome-python avatar
awesome-pythonvinta
22 小时前
333.5k
29.1k
19

回答“我想用 Python 做 X,该用哪个工具?”的权威清单

awesomeawesome-listpython+3
Python
6.9 MB
2
详情
practical-tutorials/project-based-learning avatar
project-based-learningpractical-tutorials
6 小时前
289.4k
36.8k
238

精选的项目实战教程列表

tutorialprojectbeginner-project+5
Python
472 KB
1
详情
NousResearch/hermes-agent avatar
hermes-agentNousResearch
14 分钟前
261.9k
57.9k
19.0k

与你共同成长的智能体

aiai-agentai-agents+10
Python
1.4 GB
3
详情
TheAlgorithms/Python avatar
PythonTheAlgorithms
6 天前
226.0k
50.3k
11

所有算法均用 Python 实现

algorithmalgorithm-competitionsalgorithms-implemented+11
Python
17.9 MB
2
详情
yt-dlp/yt-dlp avatar
yt-dlpyt-dlp
5 天前
206.4k
17.9k
2.1k

功能丰富的命令行音视频下载器

youtube-dlpythonsponsorblock+4
Python
63.5 MB
0
详情

关于

artificial-intelligencebenchmark-datasetscomputer-visiondeep-learningdeep-neural-networksdomain-adaptationdomain-generalizationmachine-learningpytorchsemi-supervised-learning
  • MIT License
  • 1.4k Stars
  • 194 Forks
  • 15 Watching

简要分析

热度分
1834
价值分
917
活跃状态
活跃
GitHub

语言占比

Python
Shell

贡献者

KaiyangZhouKaiyangZhousiaimessiaimesYBZhYBZhwyf0912wyf0912sansyosansyo

Dassl

Introduction

Dassl is a PyTorch toolbox initially developed for our project Domain Adaptive Ensemble Learning (DAEL) to support research in domain adaptation and generalization—since in DAEL we study how to unify these two problems in a single learning framework. Given that domain adaptation is closely related to semi-supervised learning—both study how to exploit unlabeled data—we also incorporate components that support research for the latter.

Why the name “Dassl”? Dassl combines the initials of domain adaptation (DA) and semi-supervised learning (SSL), which sounds natural and informative.

Dassl has a modular design and unified interfaces, allowing fast prototyping and experimentation of new DA/DG/SSL methods. With Dassl, a new method can be implemented with only a few lines of code. Don’t believe? Take a look at the engine folder, which contains the implementations of many existing methods (then you will come back and star this repo). :-)

Basically, Dassl is perfect for doing research in the following areas:

  • Domain adaptation
  • Domain generalization
  • Semi-supervised learning

BUT, thanks to the neat design, Dassl can also be used as a codebase to develop any deep learning projects, like this. :-)

A drawback of Dassl is that it doesn’t (yet? hmm) support distributed multi-GPU training (Dassl uses DataParallel to wrap a model, which is less efficient than DistributedDataParallel).

We don’t provide detailed documentations for Dassl, unlike another project of ours. This is because Dassl is developed for research purpose and as a researcher, we think it’s important to be able to read source code and we highly encourage you to do so—definitely not because we are lazy. :-)

What’s new

  • [Oct 2022] New paper “On-Device Domain Generalization” is out! Code, models and datasets: https://github.com/KaiyangZhou/on-device-dg.
More
  • [Jun 2022] v0.6.0: Make cfg.TRAINER.METHOD_NAME consistent with the method class name.
  • [Jun 2022] A new domain adaptation method CDAC (CVPR’21) is added by Shreejal Trivedi. See here for more details.
  • [Jun 2022] Adds three datasets from the WILDS benchmark: iWildCam, FMoW and Camelyon17. See here for more details.
  • [May 2022] A new domain generalization method DDG developed by Zhishu Sun and to appear at IJCAI’22 is added to this repo. See here for more details.
  • [Mar 2022] A new domain generalization method EFDM developed by Yabin Zhang (PolyU) and to appear at CVPR’22 is added to this repo. See here for more details.
  • [Feb 2022] In case you don’t know, a class in the painting domain of DomainNet (the official splits) only has test images (no training images), which could affect performance. See section 4.a in our paper for more details.
  • [Oct 2021] v0.5.0: Important changes made to transforms.py. 1) center_crop becomes a default transform in testing (applied after resizing the smaller edge to a certain size to keep the image aspect ratio). 2) For training, Resize(cfg.INPUT.SIZE) is deactivated when random_crop or random_resized_crop is used. These changes won’t make any difference to the training transforms used in existing config files, nor to the testing transforms unless the raw images are not squared (the only difference is that now the image aspect ratio is respected).
  • [Oct 2021] v0.4.3: Copy the attributes in self.dm (data manager) to SimpleTrainer and make self.dm optional, which means from now on, you can build data loaders from any source you like rather than being forced to use DataManager.
  • [Sep 2021] v0.4.2: An important update is to set drop_last=is_train and len(data_source)>=batch_size when constructing a data loader to avoid 0-length.

Overview

Dassl has implemented the following methods:

  • Single-source domain adaptation

    • Cross Domain Adaptive Clustering for Semi Supervised Domain Adaptation (CVPR’21) [dassl/engine/da/cdac.py]
    • Semi-supervised Domain Adaptation via Minimax Entropy (ICCV’19) [dassl/engine/da/mme.py]
    • Maximum Classifier Discrepancy for Unsupervised Domain Adaptation (CVPR’18) [dassl/engine/da/mcd.py]
    • Self-ensembling for visual domain adaptation (ICLR’18) [dassl/engine/da/self_ensembling.py]
    • Revisiting Batch Normalization For Practical Domain Adaptation (ICLR-W’17) [dassl/engine/da/adabn.py]
    • Adversarial Discriminative Domain Adaptation (CVPR’17) [dassl/engine/da/adda.py]
    • Domain-Adversarial Training of Neural Networks (JMLR’16) [dassl/engine/da/dann.py]
  • Multi-source domain adaptation

    • Domain Aadaptive Ensemble Learning [dassl/engine/da/dael.py]
    • Moment Matching for Multi-Source Domain Adaptation (ICCV’19) [dassl/engine/da/m3sda.py]
  • Domain generalization

    • Dynamic Domain Generalization (IJCAI’22) [dassl/modeling/backbone/resnet_dynamic.py] [dassl/engine/dg/domain_mix.py]
    • Exact Feature Distribution Matching for Arbitrary Style Transfer and Domain Generalization (CVPR’22) [dassl/modeling/ops/efdmix.py]
    • Domain Generalization with MixStyle (ICLR’21) [dassl/modeling/ops/mixstyle.py]
    • Deep Domain-Adversarial Image Generation for Domain Generalisation (AAAI’20) [dassl/engine/dg/ddaig.py]
    • Generalizing Across Domains via Cross-Gradient Training (ICLR’18) [dassl/engine/dg/crossgrad.py]
  • Semi-supervised learning

    • FixMatch: Simplifying Semi-Supervised Learning with Consistency and Confidence [dassl/engine/ssl/fixmatch.py]
    • MixMatch: A Holistic Approach to Semi-Supervised Learning (NeurIPS’19) [dassl/engine/ssl/mixmatch.py]
    • Mean teachers are better role models: Weight-averaged consistency targets improve semi-supervised deep learning results (NeurIPS’17) [dassl/engine/ssl/mean_teacher.py]
    • Semi-supervised Learning by Entropy Minimization (NeurIPS’04) [dassl/engine/ssl/entmin.py]

Feel free to make a PR to add your methods here to make it easier for others to benchmark!

Dassl supports the following datasets:

  • Domain adaptation

    • Office-31
    • Office-Home
    • VisDA17
    • CIFAR10-STL10
    • Digit-5
    • DomainNet
    • miniDomainNet
  • Domain generalization

    • PACS
    • VLCS
    • Office-Home
    • Digits-DG
    • Digit-Single
    • CIFAR-10-C
    • CIFAR-100-C
    • iWildCam-WILDS
    • Camelyon17-WILDS
    • FMoW-WILDS
  • Semi-supervised learning

    • CIFAR10/100
    • SVHN
    • STL10

Get started

Installation

Make sure conda is installed properly.

# Clone this repo
git clone https://github.com/KaiyangZhou/Dassl.pytorch.git
cd Dassl.pytorch/

# Create a conda environment
conda create -y -n dassl python=3.8

# Activate the environment
conda activate dassl

# Install torch (requires version >= 1.8.1) and torchvision
# Please refer to https://pytorch.org/ if you need a different cuda version
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch

# Install dependencies
pip install -r requirements.txt

# Install this library (no need to re-build if the source code is modified)
python setup.py develop

Follow the instructions in DATASETS.md to preprocess the datasets.

Training

The main interface is implemented in tools/train.py, which basically does

  1. initialize the config with cfg = setup_cfg(args) where args contains the command-line input (see tools/train.py for the list of input arguments);
  2. instantiate a trainer with build_trainer(cfg) which loads the dataset and builds a deep neural network model;
  3. call trainer.train() for training and evaluating the model.

Below we provide an example for training a source-only baseline on the popular domain adaptation dataset, Office-31,

CUDA_VISIBLE_DEVICES=0 python tools/train.py \
--root $DATA \
--trainer SourceOnly \
--source-domains amazon \
--target-domains webcam \
--dataset-config-file configs/datasets/da/office31.yaml \
--config-file configs/trainers/da/source_only/office31.yaml \
--output-dir output/source_only_office31

$DATA denotes the location where datasets are installed. --dataset-config-file loads the common setting for the dataset (Office-31 in this case) such as image size and model architecture. --config-file loads the algorithm-specific setting such as hyper-parameters and optimization parameters.

To use multiple sources, namely the multi-source domain adaptation task, one just needs to add more sources to --source-domains. For instance, to train a source-only baseline on miniDomainNet, one can do

CUDA_VISIBLE_DEVICES=0 python tools/train.py \
--root $DATA \
--trainer SourceOnly \
--source-domains clipart painting real \
--target-domains sketch \
--dataset-config-file configs/datasets/da/mini_domainnet.yaml \
--config-file configs/trainers/da/source_only/mini_domainnet.yaml \
--output-dir output/source_only_minidn

After the training finishes, the model weights will be saved under the specified output directory, along with a log file and a tensorboard file for visualization.

To print out the results saved in the log file (so you do not need to exhaustively go through all log files and calculate the mean/std by yourself), you can use tools/parse_test_res.py. The instruction can be found in the code.

For other trainers such as MCD, you can set --trainer MCD while keeping the config file unchanged, i.e. using the same training parameters as SourceOnly (in the simplest case). To modify the hyper-parameters in MCD, like N_STEP_F (number of steps to update the feature extractor), you can append TRAINER.MCD.N_STEP_F 4 to the existing input arguments (otherwise the default value will be used). Alternatively, you can create a new .yaml config file to store your custom setting. See here for a complete list of algorithm-specific hyper-parameters.

Test

Model testing can be done by using --eval-only, which asks the code to run trainer.test(). You also need to provide the trained model and specify which model file (i.e. saved at which epoch) to use. For example, to use model.pth.tar-20 saved at output/source_only_office31/model, you can do

CUDA_VISIBLE_DEVICES=0 python tools/train.py \
--root $DATA \
--trainer SourceOnly \
--source-domains amazon \
--target-domains webcam \
--dataset-config-file configs/datasets/da/office31.yaml \
--config-file configs/trainers/da/source_only/office31.yaml \
--output-dir output/source_only_office31_test \
--eval-only \
--model-dir output/source_only_office31 \
--load-epoch 20

Note that --model-dir takes as input the directory path which was specified in --output-dir in the training stage.

Write a new trainer

A good practice is to go through dassl/engine/trainer.py to get familar with the base trainer classes, which provide generic functions and training loops. To write a trainer class for domain adaptation or semi-supervised learning, the new class can subclass TrainerXU. For domain generalization, the new class can subclass TrainerX. In particular, TrainerXU and TrainerX mainly differ in whether using a data loader for unlabeled data. With the base classes, a new trainer may only need to implement the forward_backward() method, which performs loss computation and model update. See dassl/enigne/da/source_only.py for example.

Add a new backbone/head/network

backbone corresponds to a convolutional neural network model which performs feature extraction. head (which is an optional module) is mounted on top of backbone for further processing, which can be, for example, a MLP. backbone and head are basic building blocks for constructing a SimpleNet() (see dassl/engine/trainer.py) which serves as the primary model for a task. network contains custom neural network models, such as an image generator.

To add a new module, namely a backbone/head/network, you need to first register the module using the corresponding registry, i.e. BACKBONE_REGISTRY for backbone, HEAD_REGISTRY for head and NETWORK_RESIGTRY for network. Note that for a new backbone, we require the model to subclass Backbone as defined in dassl/modeling/backbone/backbone.py and specify the self._out_features attribute.

We provide an example below for how to add a new backbone.

from dassl.modeling import Backbone, BACKBONE_REGISTRY

class MyBackbone(Backbone):

    def __init__(self):
        super().__init__()
        # Create layers
        self.conv = ...

        self._out_features = 2048

    def forward(self, x):
        # Extract and return features

@BACKBONE_REGISTRY.register()
def my_backbone(**kwargs):
    return MyBackbone()

Then, you can set MODEL.BACKBONE.NAME to my_backbone to use your own architecture. For more details, please refer to the source code in dassl/modeling.

Add a dataset

An example code structure is shown below. Make sure you subclass DatasetBase and register the dataset with @DATASET_REGISTRY.register(). All you need is to load train_x, train_u (optional), val (optional) and test, among which train_u and val could be None or simply ignored. Each of these variables contains a list of Datum objects. A Datum object (implemented here) contains information for a single image, like impath (string) and label (int).

from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase

@DATASET_REGISTRY.register()
class NewDataset(DatasetBase):

    dataset_dir = ''

    def __init__(self, cfg):
        
        train_x = ...
        train_u = ...  # optional, can be None
        val = ...  # optional, can be None
        test = ...

        super().__init__(train_x=train_x, train_u=train_u, val=val, test=test)

We suggest you take a look at the datasets code in some projects like this, which is built on top of Dassl.

Relevant Research

We would like to share here our research relevant to Dassl.

  • On-Device Domain Generalization
  • Domain Generalization: A Survey (TPAMI 2022)
  • Domain Adaptive Ensemble Learning (TIP 2021)
  • MixStyle Neural Networks for Domain Generalization and Adaptation
  • Semi-Supervised Domain Generalization with Stochastic StyleMatch
  • Domain Generalization with MixStyle (ICLR 2021)
  • Learning to Generate Novel Domains for Domain Generalization (ECCV 2020)
  • Deep Domain-Adversarial Image Generation for Domain Generalisation (AAAI 2020)

Citation

If you find this code useful to your research, please give credit to the following paper

@article{zhou2022domain,
  title={Domain generalization: A survey},
  author={Zhou, Kaiyang and Liu, Ziwei and Qiao, Yu and Xiang, Tao and Loy, Chen Change},
  journal={IEEE Transactions on Pattern Analysis and Machine Intelligence},
  year={2022},
  publisher={IEEE}
}

@article{zhou2021domain,
  title={Domain adaptive ensemble learning},
  author={Zhou, Kaiyang and Yang, Yongxin and Qiao, Yu and Xiang, Tao},
  journal={IEEE Transactions on Image Processing},
  volume={30},
  pages={8008--8018},
  year={2021},
  publisher={IEEE}
}

评论

登录 后发表评论
暂无评论
GitRead 中文社区
深度解读 · 趋势洞察 · 价值精选

关于

关于我们联系我们编辑准则收录标准赞赏人员

发现

技术趋势新手训练营资源精选实战指南精选专题热门话题GitHub 文档

条款

隐私政策服务条款网站地图
26.9万收录项目
5.1万中文话题
155精选专题
发现技术价值,连接开源智慧
© 2026 GitRead · GitHub 中文社区 本站与 GitHub, Inc. 无隶属关系;GitHub 是 GitHub, Inc. 的商标。