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