Transformers-Tutorials README

项目的 README,来自 github.com/NielsRogge/Transformers-Tutorials。合并为一个 markdown 文件:README.md。

Transformers-Tutorials

Hi there!

This repository contains demos I made with the Transformers library by 🤗 HuggingFace. Currently, all of them are implemented in PyTorch.

NOTE: if you are not familiar with HuggingFace and/or Transformers, I highly recommend to check out our free course, which introduces you to several Transformer architectures (such as BERT, GPT-2, T5, BART, etc.), as well as an overview of the HuggingFace libraries, including Transformers, Tokenizers, Datasets, Accelerate and the hub.

For an overview of the ecosystem of HuggingFace for computer vision (June 2022), refer to this notebook with corresponding video.

Currently, it contains the following demos:

... more to come! 🤗

If you have any questions regarding these demos, feel free to open an issue on this repository.

Btw, I was also the main contributor to add the following algorithms to the library:

All of them were an incredible learning experience. I can recommend anyone to contribute an AI algorithm to the library!

Data preprocessing

Regarding preparing your data for a PyTorch model, there are a few options:

from torch.utils.data import Dataset

class CustomTrainDataset(Dataset):
    def __init__(self, df, tokenizer):
        self.df = df
        self.tokenizer = tokenizer

    def __len__(self):
        return len(self.df)

    def __getitem__(self, idx):
        # get item
        item = df.iloc[idx]
        text = item['text']
        label = item['label']
        # encode text
        encoding = self.tokenizer(text, padding="max_length", max_length=128, truncation=True, return_tensors="pt")
        # remove batch dimension which the tokenizer automatically adds
        encoding = {k:v.squeeze() for k,v in encoding.items()}
        # add label
        encoding["label"] = torch.tensor(label)
        
        return encoding

Instantiating the dataset then happens as follows:

from transformers import BertTokenizer
import pandas as pd

tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
df = pd.read_csv("path_to_your_csv")

train_dataset = CustomTrainDataset(df=df, tokenizer=tokenizer)

Accessing the first example of the dataset can then be done as follows:

encoding = train_dataset[0]

In practice, one creates a corresponding DataLoader, that allows to get batches from the dataset:

from torch.utils.data import DataLoader

train_dataloader = DataLoader(train_dataset, batch_size=4, shuffle=True)

I often check whether the data is created correctly by fetching the first batch from the data loader, and then printing out the shapes of the tensors, decoding the input_ids back to text, etc.

batch = next(iter(train_dataloader))
for k,v in batch.items():
    print(k, v.shape)
# decode the input_ids of the first example of the batch
print(tokenizer.decode(batch['input_ids'][0].tolist())

Loading a custom dataset as a Dataset object can be done as follows (you can install datasets using pip install datasets):

from datasets import load_dataset

dataset = load_dataset('csv', data_files={'train': ['my_train_file_1.csv', 'my_train_file_2.csv'] 'test': 'my_test_file.csv'})

Here I'm loading local CSV files, but there are other formats supported (including JSON, Parquet, txt) as well as loading data from a local Pandas dataframe or dictionary for instance. You can check out the docs for all details.

Training frameworks

Regarding fine-tuning Transformer models (or more generally, PyTorch models), there are a few options:

import torch
from transformers import BertForSequenceClassification

# Instantiate pre-trained BERT model with randomly initialized classification head
model = BertForSequenceClassification.from_pretrained("bert-base-uncased")

# I almost always use a learning rate of 5e-5 when fine-tuning Transformer based models
optimizer = torch.optim.Adam(model.parameters(), lr=5e-5)

# put model on GPU, if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

for epoch in range(epochs):
    model.train()
    train_loss = 0.0
    for batch in train_dataloader:
        # put batch on device
        batch = {k:v.to(device) for k,v in batch.items()}
        
        # forward pass
        outputs = model(**batch)
        loss = outputs.loss
        
        train_loss += loss.item()
        
        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

    print("Loss after epoch {epoch}:", train_loss/len(train_dataloader))
    
    model.eval()
    val_loss = 0.0
    with torch.no_grad():
        for batch in eval_dataloader:
            # put batch on device
            batch = {k:v.to(device) for k,v in batch.items()}
            
            # forward pass
            outputs = model(**batch)
            loss = outputs.logits
            
            val_loss += loss.item()
                  
    print("Validation loss after epoch {epoch}:", val_loss/len(eval_dataloader))

Citation

Feel free to cite me when you use some of my tutorials :)

@misc{rogge2025transformerstutorials,
  author = {Rogge, Niels},
  title = {Tutorials},
  url = {[https://github.com/NielsRogge/tutorials](https://github.com/NielsRogge/Transformers-Tutorials)},
  year = {2025}
}

Transformers-Tutorials (NielsRogge/Transformers-Tutorials)

正在搜索数据库…

这是什么?这是一组 Jupyter 笔记本演示,展示如何在 PyTorch 中使用 HuggingFace 的 Transformers 库,涵盖 BERT、GPT-2、LayoutLM、DETR、Donut 等众多模型。
这是一个库,还是一组教程?这是一组教程,不是需要安装的库:每个模型都有一个或多个可以直接运行的 Jupyter 笔记本,用来演示推理或微调。
我该如何运行其中的某个笔记本?打开你感兴趣的模型对应的笔记本(大多数都带有 Open In Colab 徽章),直接在 Google Colab 中运行;或者克隆仓库,用 Jupyter 在本地运行。
运行这些笔记本需要先安装什么?需要 Python 和 PyTorch,以及 HuggingFace Transformers 库(某些特定演示还可能需要 PyTorch Lightning 或 Gradio 等额外组件)。
这些笔记本开箱即用,对新手友好吗?如果你刚接触 HuggingFace/Transformers,作者建议先学习他们提供的免费课程(涵盖 BERT、GPT-2、T5 和 BART 等架构),再来看这些演示。
这组教程面向哪些人?面向已经了解一些深度学习、希望通过实际示例学习如何微调或运行特定 Transformer 模型推理的开发者和研究人员。
涵盖了多少个模型?数十个,涉及自然语言处理(BERT、GPT-J、LUKE)、视觉(ViT、DETR、DINO、MaskFormer)、文档 AI(LayoutLM、Donut、MarkupLM)、音频(Audio Spectrogram Transformer)和多模态(GIT、Perceiver IO)等领域。
我能用这些笔记本在自己的数据集上微调模型吗?可以。许多笔记本(例如在 FUNSD 上微调 LayoutLM、在自定义气球数据集上微调 DETR、用 Donut 做文档解析)都是按微调示例组织的,你可以改成适用于自己数据的版本。
有没有涵盖文档理解模型的演示?有。文档 AI 模型的内容很丰富,包括 LayoutLM、LayoutLMv2/v3、LayoutXLM、Donut 和 MarkupLM,可用于表单理解、文档分类和视觉问答等任务。
如果我刚接触 Transformers,应该从哪里开始?先学习 README 中提到的 HuggingFace 免费课程,然后选一个 BERT 或 ViT 等知名模型的笔记本,再去看更专业的架构。
大小
264.3 MB
星标
11.8K
更新
提交Sep 17
时长
6年
提交 · 90 天