torch06:ResNet--Cifar识别和自己数据集

MachineLP的Github(欢迎follow):https://github.com/MachineLP

MachineLP的博客目录:小鹏的博客目录

本小节使用torch搭建ResNet模型,训练和测试:

(1)定义模型超参数:迭代次数、批量大小、学习率。

(2)定义训练数据,加餐部分是使用自己的数据集:(可参考:https://blog.csdn.net/u014365862/article/details/80506147

(3)定义模型(定义残差神经网络)。

(4)定义损失函数,选用适合的损失函数。

(5)定义优化算法(SGD、Adam等)。

(6)保存模型。

---------------------------------我是可爱的分割线---------------------------------

代码部分:

# coding=utf-8
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms


# 判定GPU是否存在
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 定义超参数
num_epochs = 80
learning_rate = 0.001

# 定义数据预处理的方式
transform = transforms.Compose([
    transforms.Pad(4),
    transforms.RandomHorizontalFlip(),
    transforms.RandomCrop(32),
    transforms.ToTensor()])

# CIFAR-10 数据集
train_dataset = torchvision.datasets.CIFAR10(root='./data/',
                                             train=True, 
                                             transform=transform,
                                             download=True)

test_dataset = torchvision.datasets.CIFAR10(root='./data/',
                                            train=False, 
                                            transform=transforms.ToTensor())

# 构建数据管道, 使用自己的数据集请参考:https://blog.csdn.net/u014365862/article/details/80506147 
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=100, 
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=100, 
                                          shuffle=False)

# 3x3 卷积
def conv3x3(in_channels, out_channels, stride=1):
    return nn.Conv2d(in_channels, out_channels, kernel_size=3, 
                     stride=stride, padding=1, bias=False)

# 定义残差块
class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(ResidualBlock, self).__init__()
        self.conv1 = conv3x3(in_channels, out_channels, stride)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(out_channels, out_channels)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.downsample = downsample
        
    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        if self.downsample:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out

# 定义残差网络
class ResNet(nn.Module):
    def __init__(self, block, layers, num_classes=10):
        super(ResNet, self).__init__()
        self.in_channels = 16
        self.conv = conv3x3(3, 16)
        self.bn = nn.BatchNorm2d(16)
        self.relu = nn.ReLU(inplace=True)
        self.layer1 = self.make_layer(block, 16, layers[0])
        self.layer2 = self.make_layer(block, 32, layers[0], 2)
        self.layer3 = self.make_layer(block, 64, layers[1], 2)
        self.avg_pool = nn.AvgPool2d(8)
        self.fc = nn.Linear(64, num_classes)
        
    def make_layer(self, block, out_channels, blocks, stride=1):
        downsample = None
        if (stride != 1) or (self.in_channels != out_channels):
            downsample = nn.Sequential(
                conv3x3(self.in_channels, out_channels, stride=stride),
                nn.BatchNorm2d(out_channels))
        layers = []
        layers.append(block(self.in_channels, out_channels, stride, downsample))
        self.in_channels = out_channels
        for i in range(1, blocks):
            layers.append(block(out_channels, out_channels))
        return nn.Sequential(*layers)
    
    def forward(self, x):
        out = self.conv(x)
        out = self.bn(out)
        out = self.relu(out)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.avg_pool(out)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out

# 定义模型    
model = ResNet(ResidualBlock, [2, 2, 2, 2]).to(device)


# 损失函数和优化算法
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# 定义学习率衰减
def update_lr(optimizer, lr):    
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

# 训练模型
total_step = len(train_loader)
curr_lr = learning_rate
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)
        
        # 前向传播+计算loss
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # 后向传播+调整参数
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        # 每100个batch打印一次数据  
        if (i+1) % 100 == 0:
            print ("Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}"
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

    # 学习率衰减
    if (epoch+1) % 20 == 0:
        curr_lr /= 3
        update_lr(optimizer, curr_lr)

# 模型测试部分  
# 测试阶段不需要计算梯度,注意
model.eval()
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the model on the test images: {} %'.format(100 * correct / total))

# 保存模型参数 
torch.save(model.state_dict(), 'resnet.ckpt')

加餐:在自己数据集上使用:

其中,train.txt中的数据格式:

gender/0male/0(2).jpg 1
gender/0male/0(3).jpeg 1
gender/0male/0(1).jpg 0

test.txt中的数据格式如下:

gender/0male/0(3).jpeg 1
gender/0male/0(1).jpg 0

gender/1female/1(6).jpg 1

代码部分:

# coding=utf-8
import torch   
import torch.nn as nn  
import torchvision  
from torch.utils.data import Dataset, DataLoader      
from torchvision import transforms, utils   
from PIL import Image   


# 判定GPU是否存在
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 定义超参数
batch_size = 16
num_epochs = 5
learning_rate = 0.001

def default_loader(path):      
    # 注意要保证每个batch的tensor大小时候一样的。      
    return Image.open(path).convert('RGB')      
      
class MyDataset(Dataset):      
    def __init__(self, txt, transform=None, target_transform=None, loader=default_loader):      
        fh = open(txt, 'r')      
        imgs = []      
        for line in fh:      
            line = line.strip('\n')      
            # line = line.rstrip()      
            words = line.split(' ')      
            imgs.append((words[0],int(words[1])))      
        self.imgs = imgs      
        self.transform = transform      
        self.target_transform = target_transform      
        self.loader = loader      
          
    def __getitem__(self, index):      
        fn, label = self.imgs[index]      
        img = self.loader(fn)      
        if self.transform is not None:      
            img = self.transform(img)      
        return img,label      
          
    def __len__(self):      
        return len(self.imgs)      
      
def get_loader(dataset='train.txt', crop_size=128, image_size=32, batch_size=2, mode='train', num_workers=1):      
    """Build and return a data loader."""      
    transform = []      
    if mode == 'train':      
        transform.append(transforms.RandomHorizontalFlip())      
    transform.append(transforms.CenterCrop(crop_size))      
    transform.append(transforms.Resize(image_size))      
    transform.append(transforms.ToTensor())      
    transform.append(transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)))      
    transform = transforms.Compose(transform)      
    train_data=MyDataset(txt=dataset, transform=transform)      
    data_loader = DataLoader(dataset=train_data,      
                                  batch_size=batch_size,      
                                  shuffle=(mode=='train'),      
                                  num_workers=num_workers)      
    return data_loader      
# 注意要保证每个batch的tensor大小时候一样的。      
# data_loader = DataLoader(train_data, batch_size=2,shuffle=True)      
train_loader = get_loader('train.txt', batch_size=batch_size)      
print(len(train_loader))      
test_loader = get_loader('test.txt', batch_size=batch_size)      
print(len(test_loader))  

# 3x3 卷积
def conv3x3(in_channels, out_channels, stride=1):
    return nn.Conv2d(in_channels, out_channels, kernel_size=3, 
                     stride=stride, padding=1, bias=False)

# 定义残差块
class ResidualBlock(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1, downsample=None):
        super(ResidualBlock, self).__init__()
        self.conv1 = conv3x3(in_channels, out_channels, stride)
        self.bn1 = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(out_channels, out_channels)
        self.bn2 = nn.BatchNorm2d(out_channels)
        self.downsample = downsample
        
    def forward(self, x):
        residual = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        if self.downsample:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out

# 定义残差网络
class ResNet(nn.Module):
    def __init__(self, block, layers, num_classes=10):
        super(ResNet, self).__init__()
        self.in_channels = 16
        self.conv = conv3x3(3, 16)
        self.bn = nn.BatchNorm2d(16)
        self.relu = nn.ReLU(inplace=True)
        self.layer1 = self.make_layer(block, 16, layers[0])
        self.layer2 = self.make_layer(block, 32, layers[0], 2)
        self.layer3 = self.make_layer(block, 64, layers[1], 2)
        self.avg_pool = nn.AvgPool2d(8)
        self.fc = nn.Linear(64, num_classes)
        
    def make_layer(self, block, out_channels, blocks, stride=1):
        downsample = None
        if (stride != 1) or (self.in_channels != out_channels):
            downsample = nn.Sequential(
                conv3x3(self.in_channels, out_channels, stride=stride),
                nn.BatchNorm2d(out_channels))
        layers = []
        layers.append(block(self.in_channels, out_channels, stride, downsample))
        self.in_channels = out_channels
        for i in range(1, blocks):
            layers.append(block(out_channels, out_channels))
        return nn.Sequential(*layers)
    
    def forward(self, x):
        out = self.conv(x)
        out = self.bn(out)
        out = self.relu(out)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.avg_pool(out)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out

# 定义模型    
model = ResNet(ResidualBlock, [2, 2, 2, 2]).to(device)


# 损失函数和优化算法
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# 定义学习率衰减
def update_lr(optimizer, lr):    
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

# 训练模型
total_step = len(train_loader)
curr_lr = learning_rate
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)
        
        # 前向传播+计算loss
        outputs = model(images)
        loss = criterion(outputs, labels)
        
        # 后向传播+调整参数
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        # 每100个batch打印一次数据  
        if (i+1) % 100 == 0:
            print ("Epoch [{}/{}], Step [{}/{}] Loss: {:.4f}"
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

    # 学习率衰减
    if (epoch+1) % 20 == 0:
        curr_lr /= 3
        update_lr(optimizer, curr_lr)

# 模型测试部分  
# 测试阶段不需要计算梯度,注意
model.eval()
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    print('Accuracy of the model on the test images: {} %'.format(100 * correct / total))

# 保存模型参数 
torch.save(model.state_dict(), 'resnet.ckpt')

总结:

本节使用ResNet训练Cifar识别、自己数据的识别。

上面加餐部分需要生成自己的txt文件(数据+标签),可以参考这个,自己以前调试用的:https://github.com/MachineLP/py_workSpace/blob/master/g_img_path.py



ResNet是一种深度学习架构,用于图像分类和识别任务。要使用ResNet训练自己的数据集,你可以按照以下步骤进行操作: 1. 下载ResNet的预训练模型和数据集(例如CIFAR-10)。 2. 创建一个新的神经网络,并加载ResNet的预训练模型。 3. 修改网络的最后一层,将输出类别数修改为自己数据集的类别数。 4. 冻结ResNet前面的参数,只训练新添加的层。 5. 将数据集加载到网络中,并进行数据增强(可选)。 6. 选择GPU或CPU进行训练。 7. 训练网络,并可视化训练过程。 下面是一个示例代码,展示了如何使用ResNet训练自己的数据集: ```python import torch import torch.nn as nn import torchvision.models as models import torchvision.transforms as transforms from torch.utils.data import DataLoader # 下载预训练模型和数据集 resnet = models.resnet50(pretrained=True) dataset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transforms.ToTensor()) # 修改输出类别数 num_classes = 10 resnet.fc = nn.Linear(resnet.fc.in_features, num_classes) # 冻结前面的参数 for param in resnet.parameters(): param.requires_grad = False # 加载数据集 batch_size = 32 data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True) # 选择GPU或CPU device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') resnet = resnet.to(device) # 定义损失函数和优化器 criterion = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(resnet.fc.parameters(), lr=0.001, momentum=0.9) # 训练网络 num_epochs = 10 for epoch in range(num_epochs): for images, labels in data_loader: images = images.to(device) labels = labels.to(device) # 前向传播 outputs = resnet(images) loss = criterion(outputs, labels) # 反向传播和优化 optimizer.zero_grad() loss.backward() optimizer.step() # 可视化训练过程(使用tensorboard等工具) ``` 这是一个基本的示例,你可以根据自己的需求进行修改和扩展。通过这个过程,ResNet可以使用自己的数据集进行训练。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MachineLP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值