首页 > 解决方案 > How to implementing neural networks for logic gates?

问题描述

I need to implement neural networks for logic gates. I found something what looks like it might be helpful for me: Code below: enter image description here

And i don't even know how it works, based on which data i can draw that diagram? I am really interesting in NAND logic gate

标签: pythonlogic

解决方案


NAND gate truth table is at below,

Input Output
-------------
00  |  1
01  |  1
10  |  1
11  |  0

Basically, the neural networks contain layers. Every layers contain neurons. Each input connects these neurons with weights. Therefore, in basic manner, you should think how to arrange weights to get desired result. Assuming activation function is sigmoid, w0 = -3, w1 = 2 and w2 = 2 gives us AND while w0 = 3 , w1 = -2, w2 = -2 gives as NAND logic gate. You can check the code below.

 import math
from colorama import Back
def sigmoid(x):
  return 1 / (1 + math.exp(-x))

## AND ##

w0 = -3
w1 = 2
w2 = 2

a_input = [0,1,0,1]
b_input = [1,0,0,1]

print('\033[1;34;35m'+ '#### AND GATE #####')
for input_1,input_2 in zip(a_input,b_input):
    print('\033[1;34;32m' + str(input_1) + str(input_2))
    result = w0 + w1 * input_1 + w2*input_2


    if sigmoid(result) < 0.5:
        print('\033[1;34;31m' + "Negative Class or 0" + Back.RESET)
    if sigmoid(result) > 0.5:
        print('\033[1;34;34m' + "Positive Class or 1" + Back.RESET)

print('\033[1;34;35m'+ '#### NAND GATE #####')
## NAND ##

w0_0 = 3
w1_1= -2
w2_2 = -2

a_input = [0,1,0,1]
b_input = [1,0,0,1]

for input_1,input_2 in zip(a_input,b_input):
    print('\033[1;34;32m' + str(input_1) + str(input_2))
    result = w0_0 + w1_1 * input_1 + w2_2*input_2


    if sigmoid(result) < 0.5:
        print('\033[1;34;31m' + "Negative Class or 0" + Back.RESET)
    if sigmoid(result) > 0.5:
        print('\033[1;34;34m' + "Positive Class or 1" + Back.RESET)


#### AND GATE #####
01
Negative Class or 0
10
Negative Class or 0
00
Negative Class or 0
11
Positive Class or 1
#### NAND GATE #####
01
Positive Class or 1
10
Positive Class or 1
00
Positive Class or 1
11
Negative Class or 0

For further information, you should glance over : https://medium.com/analytics-vidhya/implementing-logic-gates-using-neural-networks-part-1-f8c0d3c48332


推荐阅读