XOR Model Implementation using tensorflow Library in Machine Learning

What does XOR Gate mean?


The XOR ( exclusive-OR ) gate acts in the same way as the logical "either/or." The output is "true" if either, but not both, of the inputs, are "true." The output is "false" if both inputs are "false" or if both inputs are "true." Another way of looking at this circuit is to observe that the output is 1 if the inputs are different, but 0 if the inputs are the same.

Here we are using a machine learning approach to find it's output.

import matplotlib.pyplot as plt
import tensorflow as tf

w1=tf.Variable([.5],tf.float32)
w2=tf.Variable([-.5],tf.float32)

x1=tf.placeholder(tf.float32)
x2=tf.placeholder(tf.float32)
xor_model=w1*x1+w2*x2
y=tf.placeholder(tf.float32)
sq_delta=tf.square(xor_model-y)
loss=tf.reduce_sum(sq_delta)
init=tf.global_variables_initializer()
optimizer=tf.train.GradientDescentOptimizer(0.01)
train =optimizer.minimize(loss)
sess=tf.Session()
sess.run(init)
for i in range(10000):
    sess.run(train,{x1:[0,1,0,1],x2:[0,0,1,1],y:[0,1,1,1]})
l=sess.run(xor_model,{x1:[0,1,0,1],x2:[0,0,1,1]})
print(l)
for i in range(10000):
    sess.run(train,{x1:[0,1,0,1],x2:[0,0,1,1],y:[0,0,0,1]})
l2=sess.run(xor_model,{x1:[0,1,0,1],x2:[0,0,1,1]})
print(l2)
l1=[]
for i in l:
    if(i>0.5):
        l1.extend([1])
    else:
        l1.extend([0])
print(l1)
l3=[]
for i in l2:
    if(i>0.5):
        l3.extend([1])
    else:
        l3.extend([0])
print(l3)
for i in range(10000):
    sess.run(train,{x1:l1,x2:l3,y:[0,1,1,0]})
l4=sess.run(xor_model,{x1:l1,x2:l3})
l5=[]
for i in l4:
    if(i>0.5):
        l5.extend([1])
    else:
        l5.extend([0])
print(l5)

In above example list named 'L1' store the result of 'OR' gate. List 'L3' store the result of  'AND' gate.
List 'L5' store the result of 'AND' operation between 'L1' and 'L3' and produce a final result for 'XOR' model.

Output:-




Comments