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
相关推荐
程序猿追5 小时前
HarmonyOS 7 ArkUI 卡片点击分发:点关闭按钮,怎样确保只收起推荐
pytorch·深度学习·harmonyos
kitsch0x975 小时前
技术学习_Cowrie 蜜罐的响应机制
学习
kyrie_sakura6 小时前
大模型学习32 --大模型微调3 -- 分布式训练算法
分布式·学习·算法
xwz小王子6 小时前
Nature Custom Media 从手术台到厨房:下一代医疗机器人,正在学习“什么时候该放手”
人工智能·学习·机器人
Rabitebla7 小时前
【Linux】 文件系统(五):挂载与软硬链接,多个文件系统怎样组成统一目录树
linux·运维·服务器·c++·笔记·学习·算法
叼烟扛炮12 小时前
[LangGraph] 学习笔记(047):Pydantic 写的 State 也不校验,并行分支还互相看不见
笔记·学习
qq_2744751512 小时前
第 16 篇:类型检测方案汇总:typeof、instanceof、Object.prototype.toString、手写 isType
javascript·学习·原型模式
Brain 博览记13 小时前
给吗啡类镇痛药装上“光开关”:照一下开、再照一下关——Cell 冷冻电镜解析阿片效价切换
开发语言·网络·论文阅读·学习·php
Answer1st13 小时前
【FPGA学习】VSCode 写 Verilog 操作指南(XII)
vscode·学习·fpga开发
Nerd(BUG版)14 小时前
KMP学习day15--Compose副作用与动画
学习·kotlin·kmp