使用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参数

相关推荐
苦猿的大模型日记几秒前
Day40|Agent 实战模块起手——ReAct + 工具 + 记忆,从 0 写一个不靠 LangChain 的 30 行核心 Agent
人工智能
txg6662 分钟前
机器人领域简报(2026年7月20日—27日)
人工智能·microsoft·机器人
AI新角度6 分钟前
开源维护自动化:issue 分类与发布管理的机器人实践
人工智能
AI大模型-小华9 分钟前
Codex 任务中断的真实成本:ChatGPT Plus 与 Pro 应该如何选择?
人工智能·chatgpt·ai编程·codex·chatgpt plus·chatgpt pro
万岳科技系统开发17 分钟前
AI赋能互联网医院小程序开启智慧医疗新时代
人工智能·小程序·apache
蓝狐社18 分钟前
市场不再为AI烧钱故事买单
人工智能
小白199720 分钟前
医疗影像分析与遥感
人工智能
电子科技圈21 分钟前
第二代无线平台历久弥新,赋能物联网创新迭代
人工智能·嵌入式硬件·mcu·物联网·设计模式·硬件架构·iot
东坡肘子29 分钟前
不是模型变慢了,是任务变大了 -- 肘子的 Swift 周报 #146
人工智能·swiftui·swift