Соберите CNN-классификатор изображений
Объедините блоки Conv-ReLU-pool в работающую модель
«Соберите CNN-классификатор изображений» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
The CNN Recipe
A classic image classifier stacks conv-ReLU-pool blocks to extract features, then ends with dense layers that predict the class.
One Building Block
Each block follows the same rhythm: a conv layer, a ReLU activation, then a pool. This is the basic conv block you repeat.
block = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
)ReLU Adds Nonlinearity
Without an activation, stacked convolutions collapse into one linear step. ReLU after each conv lets the network learn complex shapes.
Stack Blocks to Go Deeper
Repeat the block, growing the channels each time. More blocks mean a wider receptive field and richer learned features.
Flatten Before the Head
After the conv blocks you have a stack of small maps. Flatten them into one vector so a dense layer can read them.
x = torch.flatten(x, start_dim=1)The Classifier Head
A Linear layer maps the flattened features to one score per class. For ten classes, it outputs ten numbers.
head = nn.Linear(64, 10)Define the Model
Wrap the features and head in an nn.Module. The forward method runs the convs, flattens, then the classifier.
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.features = block
self.head = headWrite the Forward Pass
In forward, pass the image through features, flatten, and feed the head. The output is one raw score per class.
def forward(self, x):
x = self.features(x)
x = torch.flatten(x, 1)
return self.head(x)Outputs Are Logits
The head returns raw scores called logits, not probabilities. Cross-entropy loss expects exactly these raw values during training.
Pick the Loss
For multiclass images, use CrossEntropyLoss. It applies softmax internally and compares against the true label index.
loss_fn = nn.CrossEntropyLoss()Predict a Class
At inference, take the index of the largest logit. That argmax is the model's predicted class for the image. 🖼️
pred = logits.argmax(dim=1)Quick Check
Let us check the order of a CNN classifier's pieces.
Recap: A Working CNN
You assembled a CNN: conv-ReLU-pool blocks extract features, flatten feeds a Linear head, and argmax over logits gives the predicted class. 🎉
Часто задаваемые вопросы
Урок «Соберите CNN-классификатор изображений» бесплатный?
Да — полный текст урока «Соберите CNN-классификатор изображений» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Соберите CNN-классификатор изображений»?
Объедините блоки Conv-ReLU-pool в работающую модель Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Соберите CNN-классификатор изображений»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Свёртка: ядра скользят по пикселям
- Шаг, дополнение и pooling
- Каналы, карты признаков и рецептивные поля
- Соберите CNN-классификатор изображений