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

相关推荐
Data-Miner1 分钟前
身份信息敏感数据分析:敏感度分级、数据落点与处理逻辑固化
数据库·人工智能·数据分析
啵啵啵鱼5 分钟前
GitHub Actions 自动化:5 个真实运维提效案例
人工智能
qinglongcn16 分钟前
2026 Agent 记忆安全威胁全景
网络·人工智能·安全·web安全·编辑器·ai编程
ARM+FPGA+AI工业主板定制专家16 分钟前
工业视觉检测:Jetson 整机硬件方案与部署落地总结
人工智能·计算机视觉·视觉检测
鲜于言悠90522 分钟前
2026 GitHub AI开源榜单:冠军换人,Agent技能时代爆发
人工智能
用户23398617957326 分钟前
TypeScript源码解析:系统提示词组装管线
人工智能
数据世界128 分钟前
医院、零售、电商三端销售数据如何放进同一体系?分层抽样放大模型的分立与统一
大数据·数据库·人工智能
user44651179179128 分钟前
拆解 AgentScope Agent 运行时:一次 reply 从输入到结束的完整链路
人工智能
模事在人31 分钟前
Agent 效果上不去:先别急着换模型,先量一遍 harness
人工智能