使用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 分钟前
Cloud Agent 开发笔记(4):Skill 与 MCP 集成、项目后记
人工智能·prompt
进击的横打9 分钟前
【人工智能】AI基础知识(第七节:RAG)
人工智能
KaMeidebaby12 分钟前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
OpenApi.cc32 分钟前
猫狗分类模型 GPU版
pytorch·深度学习·分类
tmlx3I0811 小时前
高光谱拼接算法(六)RANSAC 误匹配剔除
人工智能·算法·机器学习
Mininglamp_27181 小时前
Claude Code 封禁中国开发者之后:本地 AI 编程工具的替代方案实测
开发语言·人工智能·windows·开源软件·ai-native
硅谷秋水1 小时前
World Engine:迈向自动驾驶的后训练时代
人工智能·深度学习·机器学习·计算机视觉·语言模型·自动驾驶
RobinDevNotes1 小时前
PentAGI:全自主 AI 渗透测试代理系统
人工智能
明理的信封2 小时前
AI 基础设施的“去 Python 化“:Rust 与 C# 的两条替代路径
人工智能·python·rust
优橙教育2 小时前
Rano AI智能体技术架构深度解析
人工智能