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

相关推荐
小和尚同志32 分钟前
1.8k star 的开源 token 使用量监控神器— TokenTracker
人工智能·ai编程
极客 - L U2 小时前
神经网络 - 激活函数、损失函数、优化器
人工智能·深度学习·神经网络
数字融合2 小时前
透明化视频三维矿山井下照明重建技术
人工智能·python·数码相机
yi0112 小时前
LeetCode 219:存在重复元素 II——哈希表记录“最近一次出现的位置”
数据结构·人工智能·笔记·python·算法·leetcode·哈希表
xiangzhihong82 小时前
创之星花店多端业务闭环拆解
人工智能
奈落243 小时前
AI 编程从助手到 Agent:基于两份资料看哪些环节可以交出去,哪些必须自己攥住
大数据·人工智能
Joker可视化开发平台3 小时前
AI短剧接棒真人剧:开机量跌七成,普通人进场窗口在收窄
大数据·人工智能
澳鹏Appen3 小时前
澳鹏电子书 | 强化学习环境:为AI智能体打造高保真训练场
人工智能
吴佳浩3 小时前
单卡5090跑125B 大模型:Strata 把服务器级 MoE 拉进普通 PC
人工智能
Data-Miner3 小时前
AI做表格软件哪个好?专业评测:五维对比看清差距
人工智能