Last active
March 17, 2023 17:15
-
-
Save charecktowa/180661bdfeebf2519acac2bb4cfcba95 to your computer and use it in GitHub Desktop.
Implementación de un Perceptron en Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Perceptron { | |
| private double[] pesos; | |
| private double bias; | |
| public double[] getPesos() { | |
| return this.pesos; | |
| } | |
| public double getBias() { | |
| return this.bias; | |
| } | |
| public Perceptron(int numeroCaracteristicas) { | |
| /* Inicializamos los pesos y bias en 0.0 */ | |
| this.pesos = new double[numeroCaracteristicas]; | |
| this.bias = 0.0; | |
| } | |
| public int forward(double[] x) { | |
| double z = 0.0; | |
| for (int i = 0; i < x.length; i++) { | |
| z = z + x[i] * pesos[i]; | |
| } | |
| z = z + bias; | |
| if (z > 0) | |
| return 1; | |
| else | |
| return 0; | |
| } | |
| public double backward(double[] x, int y) { | |
| int prediccion = forward(x); | |
| double error = y - prediccion; | |
| return error; | |
| } | |
| public void train(double[][] entradas, int[] clases, int epocas) { | |
| /* Vamos a entrenar durante n epocas */ | |
| for (int epoca = 0; epoca < epocas; epoca++) { | |
| /* | |
| * Recorremos cada elemento del conjunto de datos | |
| * durante cada epoca | |
| */ | |
| for (int i = 0; i < entradas.length; i++) { | |
| double error = backward(entradas[i], clases[i]); | |
| /* Creo que en Java no hay otra forma como en Python */ | |
| for (int j = 0; j < pesos.length; j++) | |
| pesos[j] = pesos[j] + error * entradas[i][j]; | |
| /* Actualizamos el bias */ | |
| bias = bias + error; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment