Every Input to Every Neuron

Neural Network Building BlocksMedium+20 XP+20

Every Input to Every Neuron

Put several neurons side by side, connect every input to every one of them, and you have a layer. Because every input is wired to every neuron, this kind is called a dense, or fully connected, layer. A layer with 333 inputs and 222 neurons has 3×2=63 \times 2 = 63×2=6 connections, so it has 666 weights, plus one bias for each neuron.

Those weights have to be stored somehow. Here they come as a connection table with one row per input and one column per neuron: weights[i][j] is the weight on the connection from input i to neuron j. For that 3-input, 2-neuron layer:

neuron 0neuron 1
input 0weights[0][0]weights[0][1]
input 1weights[1][0]weights[1][1]
input 2weights[2][0]weights[2][1]

Neuron j takes each input xix_ixi​ of an example, multiplies it by the weight on the connection from input i to neuron j, adds up those products, and then adds its own bias biases[j]. That whole total, bias included, is the neuron's zzz:

zj=∑ixi⋅weights[i][j]+biases[j]z_j = \sum_i x_i \cdot \text{weights}[i][j] + \text{biases}[j]zj​=∑i​xi​⋅weights[i][j]+biases[j]

The neuron then outputs ReLU(zj)=max⁡(0,zj)\text{ReLU}(z_j) = \max(0, z_j)ReLU(zj​)=max(0,zj​), so the bias goes in before the clipping.

Task: write dense_forward(batch, weights, biases), which runs a whole batch through one such layer.

  • batch is a list of n examples, and each example is a list of d input values.
  • weights is the d × k connection table for a layer of k neurons.
  • biases has k entries, one per neuron.
  • Return an n × k list of lists, with one row per example and one entry per neuron. Round each value to 4 decimal places. A layer with a single neuron still returns one row per example, and each row is still a list.

Each row you return is a new description of that example, written in the layer's own k features instead of the d it arrived with, and it is exactly what the next layer would take as its input. Nobody designs those features by hand: they are whatever the learned weights make them.

What If One Neuron Isn't Enough?

Every input connects to every neuron you add.

1 neuron

Examples

batch = [[1.0, 2.0, -1.0], [0.5, 0.0, 3.0]]
weights = [[0.4, -1.0], [0.3, 0.5], [-0.2, 0.8]]
biases = [0.1, 1.0]
returns [[1.3, 0.2], [0.0, 2.9]]
batch = [[1.0, -2.0], [0.0, 1.0], [2.0, 2.0]]
weights = [[1.0, -0.5, 0.25, 0.0], [0.5, 1.5, -1.0, 2.0]]
biases = [0.0, 1.0, 0.5, -1.0]
returns [[0.0, 0.0, 2.75, 0.0], [0.5, 2.5, 0.0, 1.0], [3.0, 3.0, 0.0, 3.0]]
batch = [[1.0, 2.0, 3.0, 4.0], [-1.0, 0.5, 2.0, -3.0]]
weights = [[0.25], [-0.5], [0.1], [0.3]]
biases = [0.05]
returns [[0.8], [0.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run