0Pricing
Deep Learning Academy · Aula

Herede de nn.Module: __init__ e forward

A estrutura padrão de um modelo PyTorch

Herede de nn.Module: __init__ e forward é uma aula grátis de Deep Learning Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Deep Learning Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Deep Learning Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Models Are Just Classes

In PyTorch, every model is a Python class. You build yours by subclassing nn.Module, the base that powers all networks.

Two Methods Run the Show

A model needs only two methods to work: __init__ sets up the layers, and forward describes how data flows through them.

Always Call super().__init__

The very first line inside __init__ must call super().__init__(). This wires your model into PyTorch and lets it track everything. 🔌

class Net(nn.Module):
    def __init__(self):
        super().__init__()

Define Layers in __init__

Inside __init__ you create your layers and store them as attributes. Saving them on self lets PyTorch register them automatically.

self.fc1 = nn.Linear(4, 8)
self.fc2 = nn.Linear(8, 2)

forward Is the Recipe

The forward method takes an input tensor and returns an output. It spells out the exact order your layers process the data.

def forward(self, x):
    x = self.fc1(x)
    return self.fc2(x)

Never Call forward Directly

You call the model like a function, not model.forward(x). Using model(x) runs hooks and bookkeeping that forward alone skips.

out = model(x)   # preferred
# not: out = model.forward(x)

Layers Become Parameters

Because layers live on self, their weights are collected as the model's parameters. The optimizer later updates exactly these.

Instantiate Then Use

Create the model once, then feed it tensors many times. Each call flows through the same learned weights.

model = Net()
prediction = model(sample_input)

Shapes Must Line Up

Each layer's output size must match the next layer's input size. Plan these dimensions as data travels through forward.

Why This Pattern Wins

Subclassing keeps setup and flow cleanly apart. The same simple skeleton scales from a tiny net to a giant one.

Flexible by Design

Inside forward you can branch, reshape, or reuse layers freely. This freedom is why custom nn.Module classes are so powerful. 💪

Quick Check

Think about which method defines how data moves through the network.

Recap

You build a model by subclassing nn.Module, defining layers in __init__ and the data flow in forward. Then just call model(x). 🎯

Perguntas Frequentes

A aula “Herede de nn.Module: __init__ e forward” é grátis?

Sim — o texto completo de “Herede de nn.Module: __init__ e forward” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Deep Learning Academy, atualize para CoddyKit PRO. O curso de Deep Learning Academy inclui 4 aulas no total.

O que vou aprender em “Herede de nn.Module: __init__ e forward”?

A estrutura padrão de um modelo PyTorch Você pratica Deep Learning Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Deep Learning Academy?

Nenhuma experiência prévia é necessária. Deep Learning Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Herede de nn.Module: __init__ e forward”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Deep Learning Academy?

Sim. Cada aula de Deep Learning Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Herede de nn.Module: __init__ e forward
  2. Empilhando Camadas Lineares
  3. nn.Sequential para Modelos Rápidos
  4. Inspecione Parâmetros e Formas das Camadas
← Voltar para Deep Learning Academy