[Python] Does this multiclass perceptron code look correct?

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    I found the code of this multiclass perceptron online. I can't remember the source. I have not read enough machine learning to be able to inspect it myself but I am wondering if the code is correct or not. I am posting the entire example below. (If I'm not mistaken, the code may have been generated from Microsoft Copilot.)

    import numpy as np

    class MultiClassPerceptron:
    def __init__(self, input_dim, num_classes, learning_rate=0.01, epochs=100):
    self.weights = np.zeros((num_classes, input_dim))
    self.bias = np.zeros(num_classes)
    self.learning_rate = learning_rate
    self.epochs = epochs

    def predict(self, X):
    scores = np.dot(X, self.weights.T) + self.bias
    return np.argmax(scores, axis=1)

    def fit(self, X, y):
    for epoch in range(self.epochs):
    for i in range(X.shape[0]):
    x_i = X
    y_true = y
    y_pred = self.predict(x_i.reshape(1, -1))[0]

    if y_pred != y_true:
    self.weights[y_true] += self.learning_rate * x_i
    self.weights[y_pred] -= self.learning_rate * x_i
    self.bias[y_true] += self.learning_rate
    self.bias[y_pred] -= self.learning_rate

    # Example usage
    if __name__ == "__main__":
    # Sample dataset (X: features, y: labels)
    X = np.array([[2, 1], [1, 3], [2, 3], [3, 2], [4, 1], [3, 4]])
    y = np.array([0, 1, 1, 0, 0, 1]) # Labels for two classes (0 and 1)

    # Initialize and train the perceptron
    perceptron = MultiClassPerceptron(input_dim=2, num_classes=2, learning_rate=0.1, epochs=10)
    perceptron.fit(X, y)

    # Predict on new data
    test_data = np.array([[3, 3], [1, 2]])
    predictions = perceptron.predict(test_data)
    print("Predictions:", predictions)

    Continue reading...

Compartilhe esta Página