0Pricing
Deep Learning Academy · Lección

Herede de nn.Module: __init__ y forward

La estructura estándar de un modelo de PyTorch

Herede de nn.Module: __init__ y forward es una lección gratuita de Deep Learning Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Deep Learning Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Deep Learning Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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). 🎯

Preguntas frecuentes

¿La lección «Herede de nn.Module: __init__ y forward» es gratis?

Sí — el texto completo de «Herede de nn.Module: __init__ y forward» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Deep Learning Academy, actualiza a CoddyKit PRO. El curso de Deep Learning Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Herede de nn.Module: __init__ y forward»?

La estructura estándar de un modelo de PyTorch Practicas Deep Learning Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Deep Learning Academy?

No se requiere experiencia previa. Deep Learning Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Herede de nn.Module: __init__ y forward»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Deep Learning Academy?

Sí. Cada lección de Deep Learning Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Herede de nn.Module: __init__ y forward
  2. Apilar capas lineales
  3. nn.Sequential para crear modelos rápidamente
  4. Inspeccionar parámetros y formas de las capas
← Volver a Deep Learning Academy