Marfein / -12

0 stars 0 forks source link

Обучить однонейронный перцептрон трем базовым логическим функциям #1

Open Marfein opened 1 year ago

Marfein commented 1 year ago

import java.util.Arrays;

public class Perceptron { private double[] weights; private double threshold;

public Perceptron(int numInputs) {
    weights = new double[numInputs];
    Arrays.fill(weights, 0.0);
    threshold = 0.0;
}

public int classify(double[] inputs) {
    double sum = 0.0;
    for (int i = 0; i < weights.length; i++) {
        sum += inputs[i] * weights[i];
    }
    return (sum > threshold) ? 1 : 0;
}

public void train(double[][] inputs, int[] outputs, double learningRate, int maxIterations) {
    int iteration = 0;
    while (iteration < maxIterations) {
        boolean error = false;
        for (int i = 0; i < inputs.length; i++) {
            int output = classify(inputs[i]);
            int errorSignal = outputs[i] - output;
            if (errorSignal != 0) {
                updateWeights(inputs[i], errorSignal, learningRate);
                error = true;
            }
        }
        if (!error) {
            break;
        }
        iteration++;
    }
}

private void updateWeights(double[] inputs, int errorSignal, double learningRate) {
    for (int i = 0; i < weights.length; i++) {
        weights[i] += learningRate * errorSignal * inputs[i];
    }
    threshold -= learningRate * errorSignal;
}

}

Marfein commented 1 year ago

public static void main(String[] args) { double[][] andInputs = {{0, 0}, {0, 1}, {1, 0}, {1, 1}}; int[] andOutputs = {0, 0, 0, 1}; Perceptron andPerceptron = new Perceptron(2); andPerceptron.train(andInputs, andOutputs, 0.1, 100); System.out.println("AND gate:"); System.out.println("0 AND 0 = " + andPerceptron.classify(new double[]{0, 0})); System.out.println("0 AND 1 = " + andPerceptron.classify(new double[]{0, 1})); System.out.println("1 AND 0 = " + andPerceptron.classify(new double[]{1, 0})); System.out.println("1 AND 1 = " + andPerceptron.class