2 位二进制输入异或逻辑门感知器算法的实现
在机器学习领域,感知器是一种用于二进制分类器的监督学习算法。感知器模型实现以下功能:
对于权重向量和偏差参数的特定选择,模型预测相应输入向量的输出。
异或逻辑函数真值表为 2 位二进制变量 ,即输入向量和对应的输出–
Zero | Zero | Zero |
Zero | one | one |
one | Zero | one |
one | one | Zero |
我们可以观察到, 设计感知器网络:
-
Step1: Now for the corresponding weight vector of the input vector to the AND and OR node, the associated Perceptron Function can be defined as:
-
Step2: The output from the AND node will be inputed to the NOT node with weight and the associated Perceptron Function can be defined as:
-
Step3: The output from the OR node and the output from NOT node as mentioned in Step2 will be inputed to the AND node with weight . Then the corresponding output is the final output of the XOR logic function. The associated Perceptron Function can be defined as:
实施时,权重参数考虑为,偏差参数为。
Python 实现:
# importing Python library
import numpy as np
# define Unit Step Function
def unitStep(v):
if v >= 0:
return 1
else:
return 0
# design Perceptron Model
def perceptronModel(x, w, b):
v = np.dot(w, x) + b
y = unitStep(v)
return y
# NOT Logic Function
# wNOT = -1, bNOT = 0.5
def NOT_logicFunction(x):
wNOT = -1
bNOT = 0.5
return perceptronModel(x, wNOT, bNOT)
# AND Logic Function
# here w1 = wAND1 = 1,
# w2 = wAND2 = 1, bAND = -1.5
def AND_logicFunction(x):
w = np.array([1, 1])
bAND = -1.5
return perceptronModel(x, w, bAND)
# OR Logic Function
# w1 = 1, w2 = 1, bOR = -0.5
def OR_logicFunction(x):
w = np.array([1, 1])
bOR = -0.5
return perceptronModel(x, w, bOR)
# XOR Logic Function
# with AND, OR and NOT
# function calls in sequence
def XOR_logicFunction(x):
y1 = AND_logicFunction(x)
y2 = OR_logicFunction(x)
y3 = NOT_logicFunction(y1)
final_x = np.array([y2, y3])
finalOutput = AND_logicFunction(final_x)
return finalOutput
# testing the Perceptron Model
test1 = np.array([0, 1])
test2 = np.array([1, 1])
test3 = np.array([0, 0])
test4 = np.array([1, 0])
print("XOR({}, {}) = {}".format(0, 1, XOR_logicFunction(test1)))
print("XOR({}, {}) = {}".format(1, 1, XOR_logicFunction(test2)))
print("XOR({}, {}) = {}".format(0, 0, XOR_logicFunction(test3)))
print("XOR({}, {}) = {}".format(1, 0, XOR_logicFunction(test4)))
Output:
XOR(0, 1) = 1
XOR(1, 1) = 0
XOR(0, 0) = 0
XOR(1, 0) = 1
这里,根据真值表,每个测试输入的模型预测输出()与异或逻辑门常规输出()精确匹配。 验证了异或门感知器算法的正确实现。
版权属于:月萌API www.moonapi.com,转载请注明出处