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

相关推荐
夏洛克信徒11 分钟前
从 “工具” 到 “代理”:Gemini 3.0 重构 AI 能力边界,开启智能协作新纪元
大数据·人工智能·神经网络
AI浩18 分钟前
回归基础:让去噪生成模型真正去噪
人工智能·数据挖掘·回归
ekprada37 分钟前
DAY 16 数组的常见操作和形状
人工智能·python·机器学习
用户51914958484544 分钟前
C#扩展成员全面解析:从方法到属性的演进
人工智能·aigc
柳鲲鹏1 小时前
OpenCV: 光流法python代码
人工智能·python·opencv
金融小师妹1 小时前
基于LSTM-GARCH模型:三轮黄金周期特征提取与多因子定价机制解构
人工智能·深度学习·1024程序员节
小蜜蜂爱编程1 小时前
深度学习实践 - 使用卷积神经网络的手写数字识别
人工智能·深度学习·cnn
leiming61 小时前
深度学习日记2025.11.20
人工智能·深度学习
速易达网络1 小时前
tensorflow+yolo图片训练和图片识别系统
人工智能·python·tensorflow
智元视界1 小时前
从算法到城市智能:AI在马来西亚智慧城市建设中的系统应用
人工智能·科技·智慧城市·数字化转型·产业升级