create perceptron algorithm in javascript

Here's how to create a simple Perceptron algorithm in JavaScript:

index.tsx
class Perceptron {
  constructor(numInputs, learningRate) {
    this.weights = new Array(numInputs);
    for (let i = 0; i < numInputs; i++) {
      this.weights[i] = 0;
    }
    this.bias = 0;
    this.learningRate = learningRate;
  }

  predict(inputs) {
    let sum = 0;
    for (let i = 0; i < inputs.length; i++) {
      sum += inputs[i] * this.weights[i];
    }
    sum += this.bias;
    return this.activationFunction(sum);
  }

  train(inputs, label) {
    const predicted = this.predict(inputs);
    const error = label - predicted;
    for (let i = 0; i < inputs.length; i++) {
      this.weights[i] += error * inputs[i] * this.learningRate;
    }
    this.bias += error * this.learningRate;
  }

  activationFunction(x) {
    return x >= 0 ? 1 : -1;
  }
}
768 chars
33 lines

The Perceptron class takes two arguments: numInputs, which is the number of inputs; and learningRate, which is the learning rate of the algorithm. The constructor initializes the weights and bias to 0, and saves the learning rate.

The predict method takes an array of inputs, multiplies each input by its corresponding weight, adds the bias, and passes the result through an activation function (in this case, the step function). The method returns the predicted output.

The train method takes an array of inputs and a label, computes the predicted output, calculates the error (difference between predicted output and label), and updates the weights and bias based on the error and learning rate.

The activationFunction method implements the step function, which returns 1 if the input is greater than or equal to 0, and -1 otherwise.

This Perceptron algorithm can be used for binary classification tasks, such as recognizing handwritten digits or classifying emails as spam or not spam. Note that this is a basic implementation and there are many improvements and variations that can be made to the algorithm.

gistlibby LogSnag