0Pricing
Deep Learning Academy · Урок

Правила broadcasting, которые избавят от циклов

Поэлементно объединяйте тензоры разной формы

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

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

Combine Without Matching Shapes

Broadcasting lets PyTorch stretch a smaller tensor to fit a bigger one, so you skip writing loops to repeat values.

Add a Scalar to Everything

The simplest broadcast: add one number to a whole tensor. PyTorch applies it to every element at once. ✨

x = torch.tensor([1, 2, 3])
print(x + 10)  # tensor([11, 12, 13])

Compare Shapes Right to Left

Broadcasting lines up dimensions from the right. It then checks each pair to decide if they can combine.

Rule One: Equal Sizes Match

Two dimensions are compatible when they are equal. Matching sizes line up one to one with no stretching needed.

Rule Two: A Size of 1 Stretches

If one dimension is 1, it expands to match the other. That single value is reused across the whole axis.

a = torch.tensor([[1], [2], [3]])
b = torch.tensor([10, 20])
print((a + b).shape)  # torch.Size([3, 2])

Missing Dimensions Count as 1

When one tensor has fewer dimensions, PyTorch pads it with leading ones. A vector can broadcast against a matrix this way.

m = torch.ones(2, 3)
v = torch.tensor([1, 2, 3])
print((m + v).shape)  # torch.Size([2, 3])

Add a Bias Across Rows

A classic use: add a row bias to every sample in a batch. One small vector reaches every row for free.

batch = torch.zeros(4, 3)
bias = torch.tensor([1.0, 2.0, 3.0])
print((batch + bias).shape)  # torch.Size([4, 3])

Normalize a Column at Once

Subtract a per-column mean with broadcasting and center your data in one line, no loop over rows required.

x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
m = x.mean(dim=0)
print(x - m)

When Shapes Don't Broadcast

If two dimensions differ and neither is 1, the broadcast fails and PyTorch raises a clear size error.

Add Dimensions to Steer Broadcasting

Use unsqueeze to insert a size-1 axis exactly where you need it. This guides broadcasting toward the shape you want.

col = torch.tensor([1, 2, 3]).unsqueeze(1)
print(col.shape)  # torch.Size([3, 1])

Why Broadcasting Is Fast

Broadcasting never copies the stretched values, it reuses them. That makes vectorized math far faster than Python loops. 🚀

Quick Check

Can you predict whether two shapes will broadcast?

Recap: Broadcasting Rules

You learned the two rules: dimensions match when equal or when one is 1. Master this and loops melt into clean, fast tensor math. 💪

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

Урок «Правила broadcasting, которые избавят от циклов» бесплатный?

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

Чему я научусь в уроке «Правила broadcasting, которые избавят от циклов»?

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

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

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

Сколько времени занимает урок «Правила broadcasting, которые избавят от циклов»?

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

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

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

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

  1. Формы, типы данных и индексация
  2. Изменение формы, View, Squeeze и Unsqueeze
  3. Правила broadcasting, которые избавят от циклов
  4. Тензоры взаимодействуют с NumPy
← Назад к Deep Learning Academy