Умножение матриц с matmul и @
Скалярные произведения, лежащие в основе каждого слоя
«Умножение матриц с matmul и @» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Beyond Elementwise
Multiplying tensors with the star sign is elementwise. Matrix multiplication is different: it mixes rows and columns into weighted sums.
Dot Products in Bulk
Each output entry of a matrix multiply is a dot product: one row of the left matrix paired with one column of the right matrix.
The Inner Dimensions Must Match
To multiply shapes (m, k) and (k, n), the inner k must agree. The result is (m, n): outer dimensions survive, the inner one is summed away.
The @ Operator
Python gives matrix multiply its own clean symbol. The @ operator multiplies two tensors the matrix way, no loops in sight.
c = a @ btorch.matmul Does the Same
torch.matmul is the spelled-out twin of @. Same result, handy when you prefer a named function call in your code.
c = torch.matmul(a, b)Mind the Shapes
A (2, 3) times a (3, 4) gives a (2, 4). Read the shapes left to right and the inner 3 cancels, leaving the outer pair.
a = torch.randn(2, 3)
b = torch.randn(3, 4)
c = a @ b # shape (2, 4)Star Is Not At
Do not confuse them: a * b is elementwise and needs matching shapes, while a @ b is matrix multiply and needs matching inner dimensions.
Matrix Times Vector
Multiply a matrix by a 1D vector and you get a vector. Each output number is the dot product of a matrix row with that vector.
y = W @ x # W is (n, m), x is (m,), y is (n,)Batched matmul
matmul handles batches: feed shapes (B, m, k) and (B, k, n) and it multiplies each of the B matrix pairs at once, returning (B, m, n).
out = torch.matmul(batch_a, batch_b)Shape Errors Are Loud
Mismatch the inner dimensions and PyTorch throws a clear RuntimeError. Reading those shape messages quickly becomes your fastest debugging tool.
The Engine of Every Layer
This one operation is everywhere. A linear layer is just inputs times a weight matrix plus a bias, and matmul does that heavy lifting.
out = x @ W.T + biasQuick Check
Time to check your shape arithmetic.
Recap: Rows Meet Columns
Matrix multiply with @ or torch.matmul pairs rows with columns into dot products; inner dimensions must match, outer ones survive. It powers every layer. 🔗
Изучай Python с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 30
- Уроки
- 120
Часто задаваемые вопросы
Урок «Умножение матриц с matmul и @» бесплатный?
Да — полный текст урока «Умножение матриц с matmul и @» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Умножение матриц с matmul и @»?
Скалярные произведения, лежащие в основе каждого слоя Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Умножение матриц с matmul и @»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Почему циклы медленны в математических вычислениях
- Поэлементные операции и свёртки
- Умножение матриц с matmul и @
- Скалярные произведения обеспечивают работу каждого слоя