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
相关推荐
百锦再1 分钟前
破茧成蝶:全方位解析Java学习难点与征服之路
java·python·学习·struts·kafka·maven·intellij-idea
雨奔2 分钟前
Django 学习路线图
学习·django·sqlite
冷崖1 小时前
MySQL-TrinityCore异步连接池的学习(七)
学习·mysql
pen-ai2 小时前
标签噪声学习:理论与方法详解
学习
Summer_Uncle3 小时前
【C++学习】指针
c++·学习
光影少年4 小时前
AIGG人工智能生态及学习路线和应用领域
人工智能·学习
递归不收敛4 小时前
多模态学习大纲笔记(未完成)
人工智能·笔记·学习·自然语言处理
FPGA-李宇航5 小时前
FPGA中,“按键控制LED灯实验”学习中常见问题、解决思路和措施以及经验总结!!!(新手必看)
学习·fpga开发·按键控制led灯
正经教主6 小时前
【Trae+AI】和Trae学习搭建App_01:项目架构设计与环境搭建
学习·app
普蓝机器人6 小时前
面向智慧农业的自主移动果蔬采摘机器人:融合视觉识别与自动驾驶的智能化农作系统研究
人工智能·学习·机器人·移动机器人·三维仿真导航