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

相关推荐
搞科研的小刘选手2 分钟前
【ISSN/ISBN双刊号】第三届电力电子与人工智能国际学术会议(PEAI 2026)
图像处理·人工智能·算法·电力电子·学术会议
wumingxiaoyao2 分钟前
AI - 使用 Google ADK 创建你的第一个 AI Agent
人工智能·ai·ai agent·google adk
拉姆哥的小屋4 分钟前
从混沌到秩序:条件扩散模型在图像转换中的哲学与技术革命
人工智能·算法·机器学习
Sammyyyyy9 分钟前
DeepSeek v3.2 正式发布,对标 GPT-5
开发语言·人工智能·gpt·算法·servbay
JoannaJuanCV37 分钟前
自动驾驶—CARLA仿真(6)vehicle_gallery demo
人工智能·机器学习·自动驾驶·carla
Hundred billion1 小时前
深度学习基本原理和流程
人工智能·深度学习
周杰伦_Jay1 小时前
【大模型数据标注】核心技术与优秀开源框架
人工智能·机器学习·eureka·开源·github
Jay20021111 小时前
【机器学习】33 强化学习 - 连续状态空间(DQN算法)
人工智能·算法·机器学习
Learn Forever1 小时前
由ChatGPT 的记忆系统谈及如何构建一个对话应用智能体
人工智能
资深低代码开发平台专家1 小时前
GPT-5.2与Gemini 3.0终极抉择:谁更适配你的需求?
人工智能·gpt·ai