2 位二进制输入与门感知器算法的实现

原文:https://www . geeksforgeeks . org/2 位二进制输入的感知器和逻辑门算法的实现/

在机器学习领域,感知器是一种用于二进制分类器的监督学习算法。感知器模型实现以下功能:

[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \ \text { where } \Theta(v)=\left{\begin{array}{cc} 1 & \text { if } v \geqslant 0 \ 0 & \text { otherwise } \end{array}\right. \end{array} ]

对于权重向量$\boldsymbol{w}$和偏差参数$\boldsymbol{b}$的特定选择,模型预测相应输入向量$\boldsymbol{x}$的输出$\boldsymbol{\hat{y}}$

2 位二进制变量 的逻辑函数真值表,即输入向量$\boldsymbol{x} : (\boldsymbol{x_{1}}, \boldsymbol{x_{2}})$和相应的输出$\boldsymbol{y}$

$\boldsymbol{x_{1}}$ $\boldsymbol{x_{2}}$ $\boldsymbol{y}$
Zero Zero Zero
Zero one Zero
one Zero Zero
one one one

现在对于输入向量$\boldsymbol{x} : (\boldsymbol{x_{1}}, \boldsymbol{x_{2}})$的相应权重向量$\boldsymbol{w} : (\boldsymbol{w_{1}}, \boldsymbol{w_{2}})$,关联的感知器函数可以定义为:

[$\boldsymbol{\hat{y}} = \Theta\left(w_{1} x_{1}+w_{2} x_{2}+b\right)$]

为实现,考虑的权重参数为$\boldsymbol{w_{1}} = 1, \boldsymbol{w_{2}} = 1$,偏差参数为$\boldsymbol{b} = -1.5$

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

# AND Logic Function
# w1 = 1, w2 = 1, b = -1.5
def AND_logicFunction(x):
    w = np.array([1, 1])
    b = -1.5
    return perceptronModel(x, w, b)

# 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("AND({}, {}) = {}".format(0, 1, AND_logicFunction(test1)))
print("AND({}, {}) = {}".format(1, 1, AND_logicFunction(test2)))
print("AND({}, {}) = {}".format(0, 0, AND_logicFunction(test3)))
print("AND({}, {}) = {}".format(1, 0, AND_logicFunction(test4)))

Output:

AND(0, 1) = 0
AND(1, 1) = 1
AND(0, 0) = 0
AND(1, 0) = 0

这里,根据 2 位二进制输入的真值表,每个测试输入的模型预测输出($\boldsymbol{\hat{y}}$)与“与”逻辑门常规输出($\boldsymbol{y}$)完全匹配。 由此验证了“与”逻辑门的感知器算法是正确实现的。