zuma/lab/4_Sieci_neuronowe_PyTorch.ipynb
2021-05-19 18:55:01 +02:00

25 KiB
Raw Blame History

AITech — Uczenie maszynowe — laboratoria

4. Sieci neuronowe (PyTorch)

Przykład implementacji sieci neuronowej do rozpoznawania cyfr ze zbioru MNIST, według https://github.com/pytorch/examples/tree/master/mnist

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.optim.lr_scheduler import StepLR


class Net(nn.Module):
    """W PyTorchu tworzenie sieci neuronowej
    polega na zdefiniowaniu klasy, która dziedziczy z nn.Module.
    """
    
    def __init__(self):
        super().__init__()
        
        # Warstwy splotowe
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        
        # Warstwy dropout
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        
        # Warstwy liniowe
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        """Definiujemy przechodzenie "do przodu" jako kolejne przekształcenia wejścia x"""
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output


def train(model, device, train_loader, optimizer, epoch, log_interval, dry_run):
    """Uczenie modelu"""
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)  # wrzucenie danych na kartę graficzną (jeśli dotyczy)
        optimizer.zero_grad()  # wyzerowanie gradientu
        output = model(data)  # przejście "do przodu"
        loss = F.nll_loss(output, target)  # obliczenie funkcji kosztu
        loss.backward()  # propagacja wsteczna
        optimizer.step()  # krok optymalizatora
        if batch_idx % log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
            if dry_run:
                break


def test(model, device, test_loader):
    """Testowanie modelu"""
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)  # wrzucenie danych na kartę graficzną (jeśli dotyczy)
            output = model(data)  # przejście "do przodu"
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # suma kosztów z każdego batcha
            pred = output.argmax(dim=1, keepdim=True)  # predykcja na podstawie maks. logarytmu prawdopodobieństwa
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)  # obliczenie kosztu na zbiorze testowym

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))


def run(
        batch_size=64,
        test_batch_size=1000,
        epochs=14,
        lr=1.0,
        gamma=0.7,
        no_cuda=False,
        dry_run=False,
        seed=1,
        log_interval=10,
        save_model=False,
    ):
    """Main training function.
    
    Arguments:
        batch_size - wielkość batcha podczas uczenia (default: 64),
        test_batch_size - wielkość batcha podczas testowania (default: 1000)
        epochs - liczba epok uczenia (default: 14)
        lr - współczynnik uczenia (learning rate) (default: 1.0)
        gamma - współczynnik gamma (dla optymalizatora) (default: 0.7)
        no_cuda - wyłącza uczenie na karcie graficznej (default: False)
        dry_run - szybko ("na sucho") sprawdza pojedyncze przejście (default: False)
        seed - ziarno generatora liczb pseudolosowych (default: 1)
        log_interval - interwał logowania stanu uczenia (default: 10)
        save_model - zapisuje bieżący model (default: False)
    """
    use_cuda = no_cuda and torch.cuda.is_available()

    torch.manual_seed(seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    train_kwargs = {'batch_size': batch_size}
    test_kwargs = {'batch_size': test_batch_size}
    if use_cuda:
        cuda_kwargs = {'num_workers': 1,
                       'pin_memory': True,
                       'shuffle': True}
        train_kwargs.update(cuda_kwargs)
        test_kwargs.update(cuda_kwargs)

    transform=transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.1307,), (0.3081,))
        ])
    dataset1 = datasets.MNIST('../data', train=True, download=True,
                       transform=transform)
    dataset2 = datasets.MNIST('../data', train=False,
                       transform=transform)
    train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
    test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)

    model = Net().to(device)
    optimizer = optim.Adadelta(model.parameters(), lr=lr)

    scheduler = StepLR(optimizer, step_size=1, gamma=gamma)
    for epoch in range(1, epochs + 1):
        train(model, device, train_loader, optimizer, epoch, log_interval, dry_run)
        test(model, device, test_loader)
        scheduler.step()

    if save_model:
        torch.save(model.state_dict(), "mnist_cnn.pt")

Uwaga: uruchomienie tego przykładu długo trwa. Żeby trwało krócej, można zmniejszyć liczbę epok.

run(epochs=5)
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz to ../data\MNIST\raw\train-images-idx3-ubyte.gz
HBox(children=(FloatProgress(value=1.0, bar_style='info', max=1.0), HTML(value='')))
---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
<ipython-input-3-ac97a8e9c0c6> in <module>
----> 1 run(epochs=5)

<ipython-input-1-173aee26f027> in run(batch_size, test_batch_size, epochs, lr, gamma, no_cuda, dry_run, seed, log_interval, save_model)
    127         transforms.Normalize((0.1307,), (0.3081,))
    128         ])
--> 129     dataset1 = datasets.MNIST('../data', train=True, download=True,
    130                        transform=transform)
    131     dataset2 = datasets.MNIST('../data', train=False,

~\anaconda3\lib\site-packages\torchvision\datasets\mnist.py in __init__(self, root, train, transform, target_transform, download)
     77 
     78         if download:
---> 79             self.download()
     80 
     81         if not self._check_exists():

~\anaconda3\lib\site-packages\torchvision\datasets\mnist.py in download(self)
    144         for url, md5 in self.resources:
    145             filename = url.rpartition('/')[2]
--> 146             download_and_extract_archive(url, download_root=self.raw_folder, filename=filename, md5=md5)
    147 
    148         # process and save as torch files

~\anaconda3\lib\site-packages\torchvision\datasets\utils.py in download_and_extract_archive(url, download_root, extract_root, filename, md5, remove_finished)
    254         filename = os.path.basename(url)
    255 
--> 256     download_url(url, download_root, filename, md5)
    257 
    258     archive = os.path.join(download_root, filename)

~\anaconda3\lib\site-packages\torchvision\datasets\utils.py in download_url(url, root, filename, md5)
     82                 )
     83             else:
---> 84                 raise e
     85         # check integrity of downloaded file
     86         if not check_integrity(fpath, md5):

~\anaconda3\lib\site-packages\torchvision\datasets\utils.py in download_url(url, root, filename, md5)
     68         try:
     69             print('Downloading ' + url + ' to ' + fpath)
---> 70             urllib.request.urlretrieve(
     71                 url, fpath,
     72                 reporthook=gen_bar_updater()

~\anaconda3\lib\urllib\request.py in urlretrieve(url, filename, reporthook, data)
    245     url_type, path = _splittype(url)
    246 
--> 247     with contextlib.closing(urlopen(url, data)) as fp:
    248         headers = fp.info()
    249 

~\anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223 
    224 def install_opener(opener):

~\anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    529         for processor in self.process_response.get(protocol, []):
    530             meth = getattr(processor, meth_name)
--> 531             response = meth(req, response)
    532 
    533         return response

~\anaconda3\lib\urllib\request.py in http_response(self, request, response)
    638         # request was successfully received, understood, and accepted.
    639         if not (200 <= code < 300):
--> 640             response = self.parent.error(
    641                 'http', request, response, code, msg, hdrs)
    642 

~\anaconda3\lib\urllib\request.py in error(self, proto, *args)
    567         if http_err:
    568             args = (dict, 'default', 'http_error_default') + orig_args
--> 569             return self._call_chain(*args)
    570 
    571 # XXX probably also want an abstract factory that knows when it makes

~\anaconda3\lib\urllib\request.py in _call_chain(self, chain, kind, meth_name, *args)
    500         for handler in handlers:
    501             func = getattr(handler, meth_name)
--> 502             result = func(*args)
    503             if result is not None:
    504                 return result

~\anaconda3\lib\urllib\request.py in http_error_default(self, req, fp, code, msg, hdrs)
    647 class HTTPDefaultErrorHandler(BaseHandler):
    648     def http_error_default(self, req, fp, code, msg, hdrs):
--> 649         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    650 
    651 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 503: Service Unavailable