torch07:RNN--MNIST识别和自己数据集

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

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

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

(1)定义模型超参数:rnn的输入,rnn隐含单元,rnn层数,迭代次数、批量大小、学习率。

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

(3)定义模型(定义需要的RNN结构)。

(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')

# 定义超参数
# RNN的输入是一个序列,sequence_length为序列长度,input_size为序列每个长度。
sequence_length = 28
input_size = 28
# 定义RNN隐含单元的大小。
hidden_size = 128
# 定义rnn的层数
num_layers = 2
# 识别的类别数量
num_classes = 10
# 批的大小
batch_size = 100
# 定义迭代次数
num_epochs = 2
# 定义学习率
learning_rate = 0.01

# MNIST 数据集  
train_dataset = torchvision.datasets.MNIST(root='./data/',
                                           train=True, 
                                           transform=transforms.ToTensor(),
                                           download=True)

test_dataset = torchvision.datasets.MNIST(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=batch_size, 
                                           shuffle=True)

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

# 定义RNN(LSTM)
class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, num_classes)
    
    def forward(self, x):
        # Set initial hidden and cell states 
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) 
        c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
        
        # Forward propagate LSTM
        out, _ = self.lstm(x, (h0, c0))  # out: tensor of shape (batch_size, seq_length, hidden_size)
        
        # Decode the hidden state of the last time step
        out = self.fc(out[:, -1, :])
        return out

# 定义模型 
model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)


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

# 训练模型 
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.reshape(-1, sequence_length, input_size).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()))

# 模型测试部分    
# 测试阶段不需要计算梯度,注意  
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, sequence_length, input_size).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('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total)) 

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

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

其中,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')

# 定义超参数
# RNN的输入是一个序列,sequence_length为序列长度,input_size为序列每个长度。
sequence_length = 28*3
input_size = 28
# 定义RNN隐含单元的大小。
hidden_size = 128
# 定义rnn的层数
num_layers = 2
# 识别的类别数量
num_classes = 10
# 批的大小
batch_size = 16
# 定义迭代次数
num_epochs = 2
# 定义学习率
learning_rate = 0.01

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=28, 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))    

# 定义RNN(LSTM)
class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size, num_classes)
    
    def forward(self, x):
        # Set initial hidden and cell states 
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) 
        c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
        
        # Forward propagate LSTM
        out, _ = self.lstm(x, (h0, c0))  # out: tensor of shape (batch_size, seq_length, hidden_size)
        
        # Decode the hidden state of the last time step
        out = self.fc(out[:, -1, :])
        return out

# 定义模型 
model = RNN(input_size, hidden_size, num_layers, num_classes).to(device)


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

# 训练模型 
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.reshape(-1, sequence_length, input_size).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()))

# 模型测试部分    
# 测试阶段不需要计算梯度,注意  
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, sequence_length, input_size).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('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total)) 

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

加餐2:BIRNN

# 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')

# 定义超参数  
# RNN的输入是一个序列,sequence_length为序列长度,input_size为序列每个长度。
sequence_length = 28
input_size = 28
# 定义RNN隐含单元的大小。 
hidden_size = 128
# 定义rnn的层数
num_layers = 2
num_classes = 10
batch_size = 100
num_epochs = 2
learning_rate = 0.003

# MNIST 数据集
train_dataset = torchvision.datasets.MNIST(root='./data/',
                                           train=True, 
                                           transform=transforms.ToTensor(),
                                           download=True)

test_dataset = torchvision.datasets.MNIST(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=batch_size, 
                                           shuffle=True)

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

# 定义RNN(LSTM) 
class BiRNN(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(BiRNN, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True)
        self.fc = nn.Linear(hidden_size*2, num_classes)  # 2 for bidirection
    
    def forward(self, x):
        # Set initial states
        h0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device) # 2 for bidirection 
        c0 = torch.zeros(self.num_layers*2, x.size(0), self.hidden_size).to(device)
        
        # Forward propagate LSTM
        out, _ = self.lstm(x, (h0, c0))  # out: tensor of shape (batch_size, seq_length, hidden_size*2)
        
        # Decode the hidden state of the last time step
        out = self.fc(out[:, -1, :])
        return out

# 定义模型
model = BiRNN(input_size, hidden_size, num_layers, num_classes).to(device)

# 损失函数和优化算法 
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
    
# 训练模型 
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.reshape(-1, sequence_length, input_size).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()))

# 模型测试部分      
# 测试阶段不需要计算梯度,注意 
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.reshape(-1, sequence_length, input_size).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('Test Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total)) 

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

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

总结:

本节使用RNN训练MNIST识别、自己数据的识别。

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


torch系列:

1. torch01:torch基础

2. torch02:logistic regression--MNIST识别

3. torch03:linear_regression

4. torch04:全连接神经网络--MNIST识别和自己数据集

5. torch05:CNN--MNIST识别和自己数据集

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


你可能感兴趣的:(机器学习,Deep,learning,torch练习汇总)