Runoob Tutorial ArchiveEnglish

Matrix multiplication implements neural network forward propagation

Matrix multiplication implements neural network forward propagation

Hand-write (y = Wx + b), input matrices of different shapes, observe how dimensions change and match.

After learning this case study, you will understand: when training a neural network and getting a shape mismatch error, the essence is that the matrix multiplication dimensions do not match.


Real-life introduction

**Express parcel sorting center

A batch of parcels enters from the conveyor belt (input), is routed by the sorting machine to different trucks (hidden layer), and is finally delivered to various communities (output).

Each sorter is a "neuron"—it receives all packages and decides which packages go its way based on rules. The sorter's rules are "weights": packages going in one direction receive more, and packages going in another receive less.

The operation of the entire sorting center is: matrix multiplication + activation function + bias.


Intuitive understanding

One layer of a neural network = three steps, done in one line of code:

( z = X @ W + b )

Each part has a clear role:

X

Input data

(batch, in)

W

weight matrix

(in, out)

b

bias

(out,)

z

Output

(batch, out)

Dimension matching rule:

The number of columns in A must equal the number of rows in B! (A_{(m \times n)} \cdot B_{(n \times p)} = C_{(m \times p)})

The number of input features (in_features) must equal the number of rows in the weight matrix. The number of output features (out_features) equals the number of columns in the weight matrix. batch_size remains constant throughout the process.


Mathematical definition

Single-layer forward propagation

[ z_j = \sum_{i=1}^{n} x_i \cdot W_{ij} + b_j ]

Each output (z_j) is the dot product of the input vector and the j-th column of the weight matrix, plus the bias.

Two-layer network chaining

[ \begin{aligned} h &= \text{ReLU}(X W_1 + b_1) \quad & (m \times 4) \cdot (4 \times 6) &= (m \times 6) \ o &= \text{Sigmoid}(h W_2 + b_2) \quad & (m \times 6) \cdot (6 \times 2) &= (m \times 2) \end{aligned} ]

Note: The number of features in the first layer's output (6) must equal the number of rows in the second layer's weight matrix (6). This is the "dimension connection between layers".


Python hands-on practice

Demonstrate three scenarios—single sample, batch processing, and two-layer network—using a general dense_layer function.

Example

import

numpy

as

np

def

dense_layer

(

X

,

W

,

b

,

activation

=

None

)

:

   

"""
Forward propagation of a fully connected layer
X: Input matrix (batch_size, in_features)
W: Weight matrix (in_features, out_features)
b: Bias vector (out_features,)
"""

z

=

X

@

W + b

Matrix multiplication + broadcasting addition

   

if

activation

==

"relu"

:

       

return

np.

maximum

(

0

,

z

)

         

ReLU: negative numbers become 0

   

if

activation

==

"sigmoid"

:

       

return

1

/

(

1

exp

(

-z

)

)

     

Sigmoid: compressed to (0,1)

   

return

z

print

(

"="

55

)

print

(

"RUNOOB Scenario 1: Single sample, 4D -> 3D"

)

print

(

"="

55

)

X

=

np.

array

(

[

[

1.0

,

2.0

,

0.5

,

1.0

]

]

)

   

(1, 4)

W

=

np.

random

.

randn

(

4

,

3

)

0.5

           

(4, 3)

b

=

np.

zeros

(

3

)

                           

(3,)

y

=

dense_layer

(

X

,

W

,

b

,

activation

=

"relu"

)

print

(

"X.shape:"

,

X.

shape

,

" W.shape:"

,

W.

shape

,

     

" -> y.shape:"

,

y.

shape

)

print

(

"\n"

"="

55

)

print

(

"RUNOOB Scenario 2: Batch of 8 samples, same weights"

)

print

(

"="

55

)

X_batch

=

np.

random

.

randn

(

8

,

4

)

           

(8, 4)

y_batch

=

dense_layer

(

X_batch

,

W

,

b

,

activation

=

"relu"

)

print

(

"X_batch.shape:"

,

X_batch.

shape

,

     

" -> y_batch.shape:"

,

y_batch.

shape

)

print

(

"Batch size 8 unchanged, feature dimension 4 -> 3"

)

print

(

"\n"

"="

55

)

print

(

"RUNOOB Scenario 3: Stacking Two Layers of Networks"

)

print

(

"="

55

)

First layer: 4D -> 6D + ReLU

W1

=

np.

random

.

randn

(

4

,

6

)

0.5

b1

=

np.

zeros

(

6

)

Second layer: 6D -> 2D + Sigmoid

W2

=

np.

random

.

randn

(

6

,

2

)

0.5

b2

=

np.

zeros

(

2

)

h

=

dense_layer

(

X_batch

,

W1

,

b1

,

activation

=

"relu"

)

out

=

dense_layer

(

h

,

W2

,

b2

,

activation

=

"sigmoid"

)

print

(

f

"Input layer: {X_batch.shape}"

)

print

(

f

"Hidden layer: {h.shape} (4->6, W1=(4,6))"

)

print

(

f

"Output layer: {out.shape} (6->2, W2=(6,2))"

)

Verification: What happens if the dimensions do not match?

print

(

"\n"

"="

55

)

print

(

"RUNOOB Scenario 4: Dimension mismatch will cause an error"

)

print

(

"="

55

)

try

:

    W_wrong

=

np.

random

.

randn

(

5

,

3

)

0.5

 

Incorrect number of lines

dense_layer

(

X_batch

,

W_wrong

,

b

)

except

ValueError

as

e:

   

print

(

"Error reason: X_batch has 4 columns,"

         

"W_wrong has 5 rows -> cannot multiply"

)

   

print

(

f

" Correct way: the number of rows of W ({W_wrong.shape[0]})"

          f

" should equal the number of columns of X ({X_batch.shape[1]})"

)

Original prompt (Chinese, left untranslated)



=======================================================

RUNOOB 场景 1:单样本,4 维 -> 3 维

=======================================================

X.shape: (1, 4)   W.shape: (4, 3)   ->  y.shape: (1, 3)



=======================================================

RUNOOB 场景 2:8 个样本批量,同权重

=======================================================

X_batch.shape: (8, 4)   ->  y_batch.shape: (8, 3)

批大小 8 不变,特征维度 4 -> 3



=======================================================

RUNOOB 场景 3:堆叠两层网络

=======================================================

输入层: (8, 4)

隐藏层: (8, 6)  (4->6, W1=(4,6))

输出层: (8, 2)  (6->2, W2=(6,2))



=======================================================

RUNOOB 场景 4:维度不匹配会报错

=======================================================

报错原因:X_batch 有 4 列,W_wrong 有 5 行 -> 无法相乘

  正确做法:W 的行数 (5) 应等于 X 的列数 (4)


Application scenarios in AI

AI scenarios Dimensionality change example Description
Fully connected layer (32, 784) @ (784, 128) = (32, 128) MNIST classification: 28x28=784 pixels -> 128 dimensional features
Transformer's QKV (B, L, D) @ (D, D) = (B, L, D) Self-attention: input and output token dimensions remain unchanged
Embedding lookup (B, L) → (B, L, D) Word ID sequence → Word vector sequence
Classification head (B, 768) @ (768, 10) = (B, 10) Classification output of the last layer of BERT