← back

Single Neuron

#24 · Deep Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement a single neuron that takes inputs, applies weights and a bias, and uses a sigmoid activation function. Return the activated output.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
import math

def single_neuron(features: list[list[float]], labels: list[int],
                   weights: list[float], bias: float) -> tuple[list[float], float]:
    outputs = []
    for x in features:
        z = sum(x[i] * weights[i] for i in range(len(weights))) + bias
        a = 1 / (1 + math.exp(-z))
        outputs.append(a)
    # Compute MSE loss
    mse = sum((outputs[i] - labels[i]) ** 2 for i in range(len(labels))) / len(labels)
    return [round(o, 4) for o in outputs], round(mse, 4)

Explanation

  1. For each input feature vector, compute the weighted sum: z = w * x + b.
  2. Apply the sigmoid activation: a = 1 / (1 + e^(-z)).
  3. Compute the mean squared error between outputs and true labels.
  4. Return the list of activated outputs and the MSE loss.

Complexity

  • Time: O(n * f) where n is the number of samples and f is the number of features
  • Space: O(n) for the output list