Skip to content
BIASED
Back to topic

Optional

Broadcasting and matmul

Check broadcast (3,1)+(1,4) and @ shapes; catch a misaligned case.

Version
v1
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

Python · Broadcasting и matmul / Broadcasting and matmul

Activity version: 1 · Seed: n/a · Данные: формы (3,1), (1,4), (3,4), (4,2).

Ожидаемые числа
Quantity Value Tolerance
(3,1)+(1,4)(3,1)+(1,4) shape (3, 4) exact
sum of broadcast result 2424 exact (ones+ones)
(3,4) @ (4,2) shape (3, 2) exact
Самопроверка в ноутбуке

Не влияет на mastery.

import numpy as np
 
a = np.ones((3, 1))
b = np.ones((1, 4))
c = a + b
assert c.shape == (3, 4)
assert c.sum() == 24
A = np.ones((3, 4))
B = np.ones((4, 2))
M = A @ B
assert M.shape == (3, 2)
assert np.allclose(M, 4.0)
print("c.shape", c.shape, "M", M)
print("OK: numpy broadcast/matmul")
Самопроверка в ноутбуке
  • broadcast shape (3,4), сумма 2424
  • matmul shape (3,2), значения 44