Skip to content

Instantly share code, notes, and snippets.

@HectorPulido
Created May 20, 2018 20:42
Show Gist options
  • Save HectorPulido/aa892687336a605b1a65813fa671cff3 to your computer and use it in GitHub Desktop.
Save HectorPulido/aa892687336a605b1a65813fa671cff3 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
public class Program {
public static void Main(string[] args) {
Random r = new Random();
Neurona p = new Neurona(2, r, 0.5f);
bool sw = false;
while (!sw) {
sw = true;
Console.WriteLine("---------------------------------------------");
Console.WriteLine("Peso 1: " + p.Pesos[0]);
Console.WriteLine("Peso 2: " + p.Pesos[1]);
Console.WriteLine("Umbral: " + p.Umbral);
Console.WriteLine("E1:1 E2:1 : " + p.Salida(new float[2] { 1f, 1f }));
Console.WriteLine("E1:1 E2:0 : " + p.Salida(new float[2] { 1f, 0f }));
Console.WriteLine("E1:0 E2:1 : " + p.Salida(new float[2] { 0f, 1f }));
Console.WriteLine("E1:0 E2:0 : " + p.Salida(new float[2] { 0f, 0f }));
//peso = pesoanterior + tasa aprendizaje * error * entrada
if (p.Salida(new float[2] { 1f, 1f }) != 1) {
p.Aprender(new float[2] { 1f, 1f }, 1);
sw = false;
} if (p.Salida(new float[2] { 1f, 0f }) != 0) {
p.Aprender(new float[2] { 1f, 0f }, 0);
sw = false;
} if (p.Salida(new float[2] { 0f, 1f }) != 0) {
p.Aprender(new float[2] { 0f, 1f }, 0);
sw = false;
} if (p.Salida(new float[2] { 0f, 0f }) != 0) {
p.Aprender(new float[2] { 0f, 0f }, 0);
sw = false;
}
}
Console.ReadKey();
}
}
public class Neurona
{
float[] PesosAnteriores;
float UmbralAnterior;
//peso = pesoanterior + tasa aprendizaje * error * entrada
public float[] Pesos;
public float Umbral;
public float TasaDeAprendizaje = 0.3f;
Random r;
public Neurona(int NEntradas, Random R, float tasaDeAprendizaje = 0.3f) {
r = R;
TasaDeAprendizaje = tasaDeAprendizaje;
Pesos = new float[NEntradas];
PesosAnteriores = new float[NEntradas];
Aprender();
}
public void Aprender() {
for (int i = 0; i < PesosAnteriores.Length; i++) {
PesosAnteriores[i] = Convert.ToSingle(2 * r.NextDouble() - 1);
}
UmbralAnterior = Convert.ToSingle(2 * r.NextDouble() - 1);
Pesos = PesosAnteriores;
Umbral = UmbralAnterior;
}
public void Aprender(float[] entradas, float salidaEsperada)
{
float error = salidaEsperada - Salida(entradas);
for (int i = 0; i < Pesos.Length; i++) {
Pesos[i] = PesosAnteriores[i] + TasaDeAprendizaje * error * entradas[i];
}
Umbral = UmbralAnterior + TasaDeAprendizaje * error;
PesosAnteriores = Pesos;
UmbralAnterior = Umbral;
}
public float Salida(float[] entradas)
{
float sum = Umbral;
for (int i = 0; i < Pesos.Length; i++) {
sum += entradas[i] * Pesos[i];
}
return Sigmoid(sum);
}
float Sigmoid(float d)
{
return d > 0 ? 1 : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment