PyTorch Lightning快速学习教程三:迁移学习

介绍:本期介绍Lightning的迁移学习

一、使用预训练的LightningModule

使用AutoEncoder作为特征提取器,同时其也作为模型的一部分

python 复制代码
class Encoder(torch.nn.Module):
    ...

class AutoEncoder(LightningModule):
    def __init__(self):
        self.encoder = Encoder()
        self.decoder = Decoder()

class CIFAR10Classifier(LightningModule):
    def __init__(self):
        # 初始化预训练权重
        self.feature_extractor = AutoEncoder.load_from_checkpoint(PATH)
        self.feature_extractor.freeze()

        # 输出是CIFAR10分类
        self.classifier = nn.Linear(100, 10)

    def forward(self, x):
        representations = self.feature_extractor(x)
        x = self.classifier(representations)
        ...

通过上述方法来实现迁移学习

栗子1:ImageNet(计算机视觉)

python 复制代码
import torchvision.models as models

class ImagenetTransferLearning(LightningModule):
    def __init__(self):
        super().__init__()

        # 初始化一个预训练好的resnet50
        backbone = models.resnet50(weights="DEFAULT")
        num_filters = backbone.fc.in_features
        layers = list(backbone.children())[:-1]
        self.feature_extractor = nn.Sequential(*layers)

        # 使用预训练模型对CIFAR10进行分类,用的是ImageNet的权重
        num_target_classes = 10
        self.classifier = nn.Linear(num_filters, num_target_classes)

    def forward(self, x):
        self.feature_extractor.eval()
        with torch.no_grad():
            representations = self.feature_extractor(x).flatten(1)
        x = self.classifier(representations)
        ...

Finetune(微调),进行训练

python 复制代码
model = ImagenetTransferLearning()
trainer = Trainer()
trainer.fit(model)

进行预测

python 复制代码
model = ImagenetTransferLearning.load_from_checkpoint(PATH)
model.freeze()

x = some_images_from_cifar10()
predictions = model(x)

imagenet的预训练模型,在CIFAR10上进行微调,以在CIFAR10上进行预测。在非学术领域,一般会对小数据集进行微调,并对数据集进行预测。一个意思。

栗子2:BERT(自然语言处理)

推荐一个transformer的git:hugging face

python 复制代码
class BertMNLIFinetuner(LightningModule):
    def __init__(self):
        super().__init__()

        self.bert = BertModel.from_pretrained("bert-base-cased", output_attentions=True)
        self.W = nn.Linear(bert.config.hidden_size, 3)
        self.num_classes = 3

    def forward(self, input_ids, attention_mask, token_type_ids):
        h, _, attn = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)

        h_cls = h[:, 0]
        logits = self.W(h_cls)
        return logits, attn
相关推荐
MartinYeung53 分钟前
[论文学习]谄媚研究者驱动表演性错位:大语言模型“对齐伪装”成因的颠复性实证研究
人工智能·学习·语言模型
red_redemption10 分钟前
自由学习记录(222)
学习
鱼很腾apoc25 分钟前
【Linux】第13期 详解应用层协议HTTP+Cookie/Session+HTTPS
linux·服务器·c++·学习·http·https
Lee_jerome28 分钟前
python神经网络编程入门(四十四)——微调预训练 BERT 做下游任务
微调·bert·迁移学习·文本分类·预训练·小样本·冻结特征
web行路人1 小时前
AI 全栈学习之旅 - Week4:容器化部署与生产环境实战
python·学习
翻身的咸鱼ing1 小时前
ArkTS 学习笔记
笔记·学习
程序猿炎义1 小时前
【llm-algo-leetcode学习笔记】训练侧显存优化
人工智能·笔记·学习
动词ing1 小时前
【学习笔记】数据结构(数组滑动窗口+无重复字符的最长字串题目)
数据结构·笔记·学习
田径他爸来了2 小时前
嵌入式学习第32天(同时多个用户访问的服务器)
运维·服务器·学习
骐骥12 小时前
学习:Webview的runJavaScript和runJavaScriptExt有什么区别
学习·鸿蒙