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

相关推荐
七夜zippoe6 分钟前
图神经网络实战:从社交网络到推荐系统的工业级应用
网络·人工智能·pytorch·python·神经网络·cora
啊阿狸不会拉杆7 分钟前
《计算机视觉:模型、学习和推理》第 1 章 - 绪论
人工智能·python·学习·算法·机器学习·计算机视觉·模型
X54先生(人文科技)8 分钟前
叙事响应:《当预言泛起涟漪——碳硅智能时代的叙事开篇》
人工智能·ai编程·ai写作
硅谷秋水19 分钟前
具身智能中的生成多智体协作:系统性综述
人工智能·深度学习·机器学习·语言模型·机器人
爱吃羊的老虎26 分钟前
【大模型应用】MCP (Model Context Protocol):AI界的USB接口
人工智能
本是少年29 分钟前
构建 HuggingFace 图像-文本数据集指南
pytorch·transformer
Testopia32 分钟前
垃圾分类识别:迁移学习在环保领域的应用
分类·数据挖掘·ai编程·迁移学习·#人工智能学习
用户51914958484532 分钟前
curl中的TFTP实现:整数下溢导致堆内存越界读取漏洞
人工智能·aigc
老赵全栈实战34 分钟前
《从零搭建RAG系统第5天:安装Ollama》
人工智能
星爷AG I40 分钟前
12-4 表情识别(AGI基础理论)
人工智能·agi