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

相关推荐
xinlianyq25 分钟前
2026企业流量破局:四大主流短视频矩阵获客系统深度解析与选型指南
人工智能·矩阵
workflower2 小时前
用硬件换时间”与“用算法降成本”之间的博弈
人工智能·算法·安全·集成测试·无人机·ai编程
Cx330❀2 小时前
一文吃透Linux System V共享内存:原理+实操+避坑指南
大数据·linux·运维·服务器·人工智能
OPHKVPS2 小时前
Anthropic 为 Claude Code 推出“自动模式”:AI 编码工具迈向更高自主性
网络·人工智能·安全·ai
Allen_LVyingbo2 小时前
斯坦福HAI官网完整版《2025 AI Index Report》全面解读
人工智能·数学建模·开源·云计算·知识图谱
金融小师妹2 小时前
基于AI通胀预期建模与能源冲击传导机制的政策分析:高频信号下的风险再评估
人工智能·svn·能源
胡摩西2 小时前
当大模型遇上毫米级定位:机器人将拥有“空间思维”?
人工智能·机器人·slam·gps·室内定位·roomaps
志栋智能2 小时前
超自动化运维的终极目标:让系统自治运行
运维·网络·人工智能·安全·自动化
彬鸿科技3 小时前
bhSDR Studio/Matlab入门指南(九):FMCW雷达测距实验界面全解析
人工智能·matlab·软件定义无线电
补三补四3 小时前
Prompt工程实践指南:从基础概念到高级应用
人工智能·chatgpt·prompt