1. Home
  2. Explore
  3. Computer Science
  4. Perceptron Coding Challenge

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Perceptron Coding Challenge

Perceptron: The Building Block of Neural Networks

Introduction to the Perceptron

The perceptron is the simplest model of an artificial neural network, invented by Frank Rosenblatt in 1957 at the Cornell Aeronautical Laboratory. It is inspired by and loosely modeled after a biological neuron: inputs (like dendrites) carry signals into the neuron, a mathematical process occurs inside, and an output (like an axon) sends a result onward.

  • Invented in 1957 by Frank Rosenblatt

  • Represents a single artificial neuron

  • Serves as the fundamental building block for more complex neural networks

A perceptron takes multiple inputs, weights each one, sums them, and passes the result through an activation function to produce a single output (typically +1 or -1 for classification).

The Perceptron Model

Components of a Perceptron

  • Inputs: A set of values x0,x1,…,xnx_0, x_1, \dots, x_nx0​,x1​,…,xn​ representing features of the data.

  • Weights: Each input xix_ixi​ has an associated weight wiw_iwi​. The weights determine the importance of each input.

  • Summation: The perceptron computes the weighted sum:

    sum=∑i=0nxi⋅wisum = \sum_{i=0}^{n} x_i \cdot w_isum=∑i=0n​xi​⋅wi​
  • Activation function: The sum is passed through a function to produce the output. For a binary classifier, the sign function is used:

    output={+1if sum≥0−1if sum<0output = \begin{cases} +1 & \text{if } sum \ge 0 \\ -1 & \text{if } sum < 0 \end{cases}output={+1−1​if sum≥0if sum<0​

This process is known as feed-forward: inputs flow forward through weighted connections, get summed, and pass through the activation function to generate the output.

Algorithm per Input

  1. Multiply each input by its corresponding weight.

  2. Sum all weighted inputs.

  3. Apply the activation function (e.g., sign) to the sum to get the output.

Supervised Learning with the Perceptron

A common task for the perceptron is binary classification: assigning inputs to one of two classes. For example, points in a 2D space are separated by a line; points above the line belong to class +1 and points below to class -1.

Supervised Learning Process

Supervised learning: The perceptron is trained using labeled data where the correct answer is known. For each input, the perceptron makes a guess. If the guess is wrong, the weights are adjusted to reduce future errors.

Steps:

  1. Provide an input with a known target (correct answer).

  2. The perceptron guesses the output (using its current weights).

  3. Compute the error:
    $$error = target - guess$$

  4. Adjust each weight using the weight update rule:
    $$w_i = w_i + error \times x_i \times learning\ rate$$

The learning rate (often denoted η\etaη) controls how much the weights change each time. A small learning rate (e.g., 0.1) avoids overshooting and leads to stable convergence.

Error Values

Since targets and guesses are only +1 or -1, the possible error values are:

  • If correct: error = 0

  • If target = +1 and guess = -1: error = +2

  • If target = -1 and guess = +1: error = -2

The weight update uses the full error multiplied by the input – this is a form of gradient descent (steering the weights in the direction that reduces error).

Code Implementation (Processing / Java)

Perceptron Class Structure

A Perceptron class stores an array of weights and a learning rate.

class Perceptron {
  float[] weights;
  float lr = 0.1;
  
  Perceptron(int n) {
    weights = new float[n];
    for (int i = 0; i < n; i++) {
      weights[i] = random(-1, 1);   // initialize randomly
    }
  }
  
  int guess(float[] inputs) {
    float sum = 0;
    for (int i = 0; i < weights.length; i++) {
      sum += inputs[i] * weights[i];
    }
    int output = sign(sum);
    return output;
  }
  
  int sign(float n) {
    if (n >= 0) return 1;
    else return -1;
  }
}

Training the Perceptron

A train method receives inputs and the known target (label), computes the guess, calculates the error, and updates all weights.

void train(float[] inputs, int target) {
  int guess = guess(inputs);
  int error = target - guess;
  // adjust all weights
  for (int i = 0; i < weights.length; i++) {
    weights[i] += error * inputs[i] * lr;
  }
}

Training Data: Points and Labels

A Point class represents a single training example with coordinates and a label.

class Point {
  float x, y;
  int label;
  
  Point() {
    x = random(width);
    y = random(height);
    // decision boundary: line y = x
    if (x > y) label = 1;
    else label = -1;
  }
}

The line y=xy = xy=x separates the space: points above (x>yx > yx>y) get +1, below get -1. This is arbitrary but provides a simple linearly separable dataset.

Training Loop

Two common training approaches:

Batch training (e.g., on mouse click): Loop through all training points once and update weights.

void mousePressed() {
  for (int i = 0; i < trainingData.length; i++) {
    Point pt = trainingData[i];
    float[] inputs = {pt.x, pt.y};
    brain.train(inputs, pt.label);
  }
}

Incremental training (one point per frame): Train on a single point each draw cycle, cycling through the dataset continuously.

int trainingIndex = 0;
void draw() {
  Point pt = trainingData[trainingIndex];
  float[] inputs = {pt.x, pt.y};
  brain.train(inputs, pt.label);
  trainingIndex++;
  if (trainingIndex >= trainingData.length) {
    trainingIndex = 0;
  }
  // redraw all points with correct/incorrect visualization
}

Visual Feedback

Points are drawn as ellipses:

  • Green fill if the perceptron's guess matches the label (correct)

  • Red fill if the guess is wrong (incorrect)

Over time, as training progresses, all points become green, indicating the perceptron has learned the decision boundary.

The Bias Problem

Why a Bias Input is Necessary

Consider the point at the origin (0,0)(0, 0)(0,0).

  • The weighted sum becomes 0⋅w0+0⋅w1=00 \cdot w_0 + 0 \cdot w_1 = 00⋅w0​+0⋅w1​=0.

  • The sign function returns +1 (since 0≥00 \ge 00≥0), regardless of the target.

  • Therefore the perceptron can never output -1 for (0,0)(0,0)(0,0), even though the true label might be -1 (e.g., if the decision boundary does not pass through the origin).

This is a fundamental limitation. The solution is to add a bias – a third input that is always 111, with its own weight wbw_bwb​. The weighted sum becomes:

sum=x0⋅w0+x1⋅w1+1⋅wbsum = x_0 \cdot w_0 + x_1 \cdot w_1 + 1 \cdot w_bsum=x0​⋅w0​+x1​⋅w1​+1⋅wb​

Connection to Linear Regression

The perceptron with a bias effectively learns a linear equation of the form:

y=mx+by = mx + by=mx+b
  • The weight on xxx corresponds to the slope mmm.

  • The bias weight wbw_bwb​ corresponds to the y-intercept bbb.

  • The decision boundary is the line where the weighted sum equals zero: w0x+w1y+wb=0w_0 x + w_1 y + w_b = 0w0​x+w1​y+wb​=0.

Thus the perceptron performs linear regression via gradient descent, albeit with a hard threshold activation function (sign).

Limitations and Next Steps

  • The perceptron can only classify linearly separable data. It cannot learn patterns like XOR.

  • Despite this limitation, it serves as a critical building block for multi-layer neural networks, where multiple perceptrons are connected to form hidden layers.

  • Future extensions include:

    • Adding a bias input (always 1)

    • Visualizing the learned decision line

    • Generalizing to more inputs and non-linear activation functions (e.g., sigmoid, ReLU)

    • Combining multiple perceptrons into a network capable of learning complex, non-linear decision boundaries

The perceptron's training algorithm — feed-forward, error computation, and gradient descent weight update — is the foundation upon which modern deep learning systems are built. Understanding this simple model provides the essential intuition for more advanced neural network architectures.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent