9.1 Multilayer Layer Perceptron (MLP)¶
V tomto cvičení vytvoříme tři modely MLP.
Model 1: 1 vstup, 2 skryté jednotky, 1 výstup pomocí
nn.Sequential()Model 2: s vnitřní definicí (1, 16), (16, 32), (32, 32), (32, 32), (32, 16), (16, 1)
Model 3: 1 vstup, nn.ModuleList() pro proměnlivé množství skrytých jednotek 1 výstup pomcí
nn.Sequential()ann.ModuleList().
In [5]:
Copied!
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
In [6]:
Copied!
# Data
num_points = 1000
torch.manual_seed(0)
x = torch.rand(num_points, 1)
x, _ = torch.sort(x, 0)
noise = torch.rand_like(x) * .7
y = .5 * (x*6).sin() + x + (x - .75) * noise
# Data
num_points = 1000
torch.manual_seed(0)
x = torch.rand(num_points, 1)
x, _ = torch.sort(x, 0)
noise = torch.rand_like(x) * .7
y = .5 * (x*6).sin() + x + (x - .75) * noise
In [4]:
Copied!
print(x.shape)
print(y.shape)
print(x.shape)
print(y.shape)
torch.Size([1000, 1]) torch.Size([1000, 1])
In [4]:
Copied!
# MLP model - příklad
class Multiclass(nn.Module):
def __init__(self, vstup, skryte, vystup):
super().__init__()
self.hidden = nn.Linear(vstup, skryte)
self.act = nn.ReLU()
self.output = nn.Linear(skryte, vystup)
def forward(self, x):
x = self.act(self.hidden(x))
x = self.output(x)
return x
# MLP model - příklad
class Multiclass(nn.Module):
def __init__(self, vstup, skryte, vystup):
super().__init__()
self.hidden = nn.Linear(vstup, skryte)
self.act = nn.ReLU()
self.output = nn.Linear(skryte, vystup)
def forward(self, x):
x = self.act(self.hidden(x))
x = self.output(x)
return x
Vytvořte MLP model 1¶
ANN je tvořeno sekvení kroků od vstupu přes skryté jednotky k výstupu. PyTorch používá metodu nn.Sequential()
Definice architektury MLP:
vstupy: 1
skryté jednotky:
nn.Linear(16, 32)nn.Linear(32, 16)- aktivační funkce:
nn.ReLU()
výstupy: 1
Tedy:
self.nn_block = nn.Sequential(
nn.Linear(num_features, 16), # vstup (1)
nn.ReLU(), # aktivace ReLU
... # skrytá jednotka (lineární 16, 32)
... # aktivace ReLU
... # skrytá jednotka (lineární 32, 16)
... # aktivace ReLU
... # výstup Linear(16, 1)
)
Metoda forward() pak definuje výpočet modelu:
def forward(self, inputs):
x = self.nn_block(inputs)
return (x)
In [ ]:
Copied!
# Nonlinear model with two hidden layers
class NonLinear1(nn.Module):
def __init__(self, num_features):
super(NonLinear, self).__init__()
self.nn_block = pass
def forward(self, inputs):
pass
return (x)
# Nonlinear model with two hidden layers
class NonLinear1(nn.Module):
def __init__(self, num_features):
super(NonLinear, self).__init__()
self.nn_block = pass
def forward(self, inputs):
pass
return (x)
Vytvořte MLP model 2¶
- vstup: 1
- skryté jednotky: (.., 16), (16, 32), (32, 32), (32, 32), (32, 16), (16, ..)
- aktivace
nn.ReLU() - výstup: 1
In [ ]:
Copied!
# Nonlinear model with four hidden layers
class NonLinear2(nn.Module):
def __init__(self, num_features):
super(NonLinear, self).__init__()
self.nn_block = pass
def forward(self, inputs):
pass
return (x)
# Nonlinear model with four hidden layers
class NonLinear2(nn.Module):
def __init__(self, num_features):
super(NonLinear, self).__init__()
self.nn_block = pass
def forward(self, inputs):
pass
return (x)
Vytvořte MLP model 3¶
pro proměnlivé množství skrytých jednotek pomocí nn.Sequential() a nn.ModuleList().
Definice architektury MLP:
- vstup: 1
- skryté jednotky: N s dimenzionalitou neuronů (32, 32)
- aktivační funkce:
nn.ReLU() - output layer: (32, 1)
Použijte nn.ModuleList():
self.num_hidden_layers = num_hidden_layers
self.hidden_layer_list = []
self.hidden_layer = nn.Sequential(
nn.Linear(32, 32),
nn.ReLU()
)
for i in range(num_hidden_layers):
self.hidden_layer_list.append(self.hidden_layer)
self.hidden_layers = nn.ModuleList(self.hidden_layer_list)
Metoda forward():
for i in range(len(self.hidden_layers)):
x = self.hidden_layers[i](x)
In [ ]:
Copied!
# Nonlinear model with two hidden layers
class NonLinear(3nn.Module):
def __init__(self, num_features, num_hidden_layers):
super(NonLinear, self).__init__()
self.nn_input = pass
self.hidden_layers = nn.ModuleList(pass)
self.nn_output = pass
def forward(self, inputs):
pass
return (x)
# Nonlinear model with two hidden layers
class NonLinear(3nn.Module):
def __init__(self, num_features, num_hidden_layers):
super(NonLinear, self).__init__()
self.nn_input = pass
self.hidden_layers = nn.ModuleList(pass)
self.nn_output = pass
def forward(self, inputs):
pass
return (x)
In [11]:
Copied!
# Vytvořte instace vzbraného modelu (1, ě nebo 3)
pass
# Vytvořte instace vzbraného modelu (1, ě nebo 3)
pass
In [ ]:
Copied!
# Připravte optimalizaci
learning_rate = 0.1
epochs = 3000
# Ztráta (Loss): model regrese -> MSE
pass
# Omptimalizační algoritmus: Stochastic Gradient Descent (SGC)
pass
# Připravte optimalizaci
learning_rate = 0.1
epochs = 3000
# Ztráta (Loss): model regrese -> MSE
pass
# Omptimalizační algoritmus: Stochastic Gradient Descent (SGC)
pass
In [ ]:
Copied!
# Učení modelu
# převod vstupů na Variable
inputs = Variable(x)
outputs = Variable(y)
# učení
for i in range(epochs):
# aplikace modelu
prediction = pass
# ztráta
loss = pass
# zpětná propagace chyb loss.backward()
pass
# předání parametrů modelu z optimalizačního algoritmu optimizer.step()
pass
# odstranění gradientů z předchozího kroku optimizer.zero_grad()
pass
# graf
if i % 100 == 0:
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=2)
plt.text(0.3, 0, 'Ztráta=%.4f' % loss.data.numpy(), fontdict={'size': 10, 'color': 'red'})
plt.pause(0.01)
plt.show()
# Učení modelu
# převod vstupů na Variable
inputs = Variable(x)
outputs = Variable(y)
# učení
for i in range(epochs):
# aplikace modelu
prediction = pass
# ztráta
loss = pass
# zpětná propagace chyb loss.backward()
pass
# předání parametrů modelu z optimalizačního algoritmu optimizer.step()
pass
# odstranění gradientů z předchozího kroku optimizer.zero_grad()
pass
# graf
if i % 100 == 0:
plt.cla()
plt.scatter(x.data.numpy(), y.data.numpy())
plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=2)
plt.text(0.3, 0, 'Ztráta=%.4f' % loss.data.numpy(), fontdict={'size': 10, 'color': 'red'})
plt.pause(0.01)
plt.show()
Vylaďte ML model (N vrstev)¶
In [ ]:
Copied!
pass
pass