Perceptron Predictions



    Logan Demir

    class Perceptron:
      def __init__(self, num_inputs: int, learning_rate: float = 0.1):
        # initialize the weights and bias with random values
        self.weights = [random.uniform(-1, 1) for _ in range(num_inputs)]
        self.bias = random.uniform(-1, 1)
        self.learning_rate = learning_rate
      def predict(self, inputs: List[float]) -> float:
        # calculate the dot product of the inputs and weights, plus the bias
        return sum(input * weight for input, weight in zip(inputs, self.weights)) + self.bias
      def train(self, inputs: List[float], target: float):
        # make a prediction using the current weights and bias
        prediction = self.predict(inputs)
        # calculate the error as the difference between the target and prediction
        error = target - prediction
        # update the weights and bias based on the error and learning rate
        self.weights = [weight + self.learning_rate * error * input for input, weight in zip(inputs, self.weights)]
        self.bias += self.learning_rate * error
    # create a perceptron with 2 inputs and a learning rate of 0.1
    perceptron = Perceptron(2, 0.1)
    # train the perceptron on a set of inputs and targets
    for inputs, target in zip(inputs, targets):
      perceptron.train(inputs, target)
    # make a prediction on a new input
    prediction = perceptron.predict([1, 2])
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.