以下是单层感知机的伪代码的源代码及测试代码:

import numpy as np

class Perceptron:
    def __init__(self, input_size):
        self.weights = np.zeros(input_size)
        self.bias = 0
    
    def predict(self, inputs):
        activation = np.dot(inputs, self.weights) + self.bias
        return np.where(activation >= 0, 1, 0)
    
    def train(self, training_inputs, labels, epochs):
        for _ in range(epochs):
            for inputs, label in zip(training_inputs, labels):
                prediction = self.predict(inputs)
                self.weights += (label - prediction) * inputs
                self.bias += (label - prediction)

测试代码:

training_inputs = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0], [0, 0, 1]])
labels = np.array([1, 0, 0, 0])

perceptron = Perceptron(3)
perceptron.train(training_inputs, labels, epochs=10)

test_inputs = np.array([[1, 0, 0], [0, 0, 0], [1, 1, 1]])
for inputs in test_inputs:
    print(f"Input: {inputs} -> Prediction: {perceptron.predict(inputs)}")

在这个例子中,我们使用一个3维的输入(包括偏置项),并给定了4个训练样本和相应的标签。我们创建一个Perceptron对象,并使用训练数据对其进行训练。然后,我们使用测试数据进行预测,并输出预测结果

单层感知机的伪代码的源代码及测试代码

原文地址: https://www.cveoy.top/t/topic/hF3M 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录