Redes Neurais Artificiais

De Aulas

Links relacionados: Inteligência Artificial

Neurônio Artificial Portas Lógicas em Python

"""
PROGRAM: Perceptron
author: Saulo Popov Zambiasi
created: 2019.05.17
modified: 2022.04.28
"""
from random import *


class Perceptron:
    N = 0.01
    epoch = 100
    weight = []
    option = 0
    # example by columns
    # bias (-1) | x1 | x2 | y_or | y_not_or | y_and | y_not_and | y_xor
    example = [
        [-1, 0, 0, 0, 1, 0, 1, 0],
        [-1, 0, 1, 1, 0, 0, 1, 1],
        [-1, 1, 0, 1, 0, 0, 1, 1],
        [-1, 1, 1, 1, 0, 1, 0, 0]
    ]

    def __init__(self, option):
        self.option = option
        if self.option < 0 or self.option > 4:
            self.option = 0
        self.option += 3
        for i in range(3):
            self.weight += [randint(1, 100) / 100.0]

    def adjust_weight(self, e, out):
        for i in range(3):
            self.weight[i] += self.N * \
                (self.example[e][self.option] - out) * self.example[e][i]

    def training(self):
        trained = False
        epoch = 0
        while not trained and epoch < self.epoch:
            trained = True
            for i in range(4):
                y = self.net(self.example[i][1], self.example[i][2])
                if y != self.example[i][self.option]:
                    self.adjust_weight(i, y)
                    trained = False
            epoch += 1
        if trained:
            print("Trained in", epoch, "epochs.")
            return True
        else:
            print("There was not possible to learn.")
            return False

    def net(self, x1, x2):
        y = (-1 * self.weight[0]) + \
            (x1 * self.weight[1]) + (x2 * self.weight[2])
        if y > 0:
            return 1
        return 0


# MAIN PROGRAM -----------------------------------------
def main():
    print("PERCEPTRON: training to logic ports")
    o = 0
    while o != 9:
        print("Choose operation [ 0: OR | 1: NOT OR |",
              "2: AND | 3: NOT AND | 4: XOR ] - Or 9 to exit")
        o = int(input("operation: "))
        if o != 9:
            neuron = Perceptron(o)
            if neuron.training():
                exit_loop = False
                while not exit_loop:
                    print("-- Type 0 or 1 - Or 9 to other training")
                    x1 = int(input("x1: "))
                    if x1 != 9:
                        x2 = int(input("x2: "))
                        y = neuron.net(x1, x2)
                        print("y = ", y)
                    else:
                        exit_loop = True
    print("Terminated...")


# -------------------------------------------------------
if __name__ == "__main__":
    main()

Neurônio Artificial Porta OU em C++11

#include <iostream>

using namespace std;

class Neuronio
{
private:
	int   saida;
	float N = 0.01;
	int   epocas = 100;
	float peso[3];
	int   exemplo[4][4]
	{
		{ -1, 0, 0, 0 },
		{ -1, 0, 1, 1 },
		{ -1, 1, 0, 1 },
		{ -1, 1, 1, 1 }
	};
public:
	Neuronio();
	void transferencia();
	void treinamento_pesos(int j);
	void treinamento();
	int net(int j);
	int executar(int x[2]);
};

Neuronio::Neuronio()
{
	for (int i = 0; i < 3; i++)
	{
		peso[i] = ((rand() % 200) - 100) / 100.0;
	}
}

int Neuronio::net(int j)
{
	float y = 0;
	for (int i = 0; i < 3; i++)
	{
		y += exemplo[j][i] * peso[i];
	}
	if (y > 0)
	{
		return 1;
	}
	return 0;
}

void Neuronio::treinamento_pesos(int j)
{
	for (int i = 0; i < 3; i++)
	{
		peso[i] = peso[i] + (N * (exemplo[j][3] - saida) * exemplo[j][i]);
	}
}

void Neuronio::treinamento()
{
	int e = 0;
	bool errou;
	do
	{
		cout << "Epoca(" << e << ")" << endl;
		errou = false;
		for (int i = 0; i < 4; i++)
		{
			saida = net(i);
			if (saida != exemplo[i][3])
			{
				treinamento_pesos(i);
				errou = true;
			}
			cout << "...Pesos: " << peso[0] << " " << peso[1] << " " << peso[2] << endl;
		}
		e++;
	}
	while((e < epocas) && (errou));
}

int Neuronio::executar(int x[2])
{
	cout << "-1 * " << peso[0] << " + " << x[0] << " * " << peso[1] << " + " << x[1] << " + " << peso[2] << endl;
	float y = (-1 * peso[0]) + (x[0] * peso[1]) + (x[1] * peso[2]);
	if (y > 0)
	{
		return 1;
	}
	return 0;
}

int main()
{
	Neuronio n;
	n.treinamento();
	int continuar = 1;
	while (continuar == 1)
	{
		int in[2];
		cout << "x1: ";
		cin >> in[0];
		cout << "x2: ";
		cin >> in[1];
		cout << "retorno: " << n.executar(in) << endl;
		cout << "continuar? ";
		cin >> continuar;
	}
	return 0;
}

Neurônio Artificial para Portas Lógicas em Java

import java.util.*;

public class Perceptron {
	private double[] w = new double[3];
	private double y = 0;
	private double N = 0.1;
	private final int BIAS = -1;
	private final int MAX_EPOCAS = 1000;
	private int operacao = 0;
	private Random rand = new Random();
	Scanner entrada;
	private int[][] e = {
			{ 0, 0, 0, 0, 1, 1, 0 },
			{ 0, 1, 1, 0, 0, 1, 1 },
			{ 1, 0, 1, 0, 0, 1, 1 },
			{ 1, 1, 1, 1, 0, 0, 0 }
			};

	Perceptron(int op) {
		if ((op >= 0) && (op < 5)) {
			operacao = op + 2;
		}
		for (int i = 0; i < 3; i++) {
			w[i] = ((rand.nextInt(20) + 1) / 10) - 1;
		}
		entrada = new Scanner(System.in);
	}

	int executar(int x1, int x2) {
		// Somatorio NET
		y = ((BIAS) * w[0]) + (x1 * w[1]) + (x2 * w[2]);
		// Funcao de Transferencia
		if (y > 0) {
			return 1;
		}
		return 0;
	}

	boolean treinar() {
		boolean treinou;
		int epoca = 0;
		do {
			treinou = true;
			for (int i = 0; i < 4; i++) {
				int s = executar(e[i][0], e[i][1]);
				if (s != e[i][operacao]) {
					corrigirPeso(i, s);
					treinou = false;
				}
			}
			epoca++;
		} while ((treinou == false) && (epoca < MAX_EPOCAS));
		System.out.println("O algoritmo treinou " + epoca + " epocas...");
		if (treinou == false) {
			System.out.println("O algoritmo nao conseguiu convergir...");
		}
		return treinou;
	}

	void corrigirPeso(int exemplo, int saida) {
		w[0] = w[0] + (N * (e[exemplo][operacao] - saida) * (BIAS));
		w[1] = w[1] + (N * (e[exemplo][operacao] - saida) * e[exemplo][0]);
		w[2] = w[2] + (N * (e[exemplo][operacao] - saida) * e[exemplo][1]);
	}

	void testar() {
		boolean sair = false;
		while (!sair) {
			System.out.println("-- Digite 9 para sair --");
			System.out.print("x1 : ");
			int x1 = entrada.nextInt();
			if (x1 == 9) {
				sair = true;
			} else {
				System.out.print("x2 : ");
				int x2 = entrada.nextInt();
				int y = executar(x1, x2);
				System.out.println(" y : " + y);
			}
		}
	}

	public static void main(String[] arguments) {
		boolean erro = false;
		if (arguments.length == 1) {
			int op = Integer.valueOf(arguments[0]);
			erro = ((op < 0) || (op > 4));
			if (!erro) {
				Perceptron p = new Perceptron(op);
				if (p.treinar()) {
					p.testar();
				}
			} 
		} else {
			erro = true;
		}
		if (erro) {
			System.out.println("Use: Perceptron <operacao>");
			System.out.println("operacao:");
			System.out.println("\t0 - ou");
			System.out.println("\t1 - e");
			System.out.println("\t2 - nao ou");
			System.out.println("\t3 - nao e");
			System.out.println("\t4 - ou exclusivo");
		}
	}
}