pytorch框架下的Finetune 以及ResNet50 代码

 

  1.  Resnet 50
# -*- coding: utf-8 -*-

import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo


class residual_block(nn.Module):
    expansion = 4
    def __init__(self, inplanes, planes, stride=1, downsample = None):
        super(residual_block, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes,  bias=False, kernel_size=1)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, stride = stride, kernel_size=3 , padding=1, bias = False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes*4,  kernel_size=1,bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride


    def forward(self, x):
        residual = x

        conv1 = self.conv1(x)
        bn1 = self.bn1(conv1)
        relu1 = self.relu(bn1)

        conv2 = self.conv2(relu1)
        bn2 = self.bn2(conv2)
        relu2 = self.relu(bn2)

        conv3 = self.conv3(relu2)
        bn3 = self.bn3(conv3)
        if self.downsample is not None:
            residual = self.downsample(x)
        bn3 += residual
        out = self.relu(bn3)

        return out





class Resnet(nn.Module):
    def __init__(self,  layers, numclass):
        self.inplanes = 64
        super(Resnet, self).__init__() ## super函数是用于调用父类(超类)的一个方法
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=64, kernel_size=7, stride=2,
                               padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(num_features=64)
        self.relu = nn.ReLU(inplace=True)   ##inplace为True,将会改变输入的数据 ,否则不会改变原输入,只会产生新的输出
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(residual_block, 64, blocks = layers[0], stride=1)
        self.layer2 = self._make_layer(residual_block, 128, blocks = layers[1], stride=2)
        self.layer3 = self._make_layer(residual_block, 256, blocks = layers[2], stride=2)
        self.layer4 = self._make_layer(residual_block, 512, blocks = layers[3], stride=2)
        
### 使用 ResNet50 进行预测的方法 #### PyTorch 实现 ResNet50 预测 在 PyTorch 中,可以利用 `torchvision.models` 提供的预训练 ResNet50 模型进行预测。为了确保预测结果准确,输入数据的预处理方式应与模型训练时保持一致。 以下是完整的实现过程: 1. **加载预训练模型** 利用 `torchvision.models.resnet50(pretrained=True)` 加载已训练好的 ResNet50 模型[^1]。 2. **定义图像预处理流程** 所有 torchvision 的模型均采用相同的标准化参数:均值 `[0.485, 0.456, 0.406]` 和标准差 `[0.229, 0.224, 0.225]`。这些参数需用于测试集的数据预处理。 3. **执行推理操作** 将经过预处理的图片张量传递给模型并提取其分类概率。 ```python import torch from torchvision import models, transforms from PIL import Image import json # 定义预处理变换 preprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) # 加载预训练模型 model = models.resnet50(pretrained=True) model.eval() # 设置为评估模式 # 图片路径 image_path = 'example.jpg' # 加载并预处理图片 img = Image.open(image_path).convert('RGB') input_tensor = preprocess(img) input_batch = input_tensor.unsqueeze(0) # 添加 batch 维度 # 推理阶段 with torch.no_grad(): output = model(input_batch) # 获取类别名称映射表 with open("imagenet_class_index.json") as f: class_idx = json.load(f) idx2label = [class_idx[str(k)][1] for k in range(len(class_idx))] # 输出最高概率对应的类别名 _, index = torch.max(output, 1) percentage = torch.nn.functional.softmax(output, dim=1)[0] * 100 print(idx2label[index[0]], percentage[index[0]].item()) ``` --- #### TensorFlow/Keras 实现 ResNet50 预测 在 Keras/TensorFlow 中,可以通过 `keras.applications.ResNet50` 轻松加载预训练模型,并使用内置的 `preprocess_input` 函数完成数据预处理。 具体步骤如下: 1. **导入必要的库** 2. **加载预训练模型** 3. **准备输入数据** ```python import numpy as np from tensorflow.keras.applications.resnet50 import ResNet50, decode_predictions, preprocess_input from tensorflow.keras.preprocessing import image # 加载预训练模型 model = ResNet50(weights='imagenet') # 加载并预处理图片 img_path = 'example.jpg' img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) # 推理阶段 preds = model.predict(x) decoded_preds = decode_predictions(preds, top=3)[0] for _, label, prob in decoded_preds: print(f"{label}: {prob:.2f}") ``` 上述代码会返回前三个最可能的类别及其对应的概率。 --- ### 注意事项 - 输入数据的尺寸必须匹配模型的要求(通常为 `(224, 224, 3)`),并且需要通过特定的方式进行归一化和标准化。 - 如果自定义了新的数据集,则需要重新微调 (fine-tune) 或迁移学习来适应新任务的需求[^2]。 ---
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值