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

相关推荐
敖老师6 分钟前
Dify 连局域网 Ollama 的两个坑:docker0 网段撞车,和请求里少掉的那个参数
人工智能
MocMoc23 分钟前
从 0 到 1:把 Dify Chatflow 接进一个 qiankun 中后台
人工智能
民乐团扒谱机41 分钟前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
怎么全是重名1 小时前
VerdictAD
人工智能·异常检测·few-shot·zsas·异常分割
Bode_20021 小时前
具身智能机构设计的质量控制
人工智能
阿里云大数据AI技术2 小时前
EMR Serverless StarRocks × Lance:多模态分析与检索的云上实践
人工智能
SelectDB2 小时前
数据不能出境的数仓选型与迁移落地:四问框架、可复算成本与迁移三段式
人工智能
李青菜2 小时前
一个人 + AI,用 Tauri 2 和 Rust 写了个开源的 Windows 效率工具:提醒 + 笔记 + 启动器
人工智能
泯泷2 小时前
做 AI 产品,路线图该数“实验”,而不是数“功能”
人工智能·llm·产品