0Pricing
Deep Learning Academy · Урок

Унаследуйте nn.Module: __init__ и forward

Стандартный каркас модели PyTorch

«Унаследуйте nn.Module: __init__ и forward» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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). 🎯

Часто задаваемые вопросы

Урок «Унаследуйте nn.Module: __init__ и forward» бесплатный?

Да — полный текст урока «Унаследуйте nn.Module: __init__ и forward» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.

Чему я научусь в уроке «Унаследуйте nn.Module: __init__ и forward»?

Стандартный каркас модели PyTorch Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Deep Learning Academy?

Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Унаследуйте nn.Module: __init__ и forward»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Deep Learning Academy?

Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Унаследуйте nn.Module: __init__ и forward
  2. Объединение линейных слоёв
  3. nn.Sequential для быстрых моделей
  4. Проверка параметров и форм слоёв
← Назад к Deep Learning Academy