与门(AND gate) 的Python 实现
使用Python 定义一个感知机,处理与门(AND gate)问题。
形式一(带有权重形式):
y = { 0 ( w 1 x 1 + w 2 x 2 ⩽ θ ) 1 ( w 1 x 1 + w 2 x 2 > θ ) y=\begin{cases} \begin{matrix} 0& \left( w_1x_1+w_2x_2\leqslant \theta \right)\\ \end{matrix}\\ \begin{matrix} 1& \left( w_1x_1+w_2x_2>\theta \right)\\ \end{matrix}\\ \end{cases} y={0(w1x1+w2x2⩽θ)1(w1x1+w2x2>θ)
定义一个接收 两个参数 的 AND 函数。
def AND(x_1,x_2):
w_1,w_2,theta=0.5,0.5,0.7
tmp=x_1*w_1+x_2*w_2
if tmp<=theta:
return 0
elif tmp>theta:
return 1
输入数据,检验结果:
import numpy as np
x_1=np.array([0,1,0,1])
x_2=np.array([0,0,1,1])
for i in range(len(x_1)):
Name="AND("+str(x_1[i])+","+str(x_2[i])+"):"
Tmp=AND(x_1[i],x_2[i])
print(Name,str(Tmp))
# 运行结果如下:
"""
AND(0,0): 0
AND(1,0): 0
AND(0,1): 0
AND(1,1): 1
"""
形式二(带有权重及偏置形式):
将 参数 θ \theta θ 修改为 − b -b −b 即另一种常用形式:
y = { 0 ( b + w 1 x 1 + w 2 x 2 ⩽ 0 ) 1 ( b + w 1 x 1 + w 2 x 2 > 0 ) y=\begin{cases} \begin{matrix} 0& \left( b+w_1x_1+w_2x_2\leqslant 0 \right)\\ \end{matrix}\\ \begin{matrix} 1& \left( b+w_1x_1+w_2x_2>0 \right)\\ \end{matrix}\\ \end{cases} y={0(b+w1x1+w2x2⩽0)1(b+w1x1+w2x2>0)
使用 权重和偏置形式 重新定义 AND
函数:
import numpy as np
def AND(x_1,x_2):
w=np.array([0.5,0.5])
b=-0.7
tmp=np.sum(w*x)+b
if tmp<=0:
return 0
elif tmp>0:
return 1
输入数据,验证结果:
x=np.array([[0,0],[0,1],[1,0],[1,1]])
for i in range(len(x)):
Name="AND("+str(x[i,0])+","+str(x[i,1])+")"
Value=AND(x[i,0],x[i,1])
print(Name,str(Value))
# 运行结果如下:
"""
AND(0,0) 1
AND(0,1) 1
AND(1,0) 1
AND(1,1) 1
"""