-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathann_perceptron.py
More file actions
834 lines (664 loc) · 29.2 KB
/
Copy pathann_perceptron.py
File metadata and controls
834 lines (664 loc) · 29.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
# -*- coding: utf-8 -*-
"""ANN-Perceptron
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1lua78DKXivG8TN0MhO4t9j4xUDpJUCy5
# Artificial Neural Network (ANN): Perceptron
**Aluno**: Maruan Biasi El Achkar
**GitHub**: https://github.com/MachineNeyarning/ANN-Perceptron
------------
# 1. Problema das portas lógicas AND, OR
"""
import numpy as np
np.random.seed(42)
class Perceptron: # ERROR DEVE SER PASSADO EM PORCENTAGEM, TIPO 0.1 | 1 | 50 etc.
def __init__(self, input_size, lr=0.01, epochs=1000, d_error=0.1, weights = np.random.randn(2)):
self.lr = lr # learning rate
self.epochs = epochs # quantidade de "rodadas" de treino
self.d_error = d_error / 100.0 # erro desejado por rodada para early stopping, divide por 100 para poder passar input como porcentagem
self.weights = weights # peso, por padrao vai ser aleatorio mas da pra mudar
self.bias = np.random.randn() # bias aleatorio
self.n_epochs = 0 # contador de rodadas
def activation(self, x):
return np.where(x >= 0, 1, -1) # se x for maior ou igual a 0, retorna +1. senao retorna -1
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias # weighted sum das entradas + bias
return self.activation(linear_output)
def fit(self, X, y):
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias
y_pred = self.activation(linear_output)
# ----
update = self.lr * (target - y_pred) # erro vezes learning rate
self.weights += update * xi # ajuste dos pesos
self.bias += update # ajuste do bias
epoch_error += ((target - y_pred) ** 2) / 2.0 # erro quadratico/2
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# calculadora de accuracy, compara a truth table com a predicao
def accuracy(y_true, y_pred):
correct = np.sum(y_true == y_pred)
total = len(y_true)
return (correct / total) * 100
# calculador de error rate
def error_rate(y_true, y_pred):
return 100 - accuracy(y_true, y_pred)
# AND GATE
X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
y_and = np.array([-1, -1, -1, 1])
# OR GATE
X_or = np.array([[0,0], [0,1], [1,0], [1,1]])
y_or = np.array([-1, 1, 1, 1])
# XOR GATE
X_xor = np.array([[0,0], [0,1], [1,0], [1,1]])
y_xor = np.array([-1, 1, 1, -1])
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=1000, d_error=1e-3)
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
# fit OR
model.fit(X_or, y_or)
y_or_predict = model.predict(X_or)
print("-----------------------------------------")
print("- OR GATE")
print(f"- Acurracy: {accuracy(y_or, y_or_predict):.2f}%")
print(f"- Error rate: {error_rate(y_or, y_or_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_or_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
# fit XOR
model.fit(X_xor, y_xor)
y_xor_predict = model.predict(X_xor)
print("-----------------------------------------")
print("- XOR GATE")
print(f"- Acurracy: {accuracy(y_xor, y_xor_predict):.2f}%")
print(f"- Error rate: {error_rate(y_xor, y_xor_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_xor_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
"""# 2. Repita o exercício 1 sobre o problema das portas lógicas utilizando a Regra de Aprendizado Delta"""
import numpy as np
np.random.seed(42)
class Perceptron: # ERROR DEVE SER PASSADO EM PORCENTAGEM, TIPO 0.1 | 1 | 50 etc.
def __init__(self, input_size, lr=0.01, epochs=1000, d_error=0.1, weights = np.random.randn(2)):
self.lr = lr # learning rate
self.epochs = epochs # quantidade de "rodadas" de treino
self.d_error = d_error / 100.0 # erro desejado por rodada para early stopping, divide por 100 para poder passar input como porcentagem
self.weights = weights # peso, por padrao vai ser aleatorio mas da pra mudar
self.bias = np.random.randn() # bias aleatorio
self.n_epochs = 0 # contador de rodadas
def activation(self, x):
return np.where(x >= 0, 1, -1) # se x for maior ou igual a 0, retorna +1. senao retorna -1
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias # weighted sum das entradas + bias
return self.activation(linear_output)
def fit(self, X, y):
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias
y_pred = self.activation(linear_output)
# ----
update = self.lr * (target - y_pred) # erro vezes learning rate
self.weights += update * xi # ajuste dos pesos
self.bias += update # ajuste do bias
epoch_error += ((target - y_pred) ** 2) / 2.0 # erro quadratico/2
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# TREINO COM REGRA DELTA
def fit_delta(self, X, y):
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias # weighted sum das entradas + bias
y_pred = linear_output # saida linear (identidade)
# ----
error = (target - y_pred) # erro (d - o)
update = self.lr * error # gradiente com ativacao identidade (derivada = 1)
self.weights += update * xi # ajuste dos pesos (LMS)
self.bias += update # ajuste do bias
epoch_error += (error ** 2) / 2.0 # erro quadratico/2
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# calculadora de accuracy, compara a truth table com a predicao
def accuracy(y_true, y_pred):
correct = np.sum(y_true == y_pred)
total = len(y_true)
return (correct / total) * 100
# calculador de error rate
def error_rate(y_true, y_pred):
return 100 - accuracy(y_true, y_pred)
# AND GATE
X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
y_and = np.array([-1, -1, -1, 1])
# OR GATE
X_or = np.array([[0,0], [0,1], [1,0], [1,1]])
y_or = np.array([-1, 1, 1, 1])
# XOR GATE
X_xor = np.array([[0,0], [0,1], [1,0], [1,1]])
y_xor = np.array([-1, 1, 1, -1])
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=1000, d_error=1e-3)
# fit AND
model.fit_delta(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Regra Delta")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
# fit OR
model.fit_delta(X_or, y_or)
y_or_predict = model.predict(X_or)
print("-----------------------------------------")
print("- OR GATE - Regra Delta")
print(f"- Acurracy: {accuracy(y_or, y_or_predict):.2f}%")
print(f"- Error rate: {error_rate(y_or, y_or_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_or_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
# fit XOR
model.fit_delta(X_xor, y_xor)
y_xor_predict = model.predict(X_xor)
print("-----------------------------------------")
print("- XOR GATE - Regra Delta")
print(f"- Acurracy: {accuracy(y_xor, y_xor_predict):.2f}%")
print(f"- Error rate: {error_rate(y_xor, y_xor_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_xor_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
"""# 3 Interagir com o código (Utilizando AND gate)
## Alterar a Taxa de Aprendizado (Learning Rate)
Mude o valor de ‘c’ para ver como isso afeta a velocidade de convergência do
algoritmo. Valores comuns são 0.1, 0.01, ou 0.001. Experimente com uma taxa de aprendizado muito alta e muito baixa e observe as
diferenças no comportamento do treinamento.
"""
import numpy as np
np.random.seed(42)
class Perceptron: # ERROR DEVE SER PASSADO EM PORCENTAGEM, TIPO 0.1 | 1 | 50 etc.
def __init__(self, input_size, lr=0.01, epochs=1000, d_error=0.1, weights = np.random.randn(2)):
self.lr = lr # learning rate
self.epochs = epochs # quantidade de "rodadas" de treino
self.d_error = d_error / 100.0 # erro desejado por rodada para early stopping, divide por 100 para poder passar input como porcentagem
self.weights = weights # peso, por padrao vai ser aleatorio mas da pra mudar
self.bias = np.random.randn() # bias aleatorio
self.n_epochs = 0 # contador de rodadas
def activation(self, x):
return np.where(x >= 0, 1, -1) # se x for maior ou igual a 0, retorna +1. senao retorna -1
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias # weighted sum das entradas + bias
return self.activation(linear_output)
def fit(self, X, y):
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias
y_pred = self.activation(linear_output)
# ----
update = self.lr * (target - y_pred) # erro vezes learning rate
self.weights += update * xi # ajuste dos pesos
self.bias += update # ajuste do bias
epoch_error += ((target - y_pred) ** 2) / 2.0 # erro quadratico/2
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# calculadora de accuracy, compara a truth table com a predicao
def accuracy(y_true, y_pred):
correct = np.sum(y_true == y_pred)
total = len(y_true)
return (correct / total) * 100
# calculador de error rate
def error_rate(y_true, y_pred):
return 100 - accuracy(y_true, y_pred)
# AND GATE
X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
y_and = np.array([-1, -1, -1, 1])
##################
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3)
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Learning Rate 0.1")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
#### learning rate 0.01
# treino
model = Perceptron(input_size=2, lr=0.01, epochs=10000, d_error=1e-3)
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Learning Rate 0.01")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
#### learning rate 0.001
# treino
model = Perceptron(input_size=2, lr=0.001, epochs=10000, d_error=1e-3)
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Learning Rate 0.001")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
#### learning rate 0.0000000001
# treino
model = Perceptron(input_size=2, lr=0.0000000001, epochs=50000, d_error=1e-3)
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Learning Rate 0.0000000001")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
"""## Inicialização de Pesos
Experimente diferentes métodos de inicialização de pesos, como definir todos para zero, inicializar com
valores pequenos próximos de zero, ou usar uma distribuição diferente.
"""
import numpy as np
np.random.seed(42)
class Perceptron: # ERROR DEVE SER PASSADO EM PORCENTAGEM, TIPO 0.1 | 1 | 50 etc.
def __init__(self, input_size, lr=0.01, epochs=1000, d_error=0.1, weights = np.random.randn(2)):
self.lr = lr # learning rate
self.epochs = epochs # quantidade de "rodadas" de treino
self.d_error = d_error / 100.0 # erro desejado por rodada para early stopping, divide por 100 para poder passar input como porcentagem
self.weights = weights # peso, por padrao vai ser aleatorio mas da pra mudar
self.bias = np.random.randn() # bias aleatorio
self.n_epochs = 0 # contador de rodadas
def activation(self, x):
return np.where(x >= 0, 1, -1) # se x for maior ou igual a 0, retorna +1. senao retorna -1
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias # weighted sum das entradas + bias
return self.activation(linear_output)
def fit(self, X, y):
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias
y_pred = self.activation(linear_output)
# ----
update = self.lr * (target - y_pred) # erro vezes learning rate
self.weights += update * xi # ajuste dos pesos
self.bias += update # ajuste do bias
epoch_error += ((target - y_pred) ** 2) / 2.0 # erro quadratico/2
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# calculadora de accuracy, compara a truth table com a predicao
def accuracy(y_true, y_pred):
correct = np.sum(y_true == y_pred)
total = len(y_true)
return (correct / total) * 100
# calculador de error rate
def error_rate(y_true, y_pred):
return 100 - accuracy(y_true, y_pred)
# AND GATE
X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
y_and = np.array([-1, -1, -1, 1])
##### PESOS ALEATORIOS
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3, weights=np.random.randn(2))
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Pesos Aleatorios")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
##### PESOS ZERADOS
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3, weights=[0, 0])
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Pesos Zerados")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
##### PESOS 1
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3, weights=[1, 1])
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Pesos 1")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
##### PESOS 2
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3, weights=[2, 2])
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Pesos 2")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
##### PESOS 10
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3, weights=[10, 10])
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Pesos 10")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
##### PESOS 500
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=10000, d_error=1e-3, weights=[500, 500])
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE - Pesos 500")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
"""# Graficos"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
class Perceptron: # ERROR DEVE SER PASSADO EM PORCENTAGEM, TIPO 0.1 | 1 | 50 etc.
def __init__(self, input_size, lr=0.01, epochs=1000, d_error=0.1, weights = np.random.randn(2)):
self.lr = lr # learning rate
self.epochs = epochs # quantidade de "rodadas" de treino
self.d_error = d_error / 100.0 # erro desejado por rodada para early stopping, divide por 100 para poder passar input como porcentagem
self.weights = weights # peso, por padrao vai ser aleatorio mas da pra mudar
self.bias = np.random.randn() # bias aleatorio
self.n_epochs = 0 # contador de rodadas
self.errors = [] # lista para salvar erro quadrático por epoch (mantido)
self.error_rates = [] # lista para salvar error rate (%) por epoch (para os gráficos)
def activation(self, x):
return np.where(x >= 0, 1, -1) # se x for maior ou igual a 0, retorna +1. senao retorna -1
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias # weighted sum das entradas + bias
return self.activation(linear_output)
def fit(self, X, y):
self.errors = [] # reinicia a lista de erros quadráticos por treino
self.error_rates = [] # reinicia a lista de error rate (%) por treino
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias
y_pred = self.activation(linear_output)
# ----
update = self.lr * (target - y_pred) # erro vezes learning rate
self.weights += update * xi # ajuste dos pesos
self.bias += update # ajuste do bias
epoch_error += ((target - y_pred) ** 2) / 2.0 # erro quadratico/2
self.errors.append(epoch_error) # salva erro da epoch (quadrático)
# --- cálculo da error rate (%) ao fim da epoch, usando o estado atual do modelo
y_epoch_pred = self.predict(X)
# função de error rate definida abaixo (100 - accuracy)
self.error_rates.append(100.0 - (np.sum(y == y_epoch_pred) / len(y)) * 100.0)
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# calculadora de accuracy, compara a truth table com a predicao
def accuracy(y_true, y_pred):
correct = np.sum(y_true == y_pred)
total = len(y_true)
return (correct / total) * 100
# calculador de error rate
def error_rate(y_true, y_pred):
return 100 - accuracy(y_true, y_pred)
# AND GATE
X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
y_and = np.array([-1, -1, -1, 1])
# OR GATE
X_or = np.array([[0,0], [0,1], [1,0], [1,1]])
y_or = np.array([-1, 1, 1, 1])
# XOR GATE
X_xor = np.array([[0,0], [0,1], [1,0], [1,1]])
y_xor = np.array([-1, 1, 1, -1])
# treino
model = Perceptron(input_size=2, lr=0.1, epochs=1000, d_error=1e-3)
# fit AND
model.fit(X_and, y_and)
y_and_predict = model.predict(X_and)
print("-----------------------------------------")
print("- AND GATE")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_and_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
errors_and = model.errors
error_rates_and = model.error_rates
# fit OR
model.fit(X_or, y_or)
y_or_predict = model.predict(X_or)
print("-----------------------------------------")
print("- OR GATE")
print(f"- Acurracy: {accuracy(y_or, y_or_predict):.2f}%")
print(f"- Error rate: {error_rate(y_or, y_or_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_or_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
errors_or = model.errors
error_rates_or = model.error_rates
# fit XOR
model.fit(X_xor, y_xor)
y_xor_predict = model.predict(X_xor)
print("-----------------------------------------")
print("- XOR GATE")
print(f"- Acurracy: {accuracy(y_xor, y_xor_predict):.2f}%")
print(f"- Error rate: {error_rate(y_xor, y_xor_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Predictions:", y_xor_predict)
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
errors_xor = model.errors
error_rates_xor = model.error_rates
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
axes[0].plot(error_rates_and)
axes[0].set_title("AND - Error rate por época")
axes[0].set_xlabel("Épocas")
axes[0].set_ylabel("Error rate (%)")
axes[0].grid(True)
axes[1].plot(error_rates_or)
axes[1].set_title("OR - Error rate por época")
axes[1].set_xlabel("Épocas")
axes[1].set_ylabel("Error rate (%)")
axes[1].grid(True)
axes[2].plot(error_rates_xor)
axes[2].set_title("XOR - Error rate por época")
axes[2].set_xlabel("Épocas")
axes[2].set_ylabel("Error rate (%)")
axes[2].grid(True)
fig.suptitle("Perceptron - Error rate (%) por época")
fig.tight_layout()
plt.show()
"""# Teste com Dataset mais Complexo | Sonar (Rocks vs Mines)
### Fonte do Dataset:
https://archive.ics.uci.edu/dataset/151/connectionist+bench+sonar+mines+vs+rocks
### Descricao do Dataset:
The task is to train a network to discriminate between sonar signals bounced off a metal cylinder and those bounced off a roughly cylindrical rock.
"""
!pip install ucimlrepo
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from ucimlrepo import fetch_ucirepo
np.random.seed(42)
class Perceptron: # ERROR DEVE SER PASSADO EM PORCENTAGEM, TIPO 0.1 | 1 | 50 etc.
def __init__(self, input_size, lr=0.01, epochs=1000, d_error=0.1, weights = np.random.randn(2)):
self.lr = lr # learning rate
self.epochs = epochs # quantidade de "rodadas" de treino
self.d_error = d_error / 100.0 # erro desejado por rodada para early stopping, divide por 100 para poder passar input como porcentagem
self.weights = weights # peso, por padrao vai ser aleatorio mas da pra mudar
self.bias = np.random.randn() # bias aleatorio
self.n_epochs = 0 # contador de rodadas
self.errors = [] # guardar taxa de erro
def activation(self, x):
return np.where(x >= 0, 1, -1) # se x for maior ou igual a 0, retorna +1. senao retorna -1
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias # weighted sum das entradas + bias
return self.activation(linear_output)
def fit(self, X, y):
for epoch in range(self.epochs): # rodadas
epoch_error = 0.0 # acumula erro (d - o)^2 / 2
for xi, target in zip(X, y):
linear_output = np.dot(xi, self.weights) + self.bias
y_pred = self.activation(linear_output)
# ----
update = self.lr * (target - y_pred) # erro vezes learning rate
self.weights += update * xi # ajuste dos pesos
self.bias += update # ajuste do bias
epoch_error += ((target - y_pred) ** 2) / 2.0 # erro quadratico/2
# guarda taxa de erro em porcentagem
y_pred_epoch = self.predict(X)
error_rate_epoch = 100 - (np.sum(y_pred_epoch == y) / len(y)) * 100
self.errors.append(error_rate_epoch)
if epoch_error < self.d_error: # early stopping
self.n_epochs = epoch + 1 # contador de rodadas
break
else:
self.n_epochs = self.epochs
# calculadora de accuracy, compara a truth table com a predicao
def accuracy(y_true, y_pred):
correct = np.sum(y_true == y_pred)
total = len(y_true)
return (correct / total) * 100
# calculador de error rate
def error_rate(y_true, y_pred):
return 100 - accuracy(y_true, y_pred)
# --------------------------------------------------------------------------------- #
# baixar dataset SONAR da UCI
connectionist_bench_sonar_mines_vs_rocks = fetch_ucirepo(id=151)
X = connectionist_bench_sonar_mines_vs_rocks.data.features.to_numpy(dtype=float)
y_raw = connectionist_bench_sonar_mines_vs_rocks.data.targets.values.ravel()
y = np.where(y_raw == 'M', 1, -1) # M = +1, R = -1
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.30, random_state=42, stratify=y
)
mu = X_train.mean(axis=0)
sigma = X_train.std(axis=0) + 1e-9
X_train_std = (X_train - mu) / sigma
X_test_std = (X_test - mu) / sigma
model = Perceptron(
input_size=60,
lr=0.01,
epochs=10000,
d_error=0.1,
weights=np.random.randn(60)
)
model.fit(X_train_std, y_train)
y_pred_train = model.predict(X_train_std)
y_pred_test = model.predict(X_test_std)
print("-----------------------------------------")
print("- SONAR (Rocks vs Mines)")
print(f"- Acurracy: {accuracy(y_and, y_and_predict):.2f}%")
print(f"- Error rate: {error_rate(y_and, y_and_predict):.2f}%")
print(f"- Rodadas necessárias: {model.n_epochs}")
print("- Weights:", model.weights)
print("- Bias:", model.bias)
print("-----------------------------------------")
print("--- Teste ---")
print(f"- Acurracy: {accuracy(y_test, y_pred_test):.2f}%")
print(f"- Error rate: {error_rate(y_test, y_pred_test):.2f}%")
# gfrafico
plt.figure(figsize=(8,5))
plt.plot(range(1, len(model.errors)+1), model.errors, marker="o")
plt.xlabel("Época")
plt.ylabel("Taxa de Erro (%)")
plt.title("Evolução da Taxa de Erro por Época (Treino)")
plt.grid(True)
plt.show()