v9.1.1
Menu

Dense Layer Forward

mediumPRONeural NetworksDeep LearningCV: Deep Learning

Implement forward pass of a dense (fully connected) layer, a fundamental component in Neural Networks. This process is crucial for understanding how artificial neurons process inputs to produce meaningful outputs.

In the context of Neural Networks, a dense layer is where every input is connected to every output by a weight matrix WW and a bias vector bb. The forward pass involves computing the output of each neuron by taking the dot product of the input vector xx with the corresponding weights and adding the bias term.

To compute the output, follow these steps:

  1. Initialize output vector yy
  2. For each output neuron, compute the weighted sum of inputs
  3. Add the bias term to the weighted sum
y=Wx+b\mathbf{y} = \mathbf{W}\mathbf{x} + \mathbf{b}

This technique is widely used in image classification tasks.

Example

Input
dense_forward([[1,2],[3,4]], [1,1], [0,0])
Output
[3, 7]
Reasoning
  • Inputs: W is a 2×22 \times 2 weight matrix [1234]\begin{bmatrix}1 & 2\\3 & 4\end{bmatrix} where row ii holds the weights feeding output neuron ii, so it has one row per output and one column per input. x =[1,1]= [1, 1] is the input vector and b =[0,0]= [0, 0] gives one bias per output neuron.
  • Neuron 1: take row 1 of WW against x\mathbf{x}: y1=1⋅1+2⋅1+0=3y_1 = 1 \cdot 1 + 2 \cdot 1 + 0 = 3.
  • Neuron 2: row 2 against x\mathbf{x}: y2=3⋅1+4⋅1+0=7y_2 = 3 \cdot 1 + 4 \cdot 1 + 0 = 7.
  • Output: y=[3,7]\mathbf{y} = [3, 7], a vector whose length equals the number of rows of WW, not the length of x\mathbf{x}. Rounding to 4 decimal places leaves these whole numbers unchanged.
  • Notice: with x\mathbf{x} all ones, each yiy_i is just the sum of row ii of WW. A non-zero bias would simply shift each output, e.g. b=[1,1]\mathbf{b} = [1, 1] would give [4,8][4, 8].

Constraints

  • W is a 2D weight matrix
  • x is input vector
  • b is bias vector
  • Return output rounded to 4 decimal places

Learn this in

More from CV: Deep Learning

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.