Redes Neurais Artificiais
De Aulas
Links relacionados: Inteligência Artificial
Neurônio Artificial Portas Lógicas em Python
1"""
2PROGRAM: Perceptron
3author: Saulo Popov Zambiasi
4created: 2019.05.17
5modified: 2022.04.28
6"""
7from random import *
8
9
10class Perceptron:
11 N = 0.01
12 epoch = 100
13 weight = []
14 option = 0
15 # example by columns
16 # bias (-1) | x1 | x2 | y_or | y_not_or | y_and | y_not_and | y_xor
17 example = [
18 [-1, 0, 0, 0, 1, 0, 1, 0],
19 [-1, 0, 1, 1, 0, 0, 1, 1],
20 [-1, 1, 0, 1, 0, 0, 1, 1],
21 [-1, 1, 1, 1, 0, 1, 0, 0]
22 ]
23
24 def __init__(self, option):
25 self.option = option
26 if self.option < 0 or self.option > 4:
27 self.option = 0
28 self.option += 3
29 for i in range(3):
30 self.weight += [randint(1, 100) / 100.0]
31
32 def adjust_weight(self, e, out):
33 for i in range(3):
34 self.weight[i] += self.N * \
35 (self.example[e][self.option] - out) * self.example[e][i]
36
37 def training(self):
38 trained = False
39 epoch = 0
40 while not trained and epoch < self.epoch:
41 trained = True
42 for i in range(4):
43 y = self.net(self.example[i][1], self.example[i][2])
44 if y != self.example[i][self.option]:
45 self.adjust_weight(i, y)
46 trained = False
47 epoch += 1
48 if trained:
49 print("Trained in", epoch, "epochs.")
50 return True
51 else:
52 print("There was not possible to learn.")
53 return False
54
55 def net(self, x1, x2):
56 y = (-1 * self.weight[0]) + \
57 (x1 * self.weight[1]) + (x2 * self.weight[2])
58 if y > 0:
59 return 1
60 return 0
61
62
63# MAIN PROGRAM -----------------------------------------
64def main():
65 print("PERCEPTRON: training to logic ports")
66 o = 0
67 while o != 9:
68 print("Choose operation [ 0: OR | 1: NOT OR |",
69 "2: AND | 3: NOT AND | 4: XOR ] - Or 9 to exit")
70 o = int(input("operation: "))
71 if o != 9:
72 neuron = Perceptron(o)
73 if neuron.training():
74 exit_loop = False
75 while not exit_loop:
76 print("-- Type 0 or 1 - Or 9 to other training")
77 x1 = int(input("x1: "))
78 if x1 != 9:
79 x2 = int(input("x2: "))
80 y = neuron.net(x1, x2)
81 print("y = ", y)
82 else:
83 exit_loop = True
84 print("Terminated...")
85
86
87# -------------------------------------------------------
88if __name__ == "__main__":
89 main()
Neurônio Artificial Porta OU em C++11
1#include <iostream>
2
3using namespace std;
4
5class Neuronio
6{
7private:
8 int saida;
9 float N = 0.01;
10 int epocas = 100;
11 float peso[3];
12 int exemplo[4][4]
13 {
14 { -1, 0, 0, 0 },
15 { -1, 0, 1, 1 },
16 { -1, 1, 0, 1 },
17 { -1, 1, 1, 1 }
18 };
19public:
20 Neuronio();
21 void transferencia();
22 void treinamento_pesos(int j);
23 void treinamento();
24 int net(int j);
25 int executar(int x[2]);
26};
27
28Neuronio::Neuronio()
29{
30 for (int i = 0; i < 3; i++)
31 {
32 peso[i] = ((rand() % 200) - 100) / 100.0;
33 }
34}
35
36int Neuronio::net(int j)
37{
38 float y = 0;
39 for (int i = 0; i < 3; i++)
40 {
41 y += exemplo[j][i] * peso[i];
42 }
43 if (y > 0)
44 {
45 return 1;
46 }
47 return 0;
48}
49
50void Neuronio::treinamento_pesos(int j)
51{
52 for (int i = 0; i < 3; i++)
53 {
54 peso[i] = peso[i] + (N * (exemplo[j][3] - saida) * exemplo[j][i]);
55 }
56}
57
58void Neuronio::treinamento()
59{
60 int e = 0;
61 bool errou;
62 do
63 {
64 cout << "Epoca(" << e << ")" << endl;
65 errou = false;
66 for (int i = 0; i < 4; i++)
67 {
68 saida = net(i);
69 if (saida != exemplo[i][3])
70 {
71 treinamento_pesos(i);
72 errou = true;
73 }
74 cout << "...Pesos: " << peso[0] << " " << peso[1] << " " << peso[2] << endl;
75 }
76 e++;
77 }
78 while((e < epocas) && (errou));
79}
80
81int Neuronio::executar(int x[2])
82{
83 cout << "-1 * " << peso[0] << " + " << x[0] << " * " << peso[1] << " + " << x[1] << " + " << peso[2] << endl;
84 float y = (-1 * peso[0]) + (x[0] * peso[1]) + (x[1] * peso[2]);
85 if (y > 0)
86 {
87 return 1;
88 }
89 return 0;
90}
91
92int main()
93{
94 Neuronio n;
95 n.treinamento();
96 int continuar = 1;
97 while (continuar == 1)
98 {
99 int in[2];
100 cout << "x1: ";
101 cin >> in[0];
102 cout << "x2: ";
103 cin >> in[1];
104 cout << "retorno: " << n.executar(in) << endl;
105 cout << "continuar? ";
106 cin >> continuar;
107 }
108 return 0;
109}
Neurônio Artificial para Portas Lógicas em Java
1import java.util.*;
2
3public class Perceptron {
4 private double[] w = new double[3];
5 private double y = 0;
6 private double N = 0.1;
7 private final int BIAS = -1;
8 private final int MAX_EPOCAS = 1000;
9 private int operacao = 0;
10 private Random rand = new Random();
11 Scanner entrada;
12 private int[][] e = {
13 { 0, 0, 0, 0, 1, 1, 0 },
14 { 0, 1, 1, 0, 0, 1, 1 },
15 { 1, 0, 1, 0, 0, 1, 1 },
16 { 1, 1, 1, 1, 0, 0, 0 }
17 };
18
19 Perceptron(int op) {
20 if ((op >= 0) && (op < 5)) {
21 operacao = op + 2;
22 }
23 for (int i = 0; i < 3; i++) {
24 w[i] = ((rand.nextInt(20) + 1) / 10) - 1;
25 }
26 entrada = new Scanner(System.in);
27 }
28
29 int executar(int x1, int x2) {
30 // Somatorio NET
31 y = ((BIAS) * w[0]) + (x1 * w[1]) + (x2 * w[2]);
32 // Funcao de Transferencia
33 if (y > 0) {
34 return 1;
35 }
36 return 0;
37 }
38
39 boolean treinar() {
40 boolean treinou;
41 int epoca = 0;
42 do {
43 treinou = true;
44 for (int i = 0; i < 4; i++) {
45 int s = executar(e[i][0], e[i][1]);
46 if (s != e[i][operacao]) {
47 corrigirPeso(i, s);
48 treinou = false;
49 }
50 }
51 epoca++;
52 } while ((treinou == false) && (epoca < MAX_EPOCAS));
53 System.out.println("O algoritmo treinou " + epoca + " epocas...");
54 if (treinou == false) {
55 System.out.println("O algoritmo nao conseguiu convergir...");
56 }
57 return treinou;
58 }
59
60 void corrigirPeso(int exemplo, int saida) {
61 w[0] = w[0] + (N * (e[exemplo][operacao] - saida) * (BIAS));
62 w[1] = w[1] + (N * (e[exemplo][operacao] - saida) * e[exemplo][0]);
63 w[2] = w[2] + (N * (e[exemplo][operacao] - saida) * e[exemplo][1]);
64 }
65
66 void testar() {
67 boolean sair = false;
68 while (!sair) {
69 System.out.println("-- Digite 9 para sair --");
70 System.out.print("x1 : ");
71 int x1 = entrada.nextInt();
72 if (x1 == 9) {
73 sair = true;
74 } else {
75 System.out.print("x2 : ");
76 int x2 = entrada.nextInt();
77 int y = executar(x1, x2);
78 System.out.println(" y : " + y);
79 }
80 }
81 }
82
83 public static void main(String[] arguments) {
84 boolean erro = false;
85 if (arguments.length == 1) {
86 int op = Integer.valueOf(arguments[0]);
87 erro = ((op < 0) || (op > 4));
88 if (!erro) {
89 Perceptron p = new Perceptron(op);
90 if (p.treinar()) {
91 p.testar();
92 }
93 }
94 } else {
95 erro = true;
96 }
97 if (erro) {
98 System.out.println("Use: Perceptron <operacao>");
99 System.out.println("operacao:");
100 System.out.println("\t0 - ou");
101 System.out.println("\t1 - e");
102 System.out.println("\t2 - nao ou");
103 System.out.println("\t3 - nao e");
104 System.out.println("\t4 - ou exclusivo");
105 }
106 }
107}