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

相关推荐
凯子坚持 c37 分钟前
从 0 到 1:ComfyUI AI 工作流抠图构建全实践
大数据·人工智能
背太阳的牧羊人2 小时前
OpenAI Embedding 和密集检索(如 BERT/DPR)进行语义相似度搜索有什么区别和联系
人工智能·bert·embedding
光与电子KOYUELEC加油奋斗3 小时前
Molex莫仕连接器:增强高级驾驶辅助系统,打造更安全的汽车
人工智能·光与电子
__lost5 小时前
MATLAB画出3d的常见复杂有机分子和矿物的分子结构
开发语言·人工智能·matlab·化学·分子结构
每天都要写算法(努力版)5 小时前
【神经网络与深度学习】五折交叉验证(5-Fold Cross-Validation)
人工智能·深度学习·神经网络
郭不耐5 小时前
DeepSeek智能时空数据分析(六):大模型NL2SQL绘制城市之间连线
人工智能·数据分析·时序数据库·数据可视化·deepseek
winfredzhang6 小时前
Deepseek 生成新玩法:从文本到可下载 Word 文档?思路与实践
人工智能·word·deepseek
KY_chenzhao6 小时前
ChatGPT与DeepSeek在科研论文撰写中的整体科研流程与案例解析
人工智能·机器学习·chatgpt·论文·科研·deepseek
不爱吃于先生7 小时前
生成对抗网络(Generative Adversarial Nets,GAN)
人工智能·神经网络·生成对抗网络
cxr8287 小时前
基于Playwright的浏览器自动化MCP服务
人工智能·自动化·大语言模型·mcp