.. _sec_mlp_concise:
Implementação Concisa de *Perceptrons* Multicamadas
===================================================
As you might expect, by relying on the high-level APIs, we can implement
MLPs even more concisely.
.. raw:: html
.. raw:: html
.. code:: python
from mxnet import gluon, init, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
.. raw:: html
.. raw:: html
.. code:: python
import torch
from torch import nn
from d2l import torch as d2l
.. raw:: html
.. raw:: html
.. code:: python
import tensorflow as tf
from d2l import tensorflow as d2l
.. raw:: html
.. raw:: html
Modelo
------
Em comparação com nossa implementação concisa de implementação de
regressão *softmax* (:numref:`sec_softmax_concise`), a única diferença
é que adicionamos *duas* camadas totalmente conectadas (anteriormente,
adicionamos *uma*). A primeira é nossa camada oculta, que contém 256
unidades ocultas e aplica a função de ativação ReLU. A segunda é nossa
camada de saída.
.. raw:: html
.. raw:: html
.. code:: python
net = nn.Sequential()
net.add(nn.Dense(256, activation='relu'),
nn.Dense(10))
net.initialize(init.Normal(sigma=0.01))
.. raw:: html
.. raw:: html
.. code:: python
net = nn.Sequential(nn.Flatten(),
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights);
.. raw:: html
.. raw:: html
.. code:: python
net = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(10)])
.. raw:: html
.. raw:: html
O loop de treinamento é exatamente o mesmo como quando implementamos a
regressão *softmax*. Essa modularidade nos permite separar questões
relativas à arquitetura do modelo a partir de considerações ortogonais.
.. raw:: html
.. raw:: html
.. code:: python
batch_size, lr, num_epochs = 256, 0.1, 10
loss = gluon.loss.SoftmaxCrossEntropyLoss()
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': lr})
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
.. figure:: output_mlp-concise_f87756_27_0.svg
.. raw:: html
.. raw:: html
.. code:: python
batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.CrossEntropyLoss()
trainer = torch.optim.SGD(net.parameters(), lr=lr)
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
.. figure:: output_mlp-concise_f87756_30_0.svg
.. raw:: html
.. raw:: html
.. code:: python
batch_size, lr, num_epochs = 256, 0.1, 10
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
trainer = tf.keras.optimizers.SGD(learning_rate=lr)
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
.. figure:: output_mlp-concise_f87756_33_0.svg
.. raw:: html
.. raw:: html
Resumo
------
- Usando APIs de alto nível, podemos implementar MLPs de forma muito
mais concisa.
- Para o mesmo problema de classificação, a implementação de um MLP é a
mesma da regressão *softmax*, exceto para camadas ocultas adicionais
com funções de ativação.
Exercícios
----------
1. Tente adicionar diferentes números de camadas ocultas (você também
pode modificar a taxa de aprendizagem). Qual configuração funciona
melhor?
2. Experimente diferentes funções de ativação. Qual funciona melhor?
3. Experimente diferentes esquemas para inicializar os pesos. Qual
método funciona melhor?
.. raw:: html
.. raw:: html
`Discussions `__
.. raw:: html
.. raw:: html
`Discussions `__
.. raw:: html
.. raw:: html
`Discussions `__
.. raw:: html
.. raw:: html
.. raw:: html