使用pytorch搭建ResNet并基于迁移学习训练

这里的迁移学习方法是载入预训练权重的方法

python 复制代码
    net = resnet34()
    # load pretrain weights
    # download url: https://download.pytorch.org/models/resnet34-333f7ec4.pth
    model_weight_path = "./resnet34-pre.pth"
    assert os.path.exists(model_weight_path), "file {} does not exist.".format(model_weight_path)
    net.load_state_dict(torch.load(model_weight_path, map_location='cpu'))
    # for param in net.parameters():
    #     param.requires_grad = False

    # change fc layer structure
    in_channel = net.fc.in_features
    net.fc = nn.Linear(in_channel, 5)

这里的迁移学习方法是载入预训练权重的方法net = resnet34():注意这里没有传入参数num_classes 因为后面才载入所有的参数,会覆盖我们设定的classes

change fc layer structure

in_channel = net.fc.in_features # fc 为全连接层 in_features为特征矩阵的深度

net.fc = nn.Linear(in_channel, 5)

如果不想使用迁移学习的方法,则注释阴影部分,在net = resnet34()中传入num_classes参数

相关推荐
明天好,会的15 分钟前
分形生成实验:在有限上下文中构建可组合的强类型单元
人工智能
All The Way North-16 分钟前
从0到1,构建自己的全连接神经网络
人工智能·pytorch·深度学习·全连接神经网络
week_泽17 分钟前
6、OpenCV SURF特征检测笔记
人工智能·笔记·opencv
AI即插即用19 分钟前
即插即用系列 | CVPR 2025 DICMP:基于深度信息辅助的图像去雾与深度估计双任务协同互促网络
图像处理·人工智能·深度学习·神经网络·计算机视觉·视觉检测
Coder_Boy_21 分钟前
基于SpringAI的智能平台基座开发-(五)
java·人工智能·spring boot·langchain·springai
AI即插即用21 分钟前
即插即用系列 | WACV 2024 CSAM:面向各向异性医学图像分割的 2.5D 跨切片注意力模块
图像处理·人工智能·深度学习·神经网络·目标检测·计算机视觉·视觉检测
今夕资源网21 分钟前
仙宫云自动抢算力工具可后台运行,仙宫云自动抢卡,仙宫云自动抢显卡,AI云平台抢算力
人工智能·后台·仙宫云·抢算力·抢显卡·抢gpu
小小工匠22 分钟前
LLM - AgentScope + Mem0 搭建实战可用的 AI Agent 记忆系统
人工智能·mem0·agentscope
LucianaiB23 分钟前
【基于昇腾平台的CodeLlama实践:从环境搭建到高效开发】
运维·人工智能·性能优化
工藤学编程24 分钟前
零基础学AI大模型之LangChain Tool工具
人工智能·langchain