Self-learning neural network technology, training python code demo of perceptron model

import numpy as np

class Perceptron:
    def __init__(self, learning_rate=0.1, n_iterations=1000):
        self.learning_rate = learning_rate
        self.n_iterations = n_iterations

    def fit(self, X, y):
        self.weights = np.zeros(1 + X.shape[1])
        self.errors = []

        for _ in range(self.n_iterations):
            errors = 0
            for xi, target in zip(X, y):
                update = self.learning_rate * (target - self.predict(xi))
                self.weights[1:] += update * xi
                self.weights[0] += update
                errors += int(update != 0.0)
            self.errors.append(errors)
        return self

    def net_input(self, X):
        return np.dot(X, self.weights[1:]) + self.weights[0]

    def predict(self, X):
        return np.where(self.net_input(X) >= 0.0, 1, -1)

The code implements a simple perceptron model, including __init__ , fit , net_input , and predict functions. The __init__ function initializes the learning rate and the number of iterations, the fit function is used to train the model, the net_input function is used to calculate the product of input and weight plus bias, and the predict function is used to make predictions.

Guess you like

Origin blog.csdn.net/yrldjsbk/article/details/129731070